valuecell icon indicating copy to clipboard operation
valuecell copied to clipboard

Strategy runtime resume resets active holdings to empty and resurrects initial capital when cash balance is 0.0 due to falsy evaluation`

Open codeCraft-Ritik opened this issue 1 month ago • 0 comments


Affected File & Lines

  • python/valuecell/agents/common/trading/_internal/runtime.py:125-163

Severity & Impact

  • Severity: Critical
  • Impact: Financial calculation error & portfolio desynchronization. When an automated trading strategy restarts or resumes from the database:
    1. If 100% of available cash is allocated into active positions (making free cash $0.0), the falsy evaluation free_cash_override or initial_free_cash revives the initial starting capital (e.g., granting $50,000 phantom purchasing power).
    2. All previously recorded open holdings are completely discarded because create_strategy_runtime never queries repo.get_latest_holdings(strategy_id_override). The strategy starts with initial_positions={}, making risk management, margin calculation, and position tracking completely desynchronized from the actual exchange/virtual account.

Root Cause Analysis

  1. Falsy Cash Evaluation (runtime.py:149):
    free_cash = free_cash_override or request.trading_config.initial_free_cash or 0.0
    total_cash = total_cash_override or request.trading_config.initial_capital or 0.0
    
    In Python, 0.0 is falsy. If free_cash_override was loaded as 0.0 from repo.get_latest_portfolio_snapshot(strategy_id_override), 0.0 or 50000.0 evaluates to 50000.0.
  2. Missing Holdings Restoration (runtime.py:155-163):
    portfolio_service = InMemoryPortfolioService(
        free_cash=free_cash,
        total_cash=total_cash,
        initial_positions=request.trading_config.initial_positions,  # <-- Bug: request initial positions is empty
        trading_mode=request.exchange_config.trading_mode,
        market_type=request.exchange_config.market_type,
        constraints=constraints,
        strategy_id=strategy_id,
    )
    
    StrategyRepository contains repo.get_latest_holdings(strategy_id_override), but create_strategy_runtime only reads the portfolio snapshot for cash metrics and completely neglects restoring initial_positions from the repository.

Steps to Reproduce

Run the following script:

import inspect
import sys
sys.path.insert(0, r"python")

from valuecell.agents.common.trading._internal.runtime import create_strategy_runtime

# 1. Test falsy cash evaluation
free_cash_override = 0.0  # Fully invested portfolio
initial_free_cash = 50000.0  # Starting capital

free_cash = free_cash_override or initial_free_cash or 0.0
print(f"Persisted Snapshot Cash: {free_cash_override}")
print(f"TradingConfig Initial Cash: {initial_free_cash}")
print(f"Evaluated free_cash on resume: {free_cash}")
assert free_cash == 50000.0, "Falsy bug reproduced"

# 2. Check holdings query in create_strategy_runtime
src = inspect.getsource(create_strategy_runtime)
print("Queries get_latest_portfolio_snapshot:", "get_latest_portfolio_snapshot" in src)
print("Queries get_latest_holdings:", "get_latest_holdings" in src)

Observed Behavior (Evidence)

Persisted Snapshot Cash: 0.0
TradingConfig Initial Cash: 50000.0
Evaluated free_cash on resume: 50000.0
Queries get_latest_portfolio_snapshot: True
Queries get_latest_holdings: False

Expected Behavior

  1. When free_cash_override is 0.0, it must be preserved as 0.0 rather than defaulting to initial_free_cash.
  2. Resumed strategies should fetch active holdings from repo.get_latest_holdings(strategy_id_override) and pass them to InMemoryPortfolioService.

Proposed Fix

--- a/python/valuecell/agents/common/trading/_internal/runtime.py
+++ b/python/valuecell/agents/common/trading/_internal/runtime.py
@@ -124,10 +124,12 @@ async def create_strategy_runtime(
     total_cash_override = None
+    resumed_positions = None
     if strategy_id_override:
         try:
             repo = get_strategy_repository()
             snap = repo.get_latest_portfolio_snapshot(strategy_id_override)
             if snap is not None:
-                free_cash_override = float(snap.cash or 0.0)
+                free_cash_override = float(snap.cash if snap.cash is not None else 0.0)
                 total_cash_override = float(
                     snap.total_value - snap.total_unrealized_pnl
                     if (
@@ -137,6 +139,12 @@ async def create_strategy_runtime(
                     else 0.0
                 )
+            holdings = repo.get_latest_holdings(strategy_id_override)
+            if holdings:
+                resumed_positions = {
+                    h.symbol: h.to_position_snapshot() for h in holdings
+                }
                 logger.info(
                     "Initialized runtime initial capital from persisted snapshot for strategy_id=%s",
                     strategy_id_override,
@@ -146,8 +154,8 @@ async def create_strategy_runtime(
                 strategy_id_override,
             )
 
-    free_cash = free_cash_override or request.trading_config.initial_free_cash or 0.0
-    total_cash = total_cash_override or request.trading_config.initial_capital or 0.0
+    free_cash = free_cash_override if free_cash_override is not None else (request.trading_config.initial_free_cash or 0.0)
+    total_cash = total_cash_override if total_cash_override is not None else (request.trading_config.initial_capital or 0.0)
     constraints = Constraints(
         max_positions=request.trading_config.max_positions,
         max_leverage=request.trading_config.max_leverage,
     )
     portfolio_service = InMemoryPortfolioService(
         free_cash=free_cash,
         total_cash=total_cash,
-        initial_positions=request.trading_config.initial_positions,
+        initial_positions=resumed_positions or request.trading_config.initial_positions,
         trading_mode=request.exchange_config.trading_mode,
         market_type=request.exchange_config.market_type,
         constraints=constraints,
         strategy_id=strategy_id,
     )

codeCraft-Ritik avatar Oct 27 '26 05:10 codeCraft-Ritik