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:
anor
2026-03-15 18:21:44 +10:00
co-authored by Claude Opus 4.6
parent 6d049191b1
commit 12d28d6617
3 changed files with 457 additions and 140 deletions
+231 -26
View File
@@ -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