def start_trading(self, Tmode=False): global ml now = datetime.datetime.now(TZ) Notify.info("Trading has begun") self.logger.info("Trading has begun") count = 1 if not Tmode: while now.time() < self.pack_up or self.is_dev_mode: try: for trader in self.traders: trader.run() self.logger.info(f"Completed round {count}") sleep(self.period) except Exception as e: Notify.fatal("Trading has been aborted") self.logger.critical( "Trade abort due to unexpected error : ", e) quit(0) finally: now = datetime.datetime.now(TZ) count += 1 else: Notify.info("Confirming access to live stock price...") self.logger.info("Confirming access to live stock price...") for trader in self.traders: try: get_live_price(trader.ticker) except Exception as e: Notify.fatal( "Error in fetching live stock price. Aborting") self.logger.critical( "Error in fetching live stock price : ", e)
def start_trading(self, Tmode=False): global ml now = datetime.datetime.now(TZ) Notify.info("Trading has begun") ml.info("Trading has begun") count = 1 if not Tmode: while now.time() < PACK_UP or DEV_MODE: try: for trader in self.traders: trader.run() ml.info("Completed round #", count) sleep(PERIOD_INTERVAL) except Exception as e: Notify.fatal("Trading has been aborted") ml.critical("Trade abort due to unexpected error : ", e) quit(0) finally: now = datetime.datetime.now(TZ) count += 1 else: Notify.info("Confirming access to live stock price...") ml.info("Confirming access to live stock price...") for trader in self.traders: try: get_live_price(trader.ticker) except Exception as e: Notify.fatal( "Error in fetching live stock price. Aborting") ml.critical("Error in fetching live stock price : ", e)
def lineup_traders(self, tickers): global ml count = 1 for ticker in tickers: self.traders.append(Trader(count, ticker, self.account)) Notify.info(f"Successfully connected Trader #{count} to {ticker}", delay=0.01) count += 1 self.logger.info("Trader lineup complete") print("")
def init_traders(self, Tmode=False): global ml Notify.info("Traders are in Observation phase") self.logger.info("Traders entered Observation Phase") if not Tmode: self.print_progress_bar(0, 80, prefix='Progress:', suffix='Complete', length=40) for i in range(DATA_LIMIT): for trader in self.traders: trader.get_initial_data() self.print_progress_bar(i + 1, 80, prefix='\tProgress:', suffix='Complete', length=40) sleep(self.period) Notify.info("\tStatus : Complete") self.logger.info("Observation Phase complete") print("")
def __del__(self): # load previous day's data prev_data = json.loads(open("..\\user_info.json").read()) username = prev_data['username'] # debug account_balance_prev = prev_data["account_balance"] # get new data from trader's database account_balance_new = account_balance_prev * ( 1 - self.feasible_percent) + self.account profit = account_balance_new - account_balance_prev # set up new data new_data = dict() new_data['username'] = username new_data["account_balance"] = account_balance_new new_data["stocks_to_sell"] = dict() new_data["stocks_to_buy_back"] = dict() # grab data from trader database for trader in self.traders: # check owned stocks if trader.IN_LONG_TRADE: new_data["stocks_to_sell"][trader.ticker] = { "buffer_price": trader.price_for_buffer } # check owed stocks if trader.IN_SHORT_TRADE: new_data["stocks_to_buy_back"][trader.ticker] = { "buffer_price": trader.price_for_buffer } # save trader database in respective files del trader # save master database with open("..\\user_info.json", "w") as fp: fp.write(json.dumps(new_data, indent=4)) # output profit Notify.info(f"\n\nNet Profit : $ {profit} \n") self.logger.info(f"\n\nNet Profit : $ {profit} \n") Notify.info(f'Stocks owned : {len(new_data["stocks_to_sell"])}') self.logger.info(f'Stocks owned : {len(new_data["stocks_to_sell"])}') Notify.info(f'Stocks sold : {len(new_data["stocks_to_buy_back"])}') self.logger.info( f'Stocks sold : {len(new_data["stocks_to_buy_back"])}')
def main(): """ Main Function """ # make sure that market is open if not DEV_MODE and CHECK_MARKET: if args.t: Notify.for_input("Check Market? (y/n) : ") confirm = input().strip().lower() print("") else: confirm = "y" if is_open() or confirm == "n": pass else: Notify.fatal("Market is closed at the moment, aborting.") print("") quit(0) # else: # Notify.warn("You are in developer mode, if not intended, please quit.") # Notify.info("Press ENTER to continue, Ctrl+C to quit") # input() # allow market to settle to launch Ichimoku strategy if IDLE_DELAY == 0: Notify.info("Skipped Idle phase") else: Notify.info( f"Entered Idle phase at {datetime.datetime.now(TZ).strftime('%H:%M:%S')}" ) master_logger.info(f"Entered Idle phase") Notify.info(f"\tExpected release : after {IDLE_DELAY // 60} minutes") print("") sleep(IDLE_DELAY) master_logger.info("Idle phase complete") # find relevant stocks to focus on Notify.info("Finding stocks to focus on .....") try: stocks_to_focus = fetch_stocks() except Exception as ex: print(f'Exception was {ex}') stocks_to_focus = [] Notify.fatal( "Could not fetch relevant stocks. Verify Network connection and check logs for details." ) master_logger.critical( "Could not fetch relevant stocks, Most possibly due to network error" ) quit(0) Notify.info("\tStatus : Complete") master_logger.info("Successfully found relevant stocks") print("") # setup traders and begin trade master = Master(PERIOD_INTERVAL, master_logger, FEASIBLE_PERCENT, ACCOUNT, PACK_UP, DEV_MODE) master.validate_repo() master.lineup_traders(stocks_to_focus) master.init_traders(args.t) master.start_trading(args.t) # trading in over by this point Notify.info("Trading complete") master_logger.info("Trading complete") # initiate packup del master quit(0)