refactor: exchange as source of truth вместо DB-first reconcile
Бот теперь спрашивает биржу "что открыто?" перед каждым решением. DB → журнал для trailing state, а не source of truth. - _get_exchange_position: получает позицию с биржи (futures/spot/paper) - _adopt_orphan: биржа имеет, DB нет → создаёт запись (только futures) - _close_phantom: DB имеет, биржа нет → закрывает с Bybit PnL - _sync_position_size: синхронизирует size при расхождении >2% - _inline_reconcile: оркестрирует три предыдущие функции - run_cycle/update_stops: exchange-first → inline reconcile → решения - Удалён reconcile_positions (логика встроена в основной flow) - 8 новых тестов, все 55 проходят Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+225
-113
@@ -50,115 +50,201 @@ def _get_executor(cfg: Config, asset_cfg: AssetConfig):
|
||||
return _get_spot(cfg)
|
||||
|
||||
|
||||
def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
"""Sync DB positions with actual exchange state.
|
||||
def _get_exchange_position(cfg: Config, asset_cfg: AssetConfig):
|
||||
"""Get current position from exchange (source of truth).
|
||||
|
||||
Detects positions closed externally (by user on exchange UI) and
|
||||
updates DB accordingly. Call at start of every cycle.
|
||||
Returns list of log messages.
|
||||
Returns:
|
||||
dict with keys: size, side, entryPrice, direction — if position exists
|
||||
None — no position on exchange (confirmed)
|
||||
"API_ERROR" — API call failed, skip this asset
|
||||
"""
|
||||
if cfg.mode != "live":
|
||||
return None # paper mode: DB is source of truth
|
||||
|
||||
executor = _get_executor(cfg, asset_cfg)
|
||||
|
||||
if cfg.is_futures(asset_cfg):
|
||||
from .futures import FuturesExecutor
|
||||
result = executor.get_position(asset_cfg.symbol)
|
||||
if result == FuturesExecutor.API_ERROR:
|
||||
return "API_ERROR"
|
||||
if result is None:
|
||||
return None
|
||||
# Normalize direction: side "long"→1, "short"→-1
|
||||
direction = 1 if result["side"] == "long" else -1
|
||||
result["direction"] = direction
|
||||
return result
|
||||
else:
|
||||
# Spot: check coin balance
|
||||
coin = asset_cfg.symbol.split("/")[0]
|
||||
coin_balance = executor.get_balance(coin)
|
||||
if coin_balance is None:
|
||||
return "API_ERROR"
|
||||
# Spot: need price to determine USD value
|
||||
current_price = executor.get_price(asset_cfg.symbol)
|
||||
if current_price is None:
|
||||
return "API_ERROR"
|
||||
# Only count as position if USD value ≥ $5 (Bybit min order)
|
||||
if coin_balance * current_price < 5.0:
|
||||
return None
|
||||
return {
|
||||
"size": coin_balance,
|
||||
"side": "long",
|
||||
"entryPrice": current_price, # spot: no avg entry from exchange
|
||||
"direction": 1,
|
||||
}
|
||||
|
||||
|
||||
def _adopt_orphan(conn, ticker, exchange_pos, asset_cfg, cfg):
|
||||
"""Exchange has position, DB doesn't — create DB record.
|
||||
|
||||
Returns log message.
|
||||
"""
|
||||
# Ensure asset exists in DB (FK constraint)
|
||||
asset = _get_or_skip(conn, ticker)
|
||||
if asset is None:
|
||||
log.error(f"{ticker}: cannot adopt orphan — asset not initialized")
|
||||
return f"{ticker}: ADOPT failed — asset not initialized"
|
||||
|
||||
direction = exchange_pos["direction"]
|
||||
entry_price = exchange_pos["entryPrice"]
|
||||
size = exchange_pos["size"]
|
||||
pos_value = size * entry_price
|
||||
|
||||
# Default stop: entry ± 5% (trailing will adjust)
|
||||
stop_dist = entry_price * 0.05
|
||||
stop_price = entry_price - direction * stop_dist
|
||||
|
||||
pos_id = open_position(
|
||||
conn, ticker=ticker, direction=direction,
|
||||
entry_price=entry_price, entry_date=str(date.today()),
|
||||
stop_price=stop_price, stop_dist=stop_dist,
|
||||
best_price=entry_price, pos_size=size,
|
||||
pos_value=pos_value, correlation=0.0, k_used=2,
|
||||
)
|
||||
|
||||
dir_str = "LONG" if direction == 1 else "SHORT"
|
||||
log.warning(f"{ticker}: ADOPT orphan {dir_str} {size:.4f} "
|
||||
f"@ ${entry_price:,.4f} (pos_id={pos_id})")
|
||||
return (f"{ticker}: ADOPT orphan {dir_str} {size:.4f} "
|
||||
f"@ ${entry_price:,.4f}")
|
||||
|
||||
|
||||
def _close_phantom(conn, db_pos, ticker, asset_cfg, cfg):
|
||||
"""DB has position, exchange doesn't — close in DB with real PnL.
|
||||
|
||||
Returns log message.
|
||||
"""
|
||||
executor = _get_executor(cfg, asset_cfg)
|
||||
|
||||
# Try to get real PnL from Bybit
|
||||
current_price = executor.get_price(asset_cfg.symbol)
|
||||
if current_price is None:
|
||||
current_price = db_pos["entry_price"]
|
||||
|
||||
if cfg.is_futures(asset_cfg):
|
||||
closed = executor.get_closed_pnl(asset_cfg.symbol)
|
||||
if (closed and
|
||||
abs(closed["entryPrice"] - db_pos["entry_price"]) <
|
||||
db_pos["entry_price"] * 0.02):
|
||||
pnl_net = closed["closedPnl"]
|
||||
current_price = closed["exitPrice"]
|
||||
pnl_pct = pnl_net / db_pos["pos_value"] if db_pos["pos_value"] else 0
|
||||
log.info(f"{ticker}: using Bybit closedPnl=${pnl_net:+.4f} "
|
||||
f"exit=${current_price:.4f}")
|
||||
else:
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
db_pos["entry_price"], current_price, db_pos["direction"],
|
||||
db_pos["pos_size"], db_pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
else:
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
db_pos["entry_price"], current_price, db_pos["direction"],
|
||||
db_pos["pos_size"], db_pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
|
||||
close_position(conn, db_pos["id"],
|
||||
exit_price=current_price,
|
||||
exit_date=str(date.today()),
|
||||
exit_reason="external",
|
||||
pnl_net=pnl_net, pnl_pct=pnl_pct)
|
||||
|
||||
asset = _get_or_skip(conn, ticker)
|
||||
if asset:
|
||||
new_equity = asset["equity"] + pnl_net
|
||||
new_peak = max(asset["peak_equity"], new_equity)
|
||||
win = pnl_net > 0
|
||||
update_asset(conn, ticker,
|
||||
equity=new_equity, peak_equity=new_peak,
|
||||
trades_count=asset["trades_count"] + 1,
|
||||
wins=asset["wins"] + (1 if win else 0),
|
||||
losses=asset["losses"] + (0 if win else 1),
|
||||
total_pnl=asset["total_pnl"] + pnl_net)
|
||||
|
||||
# Cancel orphaned safety stop (spot only — futures SL auto-removed)
|
||||
safety_id = db_pos.get("safety_stop_order_id")
|
||||
if safety_id and safety_id not in ("dry_run", "position_sl"):
|
||||
executor.cancel_order(asset_cfg.symbol, safety_id)
|
||||
|
||||
dir_str = "LONG" if db_pos["direction"] == 1 else "SHORT"
|
||||
log.warning(f"{ticker}: PHANTOM {dir_str} closed externally "
|
||||
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
|
||||
return (f"{ticker}: PHANTOM {dir_str} closed externally "
|
||||
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
|
||||
|
||||
|
||||
def _sync_position_size(conn, db_pos, exchange_pos, ticker, cfg=None, asset_cfg=None):
|
||||
"""Both exist but size diverges >2% — sync DB from exchange.
|
||||
|
||||
Returns log message or None.
|
||||
"""
|
||||
ex_size = exchange_pos["size"]
|
||||
db_size = db_pos["pos_size"]
|
||||
if abs(ex_size - db_size) <= db_size * 0.02:
|
||||
return None
|
||||
|
||||
# Use current price for pos_value (not entryPrice which is avg entry)
|
||||
price = db_pos["entry_price"] # fallback
|
||||
if cfg and asset_cfg:
|
||||
executor = _get_executor(cfg, asset_cfg)
|
||||
current = executor.get_price(asset_cfg.symbol)
|
||||
if current:
|
||||
price = current
|
||||
new_value = ex_size * price
|
||||
update_position(conn, db_pos["id"],
|
||||
pos_size=ex_size, pos_value=new_value)
|
||||
log.info(f"{ticker}: size synced {db_size:.4f} → {ex_size:.4f}")
|
||||
return f"{ticker}: SIZE synced {db_size:.4f} → {ex_size:.4f}"
|
||||
|
||||
|
||||
def _inline_reconcile(conn, ticker, exchange_pos, db_pos, asset_cfg, cfg):
|
||||
"""Inline reconcile: adopt orphan, close phantom, or sync size.
|
||||
|
||||
Returns list of log messages. After this, db_pos is guaranteed
|
||||
to match exchange reality.
|
||||
"""
|
||||
logs = []
|
||||
if cfg.mode != "live":
|
||||
return logs
|
||||
|
||||
for asset_cfg in cfg.assets:
|
||||
ticker = asset_cfg.ticker
|
||||
pos = get_open_position(conn, ticker)
|
||||
if pos is None:
|
||||
continue
|
||||
|
||||
executor = _get_executor(cfg, asset_cfg)
|
||||
|
||||
if exchange_pos and not db_pos:
|
||||
# Only adopt orphans for futures (unambiguous positions).
|
||||
# Spot balances are ambiguous (airdrops, manual buys, staking).
|
||||
if cfg.is_futures(asset_cfg):
|
||||
# Futures: check position via fetch_positions
|
||||
from .futures import FuturesExecutor
|
||||
fut_pos = executor.get_position(asset_cfg.symbol)
|
||||
if fut_pos == FuturesExecutor.API_ERROR:
|
||||
log.warning(f"{ticker}: reconcile skipped — position API error")
|
||||
logs.append(f"{ticker}: RECONCILE skipped — position API error")
|
||||
continue
|
||||
if fut_pos is None:
|
||||
coin_balance = 0.0 # no position = closed
|
||||
else:
|
||||
coin_balance = fut_pos["size"]
|
||||
msg = _adopt_orphan(conn, ticker, exchange_pos, asset_cfg, cfg)
|
||||
logs.append(msg)
|
||||
else:
|
||||
# Spot: check coin balance
|
||||
coin = asset_cfg.symbol.split("/")[0]
|
||||
coin_balance = executor.get_balance(coin)
|
||||
log.info(f"{ticker}: spot balance detected without DB position — ignoring")
|
||||
|
||||
if coin_balance is None:
|
||||
log.warning(f"{ticker}: reconcile skipped — balance API error")
|
||||
logs.append(f"{ticker}: RECONCILE skipped — balance API error")
|
||||
continue
|
||||
min_threshold = pos["pos_size"] * 0.1 # <10% of position = closed
|
||||
|
||||
if coin_balance < min_threshold:
|
||||
# Position was closed externally (SL, user, or liquidation)
|
||||
current_price = executor.get_price(asset_cfg.symbol)
|
||||
if current_price is None:
|
||||
current_price = pos["entry_price"] # fallback
|
||||
|
||||
# For futures: use Bybit's actual closed PnL (includes fees, slippage)
|
||||
if cfg.is_futures(asset_cfg):
|
||||
closed = executor.get_closed_pnl(asset_cfg.symbol)
|
||||
if closed and abs(closed["entryPrice"] - pos["entry_price"]) < pos["entry_price"] * 0.02:
|
||||
pnl_net = closed["closedPnl"]
|
||||
current_price = closed["exitPrice"]
|
||||
pnl_pct = pnl_net / pos["pos_value"] if pos["pos_value"] else 0
|
||||
log.info(f"{ticker}: using Bybit closedPnl=${pnl_net:+.4f} "
|
||||
f"exit=${current_price:.4f}")
|
||||
else:
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
pos["entry_price"], current_price, pos["direction"],
|
||||
pos["pos_size"], pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
else:
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
pos["entry_price"], current_price, pos["direction"],
|
||||
pos["pos_size"], pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
|
||||
close_position(conn, pos["id"],
|
||||
exit_price=current_price,
|
||||
exit_date=str(date.today()),
|
||||
exit_reason="external",
|
||||
pnl_net=pnl_net, pnl_pct=pnl_pct)
|
||||
|
||||
asset = _get_or_skip(conn, ticker)
|
||||
if asset:
|
||||
new_equity = asset["equity"] + pnl_net
|
||||
new_peak = max(asset["peak_equity"], new_equity)
|
||||
win = pnl_net > 0
|
||||
update_asset(conn, ticker,
|
||||
equity=new_equity, peak_equity=new_peak,
|
||||
trades_count=asset["trades_count"] + 1,
|
||||
wins=asset["wins"] + (1 if win else 0),
|
||||
losses=asset["losses"] + (0 if win else 1),
|
||||
total_pnl=asset["total_pnl"] + pnl_net)
|
||||
|
||||
# Cancel orphaned safety stop (spot only — futures SL auto-removed)
|
||||
safety_id = pos.get("safety_stop_order_id")
|
||||
if safety_id and safety_id not in ("dry_run", "position_sl"):
|
||||
executor.cancel_order(asset_cfg.symbol, safety_id)
|
||||
|
||||
dir_str = "LONG" if pos["direction"] == 1 else "SHORT"
|
||||
log.warning(f"{ticker}: reconcile — {dir_str} closed externally "
|
||||
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
|
||||
logs.append(f"{ticker}: RECONCILE — {dir_str} closed externally "
|
||||
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
|
||||
else:
|
||||
# Position exists — update DB with actual size if different
|
||||
if abs(coin_balance - pos["pos_size"]) > pos["pos_size"] * 0.02:
|
||||
current_price = executor.get_price(asset_cfg.symbol) or pos["entry_price"]
|
||||
update_position(conn, pos["id"],
|
||||
pos_size=coin_balance,
|
||||
pos_value=coin_balance * current_price)
|
||||
logs.append(f"{ticker}: RECONCILE — size adjusted "
|
||||
f"{pos['pos_size']:.4f} → {coin_balance:.4f}")
|
||||
elif not exchange_pos and db_pos:
|
||||
msg = _close_phantom(conn, db_pos, ticker, asset_cfg, cfg)
|
||||
logs.append(msg)
|
||||
elif exchange_pos and db_pos:
|
||||
msg = _sync_position_size(conn, db_pos, exchange_pos, ticker, cfg, asset_cfg)
|
||||
if msg:
|
||||
logs.append(msg)
|
||||
|
||||
return logs
|
||||
|
||||
@@ -176,11 +262,6 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
logs = []
|
||||
today = str(date.today())
|
||||
|
||||
# Reconcile DB with exchange reality first
|
||||
if cfg.mode == "live":
|
||||
recon_logs = reconcile_positions(conn, cfg)
|
||||
logs.extend(recon_logs)
|
||||
|
||||
if cfg.mode == "live" and len(cfg.assets) > 1:
|
||||
log.warning(f"Live mode with {len(cfg.assets)} assets — "
|
||||
f"exchange balance is shared, not per-asset")
|
||||
@@ -231,8 +312,27 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
reason_str = f"dd_cooldown ({cb_details['hours']}h)"
|
||||
logs.append(f"{ticker}: CB {'ON — ' + reason_str if cb_active else 'OFF — ' + reason_str}")
|
||||
|
||||
# 1. Check open position
|
||||
# 1. Exchange-first: get real position state (live only)
|
||||
exchange_pos = _get_exchange_position(cfg, asset_cfg)
|
||||
if exchange_pos == "API_ERROR":
|
||||
logs.append(f"{ticker}: exchange API error — SKIP")
|
||||
continue
|
||||
|
||||
# 2. DB position (for trailing state)
|
||||
pos = get_open_position(conn, ticker)
|
||||
|
||||
# 3. Inline reconcile: adopt orphan / close phantom / sync size
|
||||
if cfg.mode == "live":
|
||||
recon_logs = _inline_reconcile(
|
||||
conn, ticker, exchange_pos, pos, asset_cfg, cfg)
|
||||
logs.extend(recon_logs)
|
||||
# Re-fetch after reconcile
|
||||
pos = get_open_position(conn, ticker)
|
||||
asset = _get_or_skip(conn, ticker)
|
||||
if asset is None:
|
||||
continue
|
||||
|
||||
# 4. Check open position
|
||||
if pos is not None:
|
||||
msg = _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg)
|
||||
if msg:
|
||||
@@ -245,7 +345,7 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
asset = _get_or_skip(conn, ticker)
|
||||
pos = get_open_position(conn, ticker)
|
||||
|
||||
# 2. New signal (if no position and CB off)
|
||||
# 5. New signal (if no position and CB off)
|
||||
if pos is None and not cb_active:
|
||||
# Check max open positions
|
||||
open_count = _count_open_positions(conn)
|
||||
@@ -877,12 +977,24 @@ def update_stops(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
if cfg.mode != "live":
|
||||
return logs
|
||||
|
||||
# Reconcile first — detect externally closed positions
|
||||
recon_logs = reconcile_positions(conn, cfg)
|
||||
logs.extend(recon_logs)
|
||||
|
||||
for asset_cfg in cfg.assets:
|
||||
ticker = asset_cfg.ticker
|
||||
|
||||
# Exchange-first: get real position state
|
||||
exchange_pos = _get_exchange_position(cfg, asset_cfg)
|
||||
if exchange_pos == "API_ERROR":
|
||||
logs.append(f"{ticker}: exchange API error — skip stop update")
|
||||
continue
|
||||
|
||||
# DB position (for trailing state)
|
||||
db_pos = get_open_position(conn, ticker)
|
||||
|
||||
# Inline reconcile
|
||||
recon_logs = _inline_reconcile(
|
||||
conn, ticker, exchange_pos, db_pos, asset_cfg, cfg)
|
||||
logs.extend(recon_logs)
|
||||
|
||||
# Re-fetch after reconcile
|
||||
pos = get_open_position(conn, ticker)
|
||||
if pos is None:
|
||||
continue
|
||||
|
||||
+231
-26
@@ -531,12 +531,13 @@ class TestCircuitBreakerIntegration:
|
||||
# ===========================================================================
|
||||
|
||||
class TestReconcilePositions:
|
||||
"""reconcile_positions syncs DB with actual exchange balances."""
|
||||
"""Inline reconcile (via _inline_reconcile) syncs DB with exchange."""
|
||||
|
||||
def test_skipped_in_paper_mode(self, db, cfg_paper):
|
||||
from remizov_trader.core.executor import reconcile_positions
|
||||
logs = reconcile_positions(db, cfg_paper)
|
||||
assert logs == []
|
||||
"""Paper mode: _inline_reconcile not called (exchange_pos=None)."""
|
||||
from remizov_trader.core.executor import _get_exchange_position
|
||||
result = _get_exchange_position(cfg_paper, cfg_paper.assets[0])
|
||||
assert result is None
|
||||
|
||||
def test_external_close_detected(self, db, cfg_live):
|
||||
upsert_asset(db, "UNI-USD", 84.0)
|
||||
@@ -546,19 +547,20 @@ class TestReconcilePositions:
|
||||
best_price=4.0, pos_size=22.0, pos_value=88.0,
|
||||
safety_stop_order_id="fake_order_123",
|
||||
)
|
||||
db_pos = get_open_position(db, "UNI-USD")
|
||||
|
||||
mock_spot = MagicMock()
|
||||
mock_spot.get_balance.return_value = 0.0
|
||||
mock_spot.get_price.return_value = 4.10
|
||||
mock_spot.cancel_order.return_value = True
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
from remizov_trader.core.executor import _close_phantom
|
||||
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
|
||||
from remizov_trader.core.executor import reconcile_positions
|
||||
logs = reconcile_positions(db, cfg_live)
|
||||
msg = _close_phantom(db, db_pos, "UNI-USD",
|
||||
cfg_live.assets[0], cfg_live)
|
||||
|
||||
assert get_open_position(db, "UNI-USD") is None
|
||||
assert any("RECONCILE" in log and "externally" in log for log in logs)
|
||||
assert "PHANTOM" in msg and "externally" in msg
|
||||
mock_spot.cancel_order.assert_called_once_with("UNI/USDC", "fake_order_123")
|
||||
|
||||
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
||||
@@ -571,20 +573,19 @@ class TestReconcilePositions:
|
||||
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
|
||||
best_price=4.0, pos_size=22.0, pos_value=88.0,
|
||||
)
|
||||
db_pos = get_open_position(db, "UNI-USD")
|
||||
exchange_pos = {
|
||||
"size": 18.0, "side": "long",
|
||||
"entryPrice": 4.05, "direction": 1,
|
||||
}
|
||||
|
||||
mock_spot = MagicMock()
|
||||
mock_spot.get_balance.return_value = 18.0
|
||||
mock_spot.get_price.return_value = 4.05
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
|
||||
from remizov_trader.core.executor import reconcile_positions
|
||||
logs = reconcile_positions(db, cfg_live)
|
||||
from remizov_trader.core.executor import _sync_position_size
|
||||
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
||||
|
||||
pos = get_open_position(db, "UNI-USD")
|
||||
assert pos["pos_size"] == pytest.approx(18.0)
|
||||
assert pos["pos_value"] == pytest.approx(18.0 * 4.05)
|
||||
assert any("size adjusted" in log for log in logs)
|
||||
assert msg is not None
|
||||
assert "SIZE synced" in msg
|
||||
|
||||
def test_no_change_when_position_matches(self, db, cfg_live):
|
||||
upsert_asset(db, "UNI-USD", 84.0)
|
||||
@@ -593,16 +594,16 @@ class TestReconcilePositions:
|
||||
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
|
||||
best_price=4.0, pos_size=22.0, pos_value=88.0,
|
||||
)
|
||||
db_pos = get_open_position(db, "UNI-USD")
|
||||
exchange_pos = {
|
||||
"size": 22.0, "side": "long",
|
||||
"entryPrice": 4.0, "direction": 1,
|
||||
}
|
||||
|
||||
mock_spot = MagicMock()
|
||||
mock_spot.get_balance.return_value = 22.0
|
||||
from remizov_trader.core.executor import _sync_position_size
|
||||
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
|
||||
from remizov_trader.core.executor import reconcile_positions
|
||||
logs = reconcile_positions(db, cfg_live)
|
||||
|
||||
assert logs == []
|
||||
assert msg is None
|
||||
assert get_open_position(db, "UNI-USD") is not None
|
||||
|
||||
|
||||
@@ -704,3 +705,207 @@ class TestStopDateFormat:
|
||||
# Must be parseable
|
||||
dt = datetime.fromisoformat(last_stop)
|
||||
assert dt.tzinfo is not None # must be timezone-aware
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# Exchange as Source of Truth — new tests
|
||||
# ===========================================================================
|
||||
|
||||
@pytest.fixture
|
||||
def cfg_futures_live():
|
||||
"""Live futures config for exchange-first tests."""
|
||||
return Config(
|
||||
mode="live",
|
||||
initial_capital=60.0,
|
||||
timeframe="1h",
|
||||
risk=RiskConfig(
|
||||
per_trade=0.05, max_position_pct=0.40,
|
||||
max_open_positions=3, leverage=1,
|
||||
time_exit=False, safety_stop_pct=0.10,
|
||||
),
|
||||
assets=[
|
||||
AssetConfig(
|
||||
ticker="UNI-USD", symbol="UNI/USDT:USDT",
|
||||
market_type="futures", retrain_enabled=False,
|
||||
K=2, shift=14, lr=0.005, stop_mult=1.25, stop_scale=0.75,
|
||||
cooldown_bars=3, shape_confirm=False, weight=0.34,
|
||||
timeframe="1h",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class TestExchangeFirst:
|
||||
"""Exchange as source of truth — inline reconcile tests."""
|
||||
|
||||
def test_api_error_skips_asset(self, db, cfg_futures_live):
|
||||
"""API_ERROR → skip asset, no crash, no decisions."""
|
||||
from remizov_trader.core.executor import _get_exchange_position
|
||||
|
||||
mock_executor = MagicMock()
|
||||
mock_executor.get_position.return_value = "API_ERROR"
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
with patch.object(exc_mod, '_get_futures', return_value=mock_executor):
|
||||
result = _get_exchange_position(cfg_futures_live, cfg_futures_live.assets[0])
|
||||
|
||||
assert result == "API_ERROR"
|
||||
|
||||
def test_phantom_closed(self, db, cfg_futures_live):
|
||||
"""DB open, exchange empty → DB closed with Bybit PnL."""
|
||||
from remizov_trader.core.executor import _close_phantom
|
||||
|
||||
upsert_asset(db, "UNI-USD", 60.0)
|
||||
open_position(
|
||||
db, ticker="UNI-USD", direction=1, entry_price=4.0,
|
||||
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
|
||||
best_price=4.0, pos_size=15.0, pos_value=60.0,
|
||||
safety_stop_order_id="position_sl",
|
||||
)
|
||||
db_pos = get_open_position(db, "UNI-USD")
|
||||
|
||||
mock_executor = MagicMock()
|
||||
mock_executor.get_price.return_value = 4.20
|
||||
mock_executor.get_closed_pnl.return_value = {
|
||||
"exitPrice": 4.20, "entryPrice": 4.0,
|
||||
"closedPnl": 2.85, "qty": 15.0, "side": "Buy",
|
||||
}
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
with patch.object(exc_mod, '_get_futures', return_value=mock_executor):
|
||||
msg = _close_phantom(db, db_pos, "UNI-USD",
|
||||
cfg_futures_live.assets[0], cfg_futures_live)
|
||||
|
||||
assert "PHANTOM" in msg
|
||||
assert get_open_position(db, "UNI-USD") is None
|
||||
|
||||
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
||||
assert asset["trades_count"] == 1
|
||||
assert asset["equity"] > 60.0 # profitable close
|
||||
|
||||
def test_orphan_adopted(self, db, cfg_futures_live):
|
||||
"""Exchange open, DB empty → DB record created."""
|
||||
from remizov_trader.core.executor import _adopt_orphan
|
||||
|
||||
upsert_asset(db, "UNI-USD", 60.0)
|
||||
exchange_pos = {
|
||||
"size": 15.0, "side": "long",
|
||||
"entryPrice": 4.0, "direction": 1,
|
||||
}
|
||||
|
||||
msg = _adopt_orphan(db, "UNI-USD", exchange_pos,
|
||||
cfg_futures_live.assets[0], cfg_futures_live)
|
||||
|
||||
assert "ADOPT" in msg
|
||||
pos = get_open_position(db, "UNI-USD")
|
||||
assert pos is not None
|
||||
assert pos["pos_size"] == 15.0
|
||||
assert pos["entry_price"] == 4.0
|
||||
assert pos["direction"] == 1
|
||||
|
||||
def test_no_duplicate_open(self, db, cfg_futures_live):
|
||||
"""Exchange has position → _check_signal not called (no duplicate)."""
|
||||
from remizov_trader.core.executor import run_cycle
|
||||
|
||||
upsert_asset(db, "UNI-USD", 60.0)
|
||||
open_position(
|
||||
db, ticker="UNI-USD", direction=1, entry_price=4.0,
|
||||
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
|
||||
best_price=4.0, pos_size=15.0, pos_value=60.0,
|
||||
)
|
||||
|
||||
prices = _make_prices(200, base=4.1, noise=0.001)
|
||||
dates = _make_dates(len(prices))
|
||||
|
||||
mock_executor = MagicMock()
|
||||
mock_executor.get_position.return_value = {
|
||||
"size": 15.0, "side": "long", "entryPrice": 4.0,
|
||||
"unrealizedPnl": 1.5,
|
||||
}
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
with patch.object(exc_mod, "signals") as mock_signals, \
|
||||
patch.object(exc_mod, '_get_futures', return_value=mock_executor), \
|
||||
patch.object(exc_mod.risk, "check_circuit_breaker",
|
||||
return_value=(False, None, {})):
|
||||
mock_signals.fetch_prices.return_value = (prices, dates)
|
||||
logs = run_cycle(db, cfg_futures_live)
|
||||
|
||||
# Should be holding, NOT opening a new signal
|
||||
log_text = " ".join(logs)
|
||||
assert "SIGNAL" not in log_text
|
||||
assert "holding" in log_text or "CLOSED" in log_text
|
||||
|
||||
def test_paper_mode_unchanged(self, db, cfg_paper):
|
||||
"""Paper mode = DB source of truth, no exchange calls."""
|
||||
from remizov_trader.core.executor import _get_exchange_position
|
||||
|
||||
result = _get_exchange_position(cfg_paper, cfg_paper.assets[0])
|
||||
assert result is None # paper mode returns None (use DB)
|
||||
|
||||
def test_inline_reconcile_sync_size(self, db, cfg_futures_live):
|
||||
"""Both exist but size diverges → sync from exchange."""
|
||||
from remizov_trader.core.executor import _sync_position_size
|
||||
|
||||
upsert_asset(db, "UNI-USD", 60.0)
|
||||
open_position(
|
||||
db, ticker="UNI-USD", direction=1, entry_price=4.0,
|
||||
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
|
||||
best_price=4.0, pos_size=15.0, pos_value=60.0,
|
||||
)
|
||||
db_pos = get_open_position(db, "UNI-USD")
|
||||
|
||||
exchange_pos = {
|
||||
"size": 12.0, "side": "long",
|
||||
"entryPrice": 4.0, "direction": 1,
|
||||
}
|
||||
|
||||
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
||||
|
||||
assert msg is not None
|
||||
assert "SIZE synced" in msg
|
||||
pos = get_open_position(db, "UNI-USD")
|
||||
assert pos["pos_size"] == pytest.approx(12.0)
|
||||
|
||||
def test_inline_reconcile_no_sync_when_close(self, db, cfg_futures_live):
|
||||
"""Size within 2% → no sync needed."""
|
||||
from remizov_trader.core.executor import _sync_position_size
|
||||
|
||||
upsert_asset(db, "UNI-USD", 60.0)
|
||||
open_position(
|
||||
db, ticker="UNI-USD", direction=1, entry_price=4.0,
|
||||
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
|
||||
best_price=4.0, pos_size=15.0, pos_value=60.0,
|
||||
)
|
||||
db_pos = get_open_position(db, "UNI-USD")
|
||||
|
||||
exchange_pos = {
|
||||
"size": 15.1, "side": "long",
|
||||
"entryPrice": 4.0, "direction": 1,
|
||||
}
|
||||
|
||||
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
||||
assert msg is None # within 2% tolerance
|
||||
|
||||
def test_run_cycle_exchange_first_skips_on_api_error(self, db, cfg_futures_live):
|
||||
"""run_cycle skips asset entirely on API error."""
|
||||
from remizov_trader.core.executor import run_cycle
|
||||
|
||||
upsert_asset(db, "UNI-USD", 60.0)
|
||||
prices = _make_prices()
|
||||
dates = _make_dates(len(prices))
|
||||
|
||||
mock_executor = MagicMock()
|
||||
mock_executor.get_position.return_value = "API_ERROR"
|
||||
|
||||
from remizov_trader.core import executor as exc_mod
|
||||
with patch.object(exc_mod, "signals") as mock_signals, \
|
||||
patch.object(exc_mod, '_get_futures', return_value=mock_executor), \
|
||||
patch.object(exc_mod.risk, "check_circuit_breaker",
|
||||
return_value=(False, None, {})):
|
||||
mock_signals.fetch_prices.return_value = (prices, dates)
|
||||
logs = run_cycle(db, cfg_futures_live)
|
||||
|
||||
log_text = " ".join(logs)
|
||||
assert "API error" in log_text
|
||||
assert "SIGNAL" not in log_text # no trading decision made
|
||||
|
||||
@@ -302,7 +302,7 @@ class TestCommission:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestReconcileFutures:
|
||||
"""Test reconcile_positions with futures."""
|
||||
"""Test futures config fields."""
|
||||
|
||||
def test_config_market_type_default(self):
|
||||
"""Default market_type should be 'spot'."""
|
||||
|
||||
Reference in New Issue
Block a user