feat: Add dynamic plan_id column check and creation in get_plan_trades

This commit is contained in:
Bobby (aider) 2025-02-11 19:13:39 -08:00
parent a47cd3e1cc
commit d9692e9811

View File

@ -346,20 +346,44 @@ def link_trades_to_plan(plan_id: int, trade_ids: List[int]) -> bool:
def get_plan_trades(plan_id: int) -> List[dict]:
"""Get all trades associated with a trading plan"""
with create_client() as client:
query = """
SELECT *
FROM stock_db.trades
WHERE plan_id = %(plan_id)s
ORDER BY entry_date DESC
"""
result = client.query(query, {'plan_id': plan_id})
return [dict(zip(
['id', 'position_id', 'ticker', 'entry_date', 'shares', 'entry_price',
'target_price', 'stop_loss', 'strategy', 'order_type', 'direction',
'followed_rules', 'entry_reason', 'exit_price', 'exit_date',
'exit_reason', 'notes', 'created_at', 'plan_id'],
row
)) for row in result.result_rows]
try:
# First check if plan_id column exists
check_query = """
SELECT name
FROM system.columns
WHERE database = 'stock_db'
AND table = 'trades'
AND name = 'plan_id'
"""
result = client.query(check_query)
if not result.result_rows:
# Add plan_id column if it doesn't exist
alter_query = """
ALTER TABLE stock_db.trades
ADD COLUMN IF NOT EXISTS plan_id Nullable(UInt32)
"""
client.command(alter_query)
print("Added plan_id column to trades table")
# Now query the trades
query = """
SELECT *
FROM stock_db.trades
WHERE plan_id = %(plan_id)s
ORDER BY entry_date DESC
"""
result = client.query(query, {'plan_id': plan_id})
return [dict(zip(
['id', 'position_id', 'ticker', 'entry_date', 'shares', 'entry_price',
'target_price', 'stop_loss', 'strategy', 'order_type', 'direction',
'followed_rules', 'entry_reason', 'exit_price', 'exit_date',
'exit_reason', 'notes', 'created_at', 'plan_id'],
row
)) for row in result.result_rows]
except Exception as e:
print(f"Error in get_plan_trades: {e}")
return []
def calculate_plan_metrics(plan_id: int) -> dict:
"""Calculate performance metrics for a trading plan"""