From 9642d78942812518adfd3fcb422a425f33b4358c Mon Sep 17 00:00:00 2001 From: "Bobby (aider)" Date: Thu, 13 Feb 2025 08:32:58 -0800 Subject: [PATCH] feat: Add support for sell orders in trade history query and display --- src/pages/journal/trading_journal_page.py | 23 +++++++++++++++++------ src/trading/journal.py | 5 +++-- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/pages/journal/trading_journal_page.py b/src/pages/journal/trading_journal_page.py index 2becc93..e3b1fb8 100644 --- a/src/pages/journal/trading_journal_page.py +++ b/src/pages/journal/trading_journal_page.py @@ -286,23 +286,34 @@ def trading_journal_page(): st.plotly_chart(fig, use_container_width=True) for trade in history: + # Determine if this is a sell order or a closed trade + is_sell = trade.get('direction') == 'sell' + with st.expander(f"{trade['ticker']} - {format_datetime(trade['entry_date'])}"): - profit_loss = (trade['exit_price'] - trade['entry_price']) * trade['shares'] if trade['exit_price'] else None + if is_sell: + profit_loss = (trade['entry_price'] - trade.get('exit_price', 0)) * trade['shares'] + else: + profit_loss = (trade.get('exit_price', 0) - trade['entry_price']) * trade['shares'] if trade.get('exit_price') else None col1, col2 = st.columns(2) with col1: - st.metric("Entry Price", f"${trade['entry_price']:.2f}") + if is_sell: + st.metric("Sell Price", f"${trade['entry_price']:.2f}") + else: + st.metric("Entry Price", f"${trade['entry_price']:.2f}") st.metric("Shares", trade['shares']) - if profit_loss: + if profit_loss is not None: st.metric("P/L", f"${profit_loss:.2f}") with col2: - if trade['exit_price']: + if not is_sell and trade.get('exit_price'): st.metric("Exit Price", f"${trade['exit_price']:.2f}") st.metric("Exit Date", format_datetime(trade['exit_date'])) - st.text(f"Strategy: {trade['strategy']}") - if trade['notes']: + if trade.get('strategy'): + st.text(f"Strategy: {trade['strategy']}") + if trade.get('notes'): st.text(f"Notes: {trade['notes']}") + st.text(f"Type: {'Sell Order' if is_sell else 'Buy/Exit'}") else: st.info("No trade history found") diff --git a/src/trading/journal.py b/src/trading/journal.py index 1f74d71..746a127 100644 --- a/src/trading/journal.py +++ b/src/trading/journal.py @@ -526,13 +526,14 @@ def get_trade_history(limit: int = 50): query = f""" SELECT * FROM stock_db.trades WHERE exit_price IS NOT NULL - ORDER BY exit_date DESC + OR direction = 'sell' + ORDER BY COALESCE(exit_date, entry_date) DESC LIMIT {limit} """ result = client.query(query).result_rows columns = ['id', 'position_id', 'ticker', 'entry_date', 'shares', 'entry_price', 'target_price', 'stop_loss', 'strategy', 'order_type', 'followed_rules', 'entry_reason', 'exit_price', - 'exit_date', 'exit_reason', 'notes', 'created_at'] + 'exit_date', 'exit_reason', 'notes', 'created_at', 'direction'] return [dict(zip(columns, row)) for row in result] def journal_menu():