Exemple #1
0
    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)
Exemple #2
0
    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)
Exemple #3
0
 def get_initial_data(self):
     try:
         self.price.append(get_live_price(self.ticker))
         self.logger.debug("Successfully fetched live price")
     except SysCallError:
         Notify.warn(
             f"[Trader #{self.number} {self.ticker}]: Encountered SysCallError while initialising parameters, trying recursion"
         )
         self.logger.warning("Encountered SysCallError, trying recursion")
         self.get_initial_data()
     except Exception as e:
         Notify.warn(
             f"[Trader #{self.number} {self.ticker}]: Exception in getting initial data, trying recursion"
         )
         self.logger.error("Trying recursion due to uncommon Exception : ",
                           e)
         self.get_initial_data()
Exemple #4
0
 def update_price(self):
     try:
         new_price = get_live_price(self.ticker)
         self.price.append(new_price)
         self.logger.info(
             "Successfully fetched price, local database updated")
     except SysCallError:
         Notify.warn(
             f"[Trader #{self.number} {self.ticker}] : Encountered SysCallError in updating price, trying recursion"
         )
         self.logger.warning(
             "Encountered SysCallError while fetching live price, trying recursion"
         )
         self.update_price()
     except Exception as e:
         Notify.warn(
             f"[Trader #{self.number} {self.ticker}] : Exception in updating price, trying recursion"
         )
         self.logger.error(
             "Trying recursion, encountered uncommon exception : ", e)
         self.update_price()
Exemple #5
0
def fetch_stocks():
    """
        Find relevant stocks to focus on for trading
    Returns:
        Deque of tickers of relevant stocks

    """

    global ml

    # url to grab data from
    url = f'https://finance.yahoo.com/gainers?count={NUM_OF_STOCKS_TO_SEARCH}'
    # request header
    headers = {
        'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
    }
    try:
        src = requests.get(url=url, headers=headers).content
    except Exception as e:
        src = None
        Notify.fatal(
            "Trade abort due to unexpected error. Check activity log for details"
        )
        master_logger.critical("Encountered error : ", e)
        quit(0)
    # soup object of source code
    soup = BeautifulSoup(src, "html.parser")
    rows = soup.find('table').tbody.find_all('tr')
    # initialisations
    stocks_temp = dict()
    # check previous day's closing status
    prev_data = json.loads(open("database/user_info.json").read())
    get_sells(stocks_temp, prev_data, "stocks_to_sell")
    get_buys(stocks_temp, prev_data, "stocks_to_buy_back")

    # set counter
    count = len(stocks_temp)
    stocks = deque()
    # iterate over rows in web page
    for tr in rows:
        # exit if
        if count == NUM_OF_STOCKS_TO_FOCUS:
            break
        else:
            row_data = tr.find_all('td')
            ticker = row_data[0].text.strip()
            price = get_live_price(ticker)

            # split ticker for checking if same stock of different stock exchange is selected or not
            stock_name = ""
            stock_ex = "US"
            stock_name = ticker  #ticker.split(".")
            if price >= PENNY_STOCK_THRESHOLD and stock_name not in stocks_temp:
                stocks_temp[stock_name] = stock_ex
                count += 1
    # get back ticker
    for stock in stocks_temp:
        stocks.append(f"{stock}")
        # stocks.append(f"{stock}.{stocks_temp[stock]}")

    # return deque of stocks to focus on
    return stocks