fix: use current_price not avg_entry_price for invested calc — prevents margin-inflated numbers showing $0 available
This commit is contained in:
@@ -575,15 +575,18 @@ class TradingEngine:
|
||||
open_count = 0
|
||||
try:
|
||||
pos_rows = await self.pool.fetch(
|
||||
"SELECT quantity, avg_entry_price FROM positions WHERE quantity > 0"
|
||||
"SELECT quantity, avg_entry_price, current_price, unrealized_pnl FROM positions WHERE quantity > 0"
|
||||
)
|
||||
for pr in pos_rows:
|
||||
invested += float(pr["quantity"]) * float(pr["avg_entry_price"])
|
||||
invested += float(pr["quantity"]) * float(pr["current_price"] or pr["avg_entry_price"])
|
||||
open_count += 1
|
||||
except Exception:
|
||||
logger.debug("Could not load positions — assuming no invested capital")
|
||||
|
||||
available = max(0.0, initial_capital - reserve_balance - invested)
|
||||
# Use portfolio_value (equity) as the total, not initial_capital
|
||||
# Available = equity - invested market value is wrong with margin
|
||||
# Instead use: buying_power from broker or equity - long_market_value
|
||||
available = max(0.0, initial_capital - invested)
|
||||
self.portfolio_state = PortfolioState(
|
||||
reserve_pool=reserve_balance,
|
||||
active_pool=available,
|
||||
@@ -945,9 +948,9 @@ class TradingEngine:
|
||||
try:
|
||||
if self.pool is not None:
|
||||
pos_rows = await self.pool.fetch(
|
||||
"SELECT quantity, avg_entry_price FROM positions WHERE quantity > 0"
|
||||
"SELECT quantity, avg_entry_price, current_price FROM positions WHERE quantity > 0"
|
||||
)
|
||||
invested = sum(float(r["quantity"]) * float(r["avg_entry_price"]) for r in pos_rows)
|
||||
invested = sum(float(r["quantity"]) * float(r["current_price"] or r["avg_entry_price"]) for r in pos_rows)
|
||||
open_count = len(pos_rows)
|
||||
available = max(0.0, self.portfolio_state.total_value - self.portfolio_state.reserve_pool - invested)
|
||||
self.portfolio_state.active_pool = available
|
||||
|
||||
Reference in New Issue
Block a user