feat: Enhance watchlist addition with Streamlit debug output

This commit is contained in:
Bobby (aider) 2025-02-17 16:33:42 -08:00
parent 0eb83197cb
commit f3570ac6b3
2 changed files with 54 additions and 65 deletions

View File

@ -232,17 +232,20 @@ def trading_system_page():
if st.button("Add to Watch List", key="add_to_watchlist"): if st.button("Add to Watch List", key="add_to_watchlist"):
try: try:
# Debug print before creating item # Debug print before creating item
print("\n=== PRE-WATCHLIST ITEM CREATION ===") debug_info = {
print(f"Ticker: {ticker}") "Ticker": ticker,
print(f"Entry Price: {entry_price}") "Entry Price": entry_price,
print(f"Target Price: {target_price}") "Target Price": target_price,
print(f"Stop Loss: {position['stop_loss']}") "Stop Loss": position['stop_loss'],
print(f"Notes: {notes}") "Notes": notes,
print(f"Selected Watchlist ID: {selected_list[0]}") "Selected Watchlist ID": selected_list[0]
print("=====================================\n") }
st.write("=== PRE-WATCHLIST ITEM CREATION ===")
st.write(debug_info)
st.write("=====================================")
logger.info(f"Attempting to add {ticker} to watchlist {selected_list[0]}") logger.info(f"Attempting to add {ticker} to watchlist {selected_list[0]}")
logger.info(f"Entry: {entry_price}, Target: {target_price}, Stop: {position['stop_loss']}")
item = WatchlistItem( item = WatchlistItem(
ticker=ticker, ticker=ticker,
@ -252,13 +255,22 @@ def trading_system_page():
notes=str(notes) if notes else '' notes=str(notes) if notes else ''
) )
# Show the item details before adding
st.write("=== WATCHLIST ITEM DETAILS ===")
st.write(item)
st.write("==============================")
success = add_to_watchlist(selected_list[0], item) success = add_to_watchlist(selected_list[0], item)
# Show the result
st.write(f"Add to watchlist result: {success}")
if success: if success:
st.success(f"Added {ticker} to watch list!") st.success(f"Added {ticker} to watch list!")
time.sleep(1) # Give the database a moment to update time.sleep(2) # Give more time to see the debug output
st.rerun() st.rerun()
else: else:
st.error("Failed to add to watch list. Check the logs for details.") st.error("Failed to add to watch list. Check the details above.")
except Exception as e: except Exception as e:
logger.error(f"Error in watchlist addition: {e}", exc_info=True) logger.error(f"Error in watchlist addition: {e}", exc_info=True)
st.error(f"Error adding to watchlist: {str(e)}") st.error(f"Error adding to watchlist: {str(e)}")

View File

@ -3,6 +3,7 @@ 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 import logging
import streamlit as st
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -37,52 +38,41 @@ def get_watchlists() -> List[dict]:
def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool: def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
with create_client() as client: with create_client() as client:
try: try:
# Debug print at start of function # Debug output using st.write
print("\n=== WATCHLIST INSERT ATTEMPT ===") st.write("\n=== WATCHLIST INSERT ATTEMPT ===")
print("Input parameters:") st.write("Input parameters:")
print(f"Watchlist ID: {watchlist_id}") st.write(f"Watchlist ID: {watchlist_id}")
print(f"Item details:") st.write("Item details:", {
print(f" Ticker: {item.ticker}") "Ticker": item.ticker,
print(f" Entry Price: {item.entry_price}") "Entry Price": item.entry_price,
print(f" Target Price: {item.target_price}") "Target Price": item.target_price,
print(f" Stop Loss: {item.stop_loss}") "Stop Loss": item.stop_loss,
print(f" Notes: {item.notes}") "Notes": item.notes
print("=============================\n") })
# Log the initial state
logger.info("=== Starting add_to_watchlist operation ===")
# Check if watchlist exists # Check if watchlist exists
check_watchlist_query = f"SELECT * FROM stock_db.watchlists WHERE id = {watchlist_id}" check_watchlist_query = f"SELECT * FROM stock_db.watchlists WHERE id = {watchlist_id}"
logger.info(f"Checking watchlist query: {check_watchlist_query}")
watchlist_result = client.query(check_watchlist_query) watchlist_result = client.query(check_watchlist_query)
logger.info(f"Watchlist check result: {watchlist_result.result_rows}") st.write("Watchlist check result:", watchlist_result.result_rows)
if not watchlist_result.result_rows: if not watchlist_result.result_rows:
logger.error(f"Watchlist ID {watchlist_id} not found") st.error(f"Watchlist ID {watchlist_id} not found")
return False return False
# Get next ID query # Get next ID
id_query = "SELECT max(id) + 1 as next_id FROM stock_db.watchlist_items" id_query = "SELECT max(id) + 1 as next_id FROM stock_db.watchlist_items"
logger.info(f"Getting next ID with query: {id_query}")
result = client.query(id_query) result = client.query(id_query)
logger.info(f"Next ID query result: {result.result_rows}")
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
logger.info(f"Next ID determined: {next_id}") st.write(f"Next ID: {next_id}")
# Prepare data with explicit type conversion
entry_price = float(item.entry_price) if item.entry_price is not None else 0.0
target_price = float(item.target_price) if item.target_price is not None else 0.0
stop_loss = float(item.stop_loss) if item.stop_loss is not None else 0.0
# Prepare data
data = [( data = [(
int(next_id), int(next_id),
int(watchlist_id), int(watchlist_id),
str(item.ticker), str(item.ticker),
entry_price, float(item.entry_price),
target_price, float(item.target_price),
stop_loss, float(item.stop_loss),
str(item.notes or ''), str(item.notes or ''),
datetime.now() datetime.now()
)] )]
@ -97,20 +87,11 @@ def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
'Float64', 'Float64', 'String', 'DateTime' 'Float64', 'Float64', 'String', 'DateTime'
] ]
# Log the insert operation details # Show insert details
logger.info("=== Insert Operation Details ===") st.write("\n=== DATABASE INSERT ATTEMPT ===")
logger.info(f"Table: stock_db.watchlist_items") st.write("Data to insert:", data)
logger.info(f"Column Names: {column_names}") st.write("Column names:", column_names)
logger.info(f"Column Types: {column_types}") st.write("Column types:", column_types)
logger.info(f"Data to insert: {data}")
# Add debug print before actual insert
print("\n=== DATABASE INSERT ATTEMPT ===")
print(f"Table: stock_db.watchlist_items")
print(f"Data to insert: {data}")
print(f"Column names: {column_names}")
print(f"Column types: {column_types}")
print("============================\n")
# Perform insert # Perform insert
try: try:
@ -120,14 +101,12 @@ def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
column_names=column_names, column_names=column_names,
column_types=column_types column_types=column_types
) )
print("Insert operation completed successfully") st.write("Insert operation completed successfully")
except Exception as insert_error: except Exception as insert_error:
print(f"\nINSERT ERROR: {insert_error}") st.error(f"Insert error: {insert_error}")
print(f"Error type: {type(insert_error)}")
logger.error(f"Insert operation failed: {insert_error}")
raise raise
# Verify the insert immediately after # Verify the insert
verify_query = f""" verify_query = f"""
SELECT * SELECT *
FROM stock_db.watchlist_items FROM stock_db.watchlist_items
@ -135,15 +114,13 @@ def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
AND watchlist_id = {watchlist_id} AND watchlist_id = {watchlist_id}
AND ticker = '{item.ticker}' AND ticker = '{item.ticker}'
""" """
logger.info(f"Verification query: {verify_query}")
verify_result = client.query(verify_query) verify_result = client.query(verify_query)
logger.info(f"Verification result rows: {verify_result.result_rows}") st.write("Verification result:", verify_result.result_rows)
if not verify_result.result_rows: if not verify_result.result_rows:
logger.error("Verification failed - no rows found after insert") st.error("Verification failed - no rows found after insert")
return False return False
logger.info("=== add_to_watchlist operation completed successfully ===")
return True return True
except Exception as e: except Exception as e:
logger.error(f"Error adding to watchlist: {e}", exc_info=True) logger.error(f"Error adding to watchlist: {e}", exc_info=True)