Skip to content

Commit 3be21b5

Browse files
committed
set up for new trader class
1 parent a0ef7b2 commit 3be21b5

File tree

2 files changed

+57
-23
lines changed

2 files changed

+57
-23
lines changed

application.py

+43-16
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import pytz
1515
import json
1616
import os
17+
import sys
1718

1819

1920
# setup for coloured output
@@ -70,12 +71,14 @@
7071
PACK_UP = datetime.time(hour=15, minute=15, second=0)
7172

7273
##############################################################
73-
today = datetime.date.today().strftime("%d-%m-%Y")
74-
if not os.path.exists(f"database/{today}"):
75-
os.mkdir(f"database/{today}")
76-
ml = master_logger(f'database/{today}/master.log')
74+
TODAY = datetime.date.today().strftime("%d-%m-%Y")
75+
if not os.path.exists(f"database/{TODAY}"):
76+
os.mkdir(f"database/{TODAY}")
77+
ml = master_logger(f'database/{TODAY}/master.log')
7778
ml.info("-"*76)
7879
ml.info("-"*27 + " NEW SESSION DETECTED " + "-"*27)
80+
sys.stderr = open(f"database/{TODAY}/errorStream.txt", "a")
81+
7982
##############################################################
8083

8184
try:
@@ -86,6 +89,7 @@
8689
quit(0)
8790
ml.info("Successfully loaded user_info.json")
8891
ml.info("-"*76)
92+
8993
##############################################################
9094

9195
HEADERS = {
@@ -121,25 +125,27 @@
121125
quit(0)
122126
else:
123127
IDLE_DELAY = 0
124-
ml.warning("Running in no delay mode")
128+
ml.warning("[ MODE ] Zero delay")
125129
else:
126130
IDLE_DELAY = args.delay
127131
ml.info(f"Idle delay set to {IDLE_DELAY}")
128132

129133
if args.np:
130134
PERIOD_INTERVAL = 0
131-
ml.warning("Running with zero period interval !")
135+
ml.warning("[ MODE ] Zero period interval")
132136

133137
if args.t:
134138
IDLE_DELAY = 1
135139
PERIOD_INTERVAL = 0
136-
ml.warning("Running in test mode")
140+
Notify.warn("Running in Test Mode, meant for debugging and demonstration purposes only.")
141+
ml.warning("[ MODE ] TEST")
142+
print("")
137143

138144
# developer mode
139145
DEV_MODE = args.nd and args.np
140146
if DEV_MODE:
141147
PENNY_STOCK_THRESHOLD = 0
142-
ml.warning("Running in developer mode")
148+
ml.warning("[ MODE ] DEVELOPER")
143149

144150
##############################################################
145151

@@ -199,12 +205,21 @@ def fetch_stocks():
199205
Deque of tickers of relevant stocks
200206
201207
"""
208+
209+
global ml
210+
202211
# url to grab data from
203212
url = f'https://in.finance.yahoo.com/gainers?count={NUM_OF_STOCKS_TO_SEARCH}'
204213
# request header
205214
headers = {
206215
'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'}
207-
src = requests.get(url=url, headers=headers).content
216+
try:
217+
src = requests.get(url=url, headers=headers).content
218+
except Exception as e:
219+
src = None
220+
Notify.fatal("Trade abort due to unexpected error. Check activity log for details")
221+
ml.critical("Encountered error : ", e)
222+
quit(0)
208223
# soup object of source code
209224
soup = BeautifulSoup(src, "html.parser")
210225
rows = soup.find('table').tbody.find_all('tr')
@@ -298,6 +313,9 @@ def __init__(self, number, ticker):
298313
self.IN_SHORT_TRADE = True
299314
self.price_for_buffer = price
300315
self.logger = trader_logger(self.ticker)
316+
self.logger.info("-" * 76)
317+
self.logger.info("-" * 27 + " NEW SESSION DETECTED " + "-" * 27)
318+
self.logger.info("-" * 76)
301319

302320
def get_initial_data(self):
303321
try:
@@ -467,8 +485,10 @@ def lineup_traders(self, tickers):
467485
count = 1
468486
for ticker in tickers:
469487
self.traders.append(Trader(count, ticker))
488+
Notify.info(f"Successfully connected Trader #{count} to {ticker}", delay=0.01)
470489
count += 1
471490
ml.info("Trader lineup complete")
491+
print("")
472492

473493
# initialise traders
474494
def init_traders(self, Tmode=False):
@@ -564,15 +584,21 @@ def main():
564584
"""
565585
# make sure that market is open
566586
if not DEV_MODE:
567-
if is_open():
587+
if args.t:
588+
Notify.for_input("Check Market? (y/n) : ")
589+
confirm = input().strip().lower()
590+
print("")
591+
else:
592+
confirm = "y"
593+
if is_open() or confirm == "n":
568594
pass
569595
else:
570596
Notify.fatal("Market is closed at the moment, aborting.")
571597
print("")
572598
quit(0)
573599
else:
574600
Notify.warn("You are in developer mode, if not intended, please quit.")
575-
Notify.info("Press ENTER to continue, Ctrl + C to quit")
601+
Notify.info("Press ENTER to continue, Ctrl+C to quit")
576602
input()
577603

578604
# allow market to settle to launch Ichimoku strategy
@@ -590,16 +616,14 @@ def main():
590616
Notify.info("Finding stocks to focus on .....")
591617
try:
592618
stocks_to_focus = fetch_stocks()
593-
except Exception as e:
619+
except:
594620
stocks_to_focus = []
595-
ml.critical("Could not fetch relevant stocks : ", e)
621+
Notify.fatal("Could not fetch relevant stocks. Verify Network connection and check logs for details.")
622+
ml.critical("Could not fetch relevant stocks, Most possibly due to network error")
596623
quit(0)
597624
Notify.info("\tStatus : Complete")
598625
ml.info("Successfully found relevant stocks")
599626
print("")
600-
print(stocks_to_focus)
601-
print("")
602-
print("")
603627

604628
# setup traders and begin trade
605629
master = Master()
@@ -624,3 +648,6 @@ def main():
624648
Notify.fatal("Operation cancelled by user.")
625649
ml.critical("Operation cancelled by user")
626650
quit(0)
651+
except Exception as err:
652+
Notify.fatal("Encountered fatal error. Check log for details. Aborting")
653+
ml.critical("Trade abort due to unexpected error : ", err)

library/notifications.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from time import sleep
33

44

5-
PAUSE = 0.03
5+
PAUSE = 0.02
66

77

88
class Notify:
@@ -12,25 +12,32 @@ def heading(heading: str) -> None:
1212
print(Style.RESET_ALL)
1313

1414
@staticmethod
15-
def info(message: str) -> None:
15+
def for_input(message: str, delay: float = PAUSE) -> None:
1616
print(Fore.GREEN + "[ MESSAGE ] " + Style.RESET_ALL, end="")
1717
for char in message:
1818
print(char, end="")
19-
sleep(PAUSE)
19+
sleep(delay)
20+
21+
@staticmethod
22+
def info(message: str, delay: float = PAUSE) -> None:
23+
print(Fore.GREEN + "[ MESSAGE ] " + Style.RESET_ALL, end="")
24+
for char in message:
25+
print(char, end="")
26+
sleep(delay)
2027
print("")
2128

2229
@staticmethod
23-
def warn(message: str) -> None:
30+
def warn(message: str, delay: float = PAUSE) -> None:
2431
print(Fore.CYAN + "[ WARNING ] " + Style.RESET_ALL, end="")
2532
for char in message:
2633
print(char, end="")
27-
sleep(PAUSE)
34+
sleep(delay)
2835
print("")
2936

3037
@staticmethod
31-
def fatal(message: str) -> None:
38+
def fatal(message: str, delay: float = PAUSE) -> None:
3239
print(Fore.RED + "[ FATAL ] " + Style.RESET_ALL, end="")
3340
for char in message:
3441
print(char, end="")
35-
sleep(PAUSE)
42+
sleep(delay)
3643
print("")

0 commit comments

Comments
 (0)