feat: Improve trade entry and performance calculation for sell orders

This commit is contained in:
Bobby (aider) 2025-02-13 11:11:42 -08:00
parent 6d29558752
commit abaf3ab855
2 changed files with 22 additions and 26 deletions

View File

@ -19,26 +19,23 @@ def calculate_position_performance(trades):
for trade in trades:
try:
shares = float(trade['shares'])
price = float(trade['entry_price'])
# If no direction field, infer from exit_price
if 'direction' not in trade or not trade['direction']:
# If no exit_price, assume it's a buy
if trade.get('exit_price') is None:
direction = 'buy'
else:
direction = 'sell'
else:
direction = str(trade.get('direction', '')).lower()
# Handle buy orders
if ('direction' not in trade or not trade['direction'] or
trade.get('direction', '').lower() == 'buy'):
if trade.get('entry_price'):
price = float(trade['entry_price'])
total_bought += shares
total_cost += shares * price
if direction == 'buy':
total_bought += shares
total_cost += shares * price
elif direction == 'sell':
# Handle sell orders
elif trade.get('direction', '').lower() == 'sell' or trade.get('exit_price'):
price = float(trade.get('exit_price') or trade.get('entry_price'))
total_sold += shares
total_proceeds += shares * price
print(f"Processing trade: Direction={direction}, Shares={shares}, Price={price}") # Debug
print(f"Processing trade: Direction={trade.get('direction')}, "
f"Shares={shares}, Price={price}") # Debug
except (ValueError, TypeError) as e:
print(f"Error processing trade: {e}")
@ -491,19 +488,19 @@ def trading_journal_page():
# Show sell trades
st.subheader("Sell Orders")
for trade in trades:
# Infer direction if not set
if 'direction' not in trade or not trade['direction']:
is_sell = trade.get('exit_price') is not None
else:
is_sell = trade.get('direction', '').lower() == 'sell'
# Check for sell orders
is_sell = (trade.get('direction', '').lower() == 'sell' or
trade.get('exit_price') is not None)
if is_sell:
col1, col2 = st.columns(2)
with col1:
st.text(f"Date: {format_datetime(trade['entry_date'])}")
st.text(f"Date: {format_datetime(trade.get('exit_date') or trade.get('entry_date'))}")
st.text(f"Shares: {trade['shares']}")
with col2:
st.text(f"Price: ${float(trade['entry_price']):.2f}")
# Use exit_price for sells, fallback to entry_price
price = float(trade.get('exit_price') or trade.get('entry_price'))
st.text(f"Price: ${price:.2f}")
st.text(f"Order: {trade['order_type']}")
if trade.get('exit_reason'):
st.text(f"Reason: {trade['exit_reason']}")

View File

@ -169,13 +169,12 @@ class TradeEntry:
position_id: Optional[str] = None
def __post_init__(self):
# For sell orders, move entry_price to exit_price and entry_date to exit_date
# For sell orders, set exit_price and exit_date
if self.direction.lower() == 'sell':
self.exit_price = self.entry_price
self.exit_date = self.entry_date
# Clear entry price since this is a sell
self.entry_price = None
self.entry_date = None
self.entry_price = None # Set to NULL for sells
self.entry_date = None # Set to NULL for sells
@property
def expected_profit_loss(self) -> Optional[float]: