feat: Add logging and improve watchlist UI for better error handling
This commit is contained in:
parent
ca843a370e
commit
4bdd85405a
@ -1,41 +1,53 @@
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import logging
|
||||||
|
|
||||||
# Add the src directory to the Python path
|
# Add the src directory to the Python path
|
||||||
src_path = str(Path(__file__).parent.parent)
|
src_path = str(Path(__file__).parent.parent)
|
||||||
sys.path.append(src_path)
|
sys.path.append(src_path)
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
from db.db_connection import create_client
|
from db.db_connection import create_client
|
||||||
|
|
||||||
def create_watchlist_tables():
|
def create_watchlist_tables():
|
||||||
with create_client() as client:
|
with create_client() as client:
|
||||||
# Create watchlists table
|
try:
|
||||||
client.command("""
|
# Create watchlists table
|
||||||
CREATE TABLE IF NOT EXISTS stock_db.watchlists (
|
logger.info("Creating watchlists table...")
|
||||||
id UInt32,
|
client.command("""
|
||||||
name String,
|
CREATE TABLE IF NOT EXISTS stock_db.watchlists (
|
||||||
strategy String,
|
id UInt32,
|
||||||
created_at DateTime DEFAULT now()
|
name String,
|
||||||
)
|
strategy String,
|
||||||
ENGINE = MergeTree()
|
created_at DateTime DEFAULT now()
|
||||||
ORDER BY (id)
|
)
|
||||||
""")
|
ENGINE = MergeTree()
|
||||||
|
ORDER BY (id)
|
||||||
# Create watchlist items table
|
""")
|
||||||
client.command("""
|
|
||||||
CREATE TABLE IF NOT EXISTS stock_db.watchlist_items (
|
# Create watchlist items table
|
||||||
id UInt32,
|
logger.info("Creating watchlist_items table...")
|
||||||
watchlist_id UInt32,
|
client.command("""
|
||||||
ticker String,
|
CREATE TABLE IF NOT EXISTS stock_db.watchlist_items (
|
||||||
entry_price Float64,
|
id UInt32,
|
||||||
target_price Float64,
|
watchlist_id UInt32,
|
||||||
stop_loss Float64,
|
ticker String,
|
||||||
notes String,
|
entry_price Float64,
|
||||||
created_at DateTime DEFAULT now()
|
target_price Float64,
|
||||||
)
|
stop_loss Float64,
|
||||||
ENGINE = MergeTree()
|
notes String,
|
||||||
ORDER BY (id, watchlist_id)
|
created_at DateTime DEFAULT now()
|
||||||
""")
|
)
|
||||||
|
ENGINE = MergeTree()
|
||||||
|
ORDER BY (id, watchlist_id)
|
||||||
|
""")
|
||||||
|
|
||||||
|
logger.info("Tables created successfully")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error creating tables: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
create_watchlist_tables()
|
create_watchlist_tables()
|
||||||
|
|||||||
@ -184,20 +184,23 @@ def trading_system_page():
|
|||||||
st.metric("Confidence Level", f"{confidence_level}%")
|
st.metric("Confidence Level", f"{confidence_level}%")
|
||||||
|
|
||||||
# Add to watchlist option
|
# Add to watchlist option
|
||||||
if st.button("Add to Watch List"):
|
st.divider()
|
||||||
watchlists = get_watchlists()
|
st.subheader("Add to Watch List")
|
||||||
if not watchlists:
|
watchlists = get_watchlists()
|
||||||
st.warning("No watch lists available. Create one in the Watch Lists tab.")
|
if not watchlists:
|
||||||
else:
|
st.warning("No watch lists available. Create one in the Watch Lists tab.")
|
||||||
|
else:
|
||||||
|
col1, col2 = st.columns([3, 1])
|
||||||
|
with col1:
|
||||||
selected_list = st.selectbox(
|
selected_list = st.selectbox(
|
||||||
"Select Watch List",
|
"Select Watch List",
|
||||||
options=[(w['id'], w['name']) for w in watchlists],
|
options=[(w['id'], w['name']) for w in watchlists],
|
||||||
format_func=lambda x: x[1]
|
format_func=lambda x: x[1]
|
||||||
)
|
)
|
||||||
|
|
||||||
notes = st.text_area("Notes")
|
notes = st.text_area("Notes")
|
||||||
|
|
||||||
if st.button("Confirm Add to Watch List"):
|
with col2:
|
||||||
|
if st.button("Add to Watch List", key="add_to_watchlist"):
|
||||||
item = WatchlistItem(
|
item = WatchlistItem(
|
||||||
ticker=ticker,
|
ticker=ticker,
|
||||||
entry_price=entry_price,
|
entry_price=entry_price,
|
||||||
@ -207,6 +210,7 @@ def trading_system_page():
|
|||||||
)
|
)
|
||||||
if add_to_watchlist(selected_list[0], item):
|
if add_to_watchlist(selected_list[0], item):
|
||||||
st.success(f"Added {ticker} to watch list!")
|
st.success(f"Added {ticker} to watch list!")
|
||||||
|
st.rerun()
|
||||||
else:
|
else:
|
||||||
st.error("Failed to add to watch list")
|
st.error("Failed to add to watch list")
|
||||||
|
|
||||||
|
|||||||
@ -2,6 +2,10 @@ from dataclasses import dataclass
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
from db.db_connection import create_client
|
from db.db_connection import create_client
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WatchlistItem:
|
class WatchlistItem:
|
||||||
@ -37,14 +41,30 @@ def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
|
|||||||
result = client.query("SELECT max(id) + 1 as next_id FROM stock_db.watchlist_items")
|
result = client.query("SELECT max(id) + 1 as next_id FROM stock_db.watchlist_items")
|
||||||
next_id = result.first_row[0] if result.first_row[0] is not None else 1
|
next_id = result.first_row[0] if result.first_row[0] is not None else 1
|
||||||
|
|
||||||
client.insert('stock_db.watchlist_items',
|
logger.info(f"Adding item to watchlist: ID={next_id}, WatchlistID={watchlist_id}, Ticker={item.ticker}")
|
||||||
[(next_id, watchlist_id, item.ticker, item.entry_price,
|
|
||||||
item.target_price, item.stop_loss, item.notes or '', datetime.now())],
|
data = [(
|
||||||
column_names=['id', 'watchlist_id', 'ticker', 'entry_price',
|
next_id,
|
||||||
'target_price', 'stop_loss', 'notes', 'created_at'])
|
watchlist_id,
|
||||||
|
item.ticker,
|
||||||
|
float(item.entry_price),
|
||||||
|
float(item.target_price),
|
||||||
|
float(item.stop_loss),
|
||||||
|
item.notes or '',
|
||||||
|
datetime.now()
|
||||||
|
)]
|
||||||
|
|
||||||
|
logger.info(f"Insert {data}")
|
||||||
|
|
||||||
|
client.insert(
|
||||||
|
'stock_db.watchlist_items',
|
||||||
|
data,
|
||||||
|
column_names=['id', 'watchlist_id', 'ticker', 'entry_price',
|
||||||
|
'target_price', 'stop_loss', 'notes', 'created_at']
|
||||||
|
)
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error adding to watchlist: {e}")
|
logger.error(f"Error adding to watchlist: {e}", exc_info=True)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def remove_from_watchlist(item_id: int) -> bool:
|
def remove_from_watchlist(item_id: int) -> bool:
|
||||||
@ -61,27 +81,34 @@ def remove_from_watchlist(item_id: int) -> bool:
|
|||||||
|
|
||||||
def get_watchlist_items(watchlist_id: Optional[int] = None) -> List[WatchlistItem]:
|
def get_watchlist_items(watchlist_id: Optional[int] = None) -> List[WatchlistItem]:
|
||||||
with create_client() as client:
|
with create_client() as client:
|
||||||
query = """
|
try:
|
||||||
SELECT i.*, w.name as watchlist_name, w.strategy
|
query = """
|
||||||
FROM stock_db.watchlist_items i
|
SELECT i.*, w.name as watchlist_name, w.strategy
|
||||||
JOIN stock_db.watchlists w ON w.id = i.watchlist_id
|
FROM stock_db.watchlist_items i
|
||||||
"""
|
JOIN stock_db.watchlists w ON w.id = i.watchlist_id
|
||||||
if watchlist_id:
|
"""
|
||||||
query += f" WHERE watchlist_id = {watchlist_id}"
|
if watchlist_id:
|
||||||
query += " ORDER BY i.created_at DESC"
|
query += f" WHERE i.watchlist_id = {watchlist_id}"
|
||||||
|
query += " ORDER BY i.created_at DESC"
|
||||||
result = client.query(query)
|
|
||||||
items = []
|
logger.info(f"Executing query: {query}")
|
||||||
for row in result.result_rows:
|
|
||||||
data = dict(zip(result.column_names, row))
|
result = client.query(query)
|
||||||
items.append(WatchlistItem(
|
items = []
|
||||||
id=data['id'],
|
for row in result.result_rows:
|
||||||
watchlist_id=data['watchlist_id'],
|
data = dict(zip(result.column_names, row))
|
||||||
ticker=data['ticker'],
|
logger.info(f"Processing row: {data}")
|
||||||
entry_price=data['entry_price'],
|
items.append(WatchlistItem(
|
||||||
target_price=data['target_price'],
|
id=data['id'],
|
||||||
stop_loss=data['stop_loss'],
|
watchlist_id=data['watchlist_id'],
|
||||||
notes=data['notes'],
|
ticker=data['ticker'],
|
||||||
created_at=data['created_at']
|
entry_price=data['entry_price'],
|
||||||
))
|
target_price=data['target_price'],
|
||||||
return items
|
stop_loss=data['stop_loss'],
|
||||||
|
notes=data['notes'],
|
||||||
|
created_at=data['created_at']
|
||||||
|
))
|
||||||
|
return items
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting watchlist items: {e}", exc_info=True)
|
||||||
|
return []
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user