feat: Enhance trade update functionality with flexible field modifications
This commit is contained in:
parent
933141618b
commit
3819547de7
@ -356,17 +356,32 @@ def add_trade(trade: TradeEntry):
|
||||
"""
|
||||
client.command(query)
|
||||
|
||||
def update_trade_exit(trade_id: int, exit_price: float, exit_date: datetime,
|
||||
followed_rules: bool, exit_reason: str, notes: Optional[str] = None):
|
||||
def update_trade(trade_id: int, updates: dict):
|
||||
"""
|
||||
Update trade details
|
||||
|
||||
Args:
|
||||
trade_id (int): ID of trade to update
|
||||
updates (dict): Dictionary of fields and values to update
|
||||
"""
|
||||
with create_client() as client:
|
||||
# Build update query dynamically from provided updates
|
||||
update_statements = []
|
||||
for field, value in updates.items():
|
||||
if isinstance(value, str):
|
||||
update_statements.append(f"{field} = '{value}'")
|
||||
elif isinstance(value, datetime):
|
||||
update_statements.append(f"{field} = '{value.strftime('%Y-%m-%d %H:%M:%S')}'")
|
||||
elif value is None:
|
||||
update_statements.append(f"{field} = NULL")
|
||||
else:
|
||||
update_statements.append(f"{field} = {value}")
|
||||
|
||||
update_clause = ", ".join(update_statements)
|
||||
|
||||
query = f"""
|
||||
ALTER TABLE stock_db.trades
|
||||
UPDATE
|
||||
exit_price = {exit_price},
|
||||
exit_date = '{exit_date.strftime('%Y-%m-%d %H:%M:%S')}',
|
||||
followed_rules = {1 if followed_rules else 0},
|
||||
exit_reason = {f"'{exit_reason}'" if exit_reason else 'NULL'},
|
||||
notes = {f"'{notes}'" if notes else 'notes'}
|
||||
UPDATE {update_clause}
|
||||
WHERE id = {trade_id}
|
||||
"""
|
||||
client.command(query)
|
||||
@ -593,25 +608,82 @@ def journal_menu():
|
||||
for trade in open_trades:
|
||||
print(f"{trade['id']}: {trade['ticker']} - Entered at ${trade['entry_price']}")
|
||||
|
||||
trade_id = int(input("\nEnter trade ID to update: "))
|
||||
exit_price = float(input("Enter exit price: "))
|
||||
print("\nOpen Trades:")
|
||||
for trade in open_trades:
|
||||
print(f"\nID: {trade['id']}")
|
||||
print(f"Ticker: {trade['ticker']}")
|
||||
print(f"Entry Date: {trade['entry_date']}")
|
||||
print(f"Shares: {trade['shares']}")
|
||||
print(f"Entry Price: ${trade['entry_price']}")
|
||||
print(f"Target: ${trade['target_price']}")
|
||||
print(f"Stop Loss: ${trade['stop_loss']}")
|
||||
print(f"Strategy: {trade['strategy']}")
|
||||
print("-" * 40)
|
||||
|
||||
# Get exit date/time with market hours validation
|
||||
exit_date = get_datetime_input("Enter exit date and time", default=datetime.now())
|
||||
trade_id = get_user_input("\nEnter trade ID to update:", int)
|
||||
if trade_id is None:
|
||||
continue
|
||||
|
||||
followed_rules = input("Did you follow your rules? (y/n): ").lower() == 'y'
|
||||
exit_reason = input("Enter exit reason: ")
|
||||
notes = input("Additional notes (optional): ") or None
|
||||
# Find the trade to update
|
||||
trade_to_update = next((t for t in open_trades if t['id'] == trade_id), None)
|
||||
if not trade_to_update:
|
||||
print("Trade not found.")
|
||||
continue
|
||||
|
||||
update_trade_exit(
|
||||
trade_id=trade_id,
|
||||
exit_price=exit_price,
|
||||
exit_date=datetime.now(),
|
||||
followed_rules=followed_rules,
|
||||
exit_reason=exit_reason,
|
||||
notes=notes
|
||||
)
|
||||
print("Trade updated successfully!")
|
||||
print("\nUpdate Trade Fields")
|
||||
print("Leave blank to keep existing value")
|
||||
|
||||
updates = {}
|
||||
|
||||
# Entry date
|
||||
new_date = get_datetime_input("Enter new entry date and time (blank to keep):", None)
|
||||
if new_date:
|
||||
updates['entry_date'] = new_date
|
||||
|
||||
# Shares
|
||||
new_shares = get_user_input("Enter new number of shares:", int, allow_empty=True)
|
||||
if new_shares is not None:
|
||||
updates['shares'] = new_shares
|
||||
|
||||
# Entry price
|
||||
new_entry = get_user_input("Enter new entry price:", float, allow_empty=True)
|
||||
if new_entry is not None:
|
||||
updates['entry_price'] = new_entry
|
||||
|
||||
# Target price
|
||||
new_target = get_user_input("Enter new target price:", float, allow_empty=True)
|
||||
if new_target is not None:
|
||||
updates['target_price'] = new_target
|
||||
|
||||
# Stop loss
|
||||
new_stop = get_user_input("Enter new stop loss:", float, allow_empty=True)
|
||||
if new_stop is not None:
|
||||
updates['stop_loss'] = new_stop
|
||||
|
||||
# Strategy
|
||||
new_strategy = input("Enter new strategy (blank to keep): ").strip()
|
||||
if new_strategy:
|
||||
updates['strategy'] = new_strategy
|
||||
|
||||
# Order type
|
||||
if input("Update order type? (y/n): ").lower() == 'y':
|
||||
new_order_type = get_order_type()
|
||||
if new_order_type:
|
||||
updates['order_type'] = new_order_type
|
||||
|
||||
# Notes
|
||||
new_notes = input("Enter new notes (blank to keep): ").strip()
|
||||
if new_notes:
|
||||
updates['notes'] = new_notes
|
||||
|
||||
if updates:
|
||||
try:
|
||||
update_trade(trade_id, updates)
|
||||
print("Trade updated successfully!")
|
||||
except Exception as e:
|
||||
print(f"Error updating trade: {e}")
|
||||
else:
|
||||
print("No updates provided.")
|
||||
|
||||
elif choice == "3":
|
||||
open_trades = get_open_trades()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user