valuecell
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`
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:
- If 100% of available cash is allocated into active positions (making free cash
$0.0), the falsy evaluationfree_cash_override or initial_free_cashrevives the initial starting capital (e.g., granting$50,000phantom purchasing power). - All previously recorded open holdings are completely discarded because
create_strategy_runtimenever queriesrepo.get_latest_holdings(strategy_id_override). The strategy starts withinitial_positions={}, making risk management, margin calculation, and position tracking completely desynchronized from the actual exchange/virtual account.
- If 100% of available cash is allocated into active positions (making free cash
Root Cause Analysis
- Falsy Cash Evaluation (
runtime.py:149):
In Python,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.00.0is falsy. Iffree_cash_overridewas loaded as0.0fromrepo.get_latest_portfolio_snapshot(strategy_id_override),0.0 or 50000.0evaluates to50000.0. - 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, )StrategyRepositorycontainsrepo.get_latest_holdings(strategy_id_override), butcreate_strategy_runtimeonly reads the portfolio snapshot for cash metrics and completely neglects restoringinitial_positionsfrom 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
- When
free_cash_overrideis0.0, it must be preserved as0.0rather than defaulting toinitial_free_cash. - Resumed strategies should fetch active holdings from
repo.get_latest_holdings(strategy_id_override)and pass them toInMemoryPortfolioService.
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,
)