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"):
try:
# Debug print before creating item
print("\n=== PRE-WATCHLIST ITEM CREATION ===")
print(f"Ticker: {ticker}")
print(f"Entry Price: {entry_price}")
print(f"Target Price: {target_price}")
print(f"Stop Loss: {position['stop_loss']}")
print(f"Notes: {notes}")
print(f"Selected Watchlist ID: {selected_list[0]}")
print("=====================================\n")
debug_info = {
"Ticker": ticker,
"Entry Price": entry_price,
"Target Price": target_price,
"Stop Loss": position['stop_loss'],
"Notes": notes,
"Selected Watchlist ID": selected_list[0]
}
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"Entry: {entry_price}, Target: {target_price}, Stop: {position['stop_loss']}")
item = WatchlistItem(
ticker=ticker,
@ -252,13 +255,22 @@ def trading_system_page():
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)
# Show the result
st.write(f"Add to watchlist result: {success}")
if success:
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()
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:
logger.error(f"Error in watchlist addition: {e}", exc_info=True)
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 db.db_connection import create_client
import logging
import streamlit as st
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@ -37,52 +38,41 @@ def get_watchlists() -> List[dict]:
def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
with create_client() as client:
try:
# Debug print at start of function
print("\n=== WATCHLIST INSERT ATTEMPT ===")
print("Input parameters:")
print(f"Watchlist ID: {watchlist_id}")
print(f"Item details:")
print(f" Ticker: {item.ticker}")
print(f" Entry Price: {item.entry_price}")
print(f" Target Price: {item.target_price}")
print(f" Stop Loss: {item.stop_loss}")
print(f" Notes: {item.notes}")
print("=============================\n")
# Log the initial state
logger.info("=== Starting add_to_watchlist operation ===")
# Debug output using st.write
st.write("\n=== WATCHLIST INSERT ATTEMPT ===")
st.write("Input parameters:")
st.write(f"Watchlist ID: {watchlist_id}")
st.write("Item details:", {
"Ticker": item.ticker,
"Entry Price": item.entry_price,
"Target Price": item.target_price,
"Stop Loss": item.stop_loss,
"Notes": item.notes
})
# Check if watchlist exists
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)
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:
logger.error(f"Watchlist ID {watchlist_id} not found")
st.error(f"Watchlist ID {watchlist_id} not found")
return False
# Get next ID query
# Get next ID
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)
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
logger.info(f"Next ID determined: {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
st.write(f"Next ID: {next_id}")
# Prepare data
data = [(
int(next_id),
int(watchlist_id),
str(item.ticker),
entry_price,
target_price,
stop_loss,
float(item.entry_price),
float(item.target_price),
float(item.stop_loss),
str(item.notes or ''),
datetime.now()
)]
@ -97,20 +87,11 @@ def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
'Float64', 'Float64', 'String', 'DateTime'
]
# Log the insert operation details
logger.info("=== Insert Operation Details ===")
logger.info(f"Table: stock_db.watchlist_items")
logger.info(f"Column Names: {column_names}")
logger.info(f"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")
# Show insert details
st.write("\n=== DATABASE INSERT ATTEMPT ===")
st.write("Data to insert:", data)
st.write("Column names:", column_names)
st.write("Column types:", column_types)
# Perform insert
try:
@ -120,14 +101,12 @@ def add_to_watchlist(watchlist_id: int, item: WatchlistItem) -> bool:
column_names=column_names,
column_types=column_types
)
print("Insert operation completed successfully")
st.write("Insert operation completed successfully")
except Exception as insert_error:
print(f"\nINSERT ERROR: {insert_error}")
print(f"Error type: {type(insert_error)}")
logger.error(f"Insert operation failed: {insert_error}")
st.error(f"Insert error: {insert_error}")
raise
# Verify the insert immediately after
# Verify the insert
verify_query = f"""
SELECT *
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 ticker = '{item.ticker}'
"""
logger.info(f"Verification 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:
logger.error("Verification failed - no rows found after insert")
st.error("Verification failed - no rows found after insert")
return False
logger.info("=== add_to_watchlist operation completed successfully ===")
return True
except Exception as e:
logger.error(f"Error adding to watchlist: {e}", exc_info=True)