test_update_and_check_mark_price.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import sys
  2. import os
  3. from datetime import datetime
  4. # Adjust path if needed to import TradingStats and TradingEngine
  5. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  6. from src.stats.trading_stats import TradingStats
  7. from src.trading.trading_engine import TradingEngine
  8. def update_db_with_latest_mark_prices():
  9. engine = TradingEngine()
  10. stats = TradingStats()
  11. exchange_positions = engine.get_positions() or []
  12. print(f"Fetched {len(exchange_positions)} positions from exchange.")
  13. updated = 0
  14. for pos in exchange_positions:
  15. symbol = pos.get('symbol')
  16. mark_price = pos.get('markPrice') or pos.get('markPx')
  17. if symbol and mark_price is not None:
  18. # Find the open trade in DB
  19. open_positions = stats.get_open_positions()
  20. for db_pos in open_positions:
  21. if db_pos.get('symbol') == symbol:
  22. lifecycle_id = db_pos.get('trade_lifecycle_id')
  23. try:
  24. stats.trade_manager.update_trade_market_data(
  25. lifecycle_id,
  26. mark_price=float(mark_price)
  27. )
  28. updated += 1
  29. print(f"Updated {symbol} (Lifecycle: {lifecycle_id}) with mark_price={mark_price}")
  30. except Exception as e:
  31. print(f"Failed to update {symbol}: {e}")
  32. print(f"Updated {updated} positions in DB with latest mark prices.")
  33. def print_open_positions_mark_prices():
  34. stats = TradingStats()
  35. open_positions = stats.get_open_positions()
  36. print(f"\nDB now has {len(open_positions)} open positions:")
  37. for pos in open_positions:
  38. symbol = pos.get('symbol', 'N/A')
  39. entry_price = pos.get('entry_price', 'N/A')
  40. mark_price = pos.get('mark_price', 'N/A')
  41. print(f"Symbol: {symbol}, Entry Price: {entry_price}, Mark Price: {mark_price}")
  42. if __name__ == "__main__":
  43. update_db_with_latest_mark_prices()
  44. print_open_positions_mark_prices()