Spaces:
Sleeping
Sleeping
File size: 10,019 Bytes
2e658e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | from __future__ import annotations
import asyncio
import json
import pytest
import trading.domain.execution_service as execution_module
from trading.adapters.paper_adapter import PaperExchangeAdapter
from trading.domain.approvals import create_approval
from trading.domain.execution_contracts import ExecuteApprovedPlanCommand, ExecutionErrorCode
from trading.domain.execution_service import ExecutionService, ExecutionServiceError
from trading.domain.identity_repo import ensure_paper_exchange_account
from trading.domain.plan_revalidation import PlanRevalidationResult
from trading.domain.plans_repo import create_plan
from trading.domain.risk_limits import MarketRiskContext, RiskRejected
from trading.domain.schema import apply_migrations, connect
from trading.futures_execution import TradingError
class SpyPaperAdapter(PaperExchangeAdapter):
def __init__(self, *, default_price: float = 100.0) -> None:
super().__init__(default_price=default_price)
self.load_market_calls = 0
self.configure_calls = 0
self.create_order_calls = 0
async def load_markets(self):
self.load_market_calls += 1
return await super().load_markets()
async def configure_account(self, symbol, leverage, margin_mode, position_mode):
self.configure_calls += 1
return await super().configure_account(symbol, leverage, margin_mode, position_mode)
async def create_order(self, req):
self.create_order_calls += 1
return await super().create_order(req)
@pytest.fixture(autouse=True)
def _db(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setenv("TRADING_MODE", "paper")
monkeypatch.setenv("HERMES_EXECUTION_ENABLED", "true")
ok, messages = apply_migrations()
assert ok, messages
def _plan(**overrides):
plan = {
"symbol": "BTCUSDT",
"decision": "LONG",
"entry": 100.0,
"stop_loss": 95.0,
"take_profit": 110.0,
"leverage": 3,
"quantity": 1.0,
"risk_profile": "moderate",
"risk_percent": 0.01,
"futuresVerified": True,
"noTradeGuard": False,
"trading_readiness": "ready",
"executable": True,
"expires_at": "2099-01-01T00:00:00Z",
}
plan.update(overrides)
return plan
def _accepted(plan_id: str) -> PlanRevalidationResult:
return PlanRevalidationResult(
revalidation_id=f"rv-{plan_id}",
accepted=True,
reasons=(),
context_hash="context-hash",
observed_price=100.0,
observed_spread_bps=1.0,
observed_slippage_percent=0.0,
market_risk=MarketRiskContext(
provider_fresh=True,
reconciliation_clear=True,
spread_bps=1.0,
funding_rate=0.0,
liquidity_ok=True,
),
orderbook={"bids": [[99.9, 100]], "asks": [[100.0, 100]]},
)
def _setup(owner_id: str = "owner-validation"):
account = ensure_paper_exchange_account(owner_id)
plan = create_plan(_plan(), owner_id=owner_id, account_id=account.account_id)
approval_id = create_approval(
plan["plan_id"], plan["plan_hash"], owner_id, account_id=account.account_id,
)
return owner_id, account, plan, approval_id
def _command(base_owner_id, base_account, plan, approval_id, **overrides):
values = {
"plan_id": plan["plan_id"],
"approval_id": approval_id,
"owner_id": base_owner_id,
"account_id": base_account.account_id,
"session_id": None,
"idempotency_key": f"validation:{plan['plan_id']}:{approval_id}",
}
values.update(overrides)
return ExecuteApprovedPlanCommand(**values)
def test_binding_mode_integrity_and_revalidation_fail_before_adapter_calls(monkeypatch):
owner_id, account, plan, approval_id = _setup()
adapter = SpyPaperAdapter()
service = ExecutionService(adapter)
async def rejected(plan_id, **_kwargs):
result = _accepted(plan_id)
return PlanRevalidationResult(
**{**result.__dict__, "accepted": False, "reasons": ("plan expired",)}
)
async def run():
with pytest.raises(ExecutionServiceError) as owner_error:
await service.execute_approved_plan(
_command(owner_id, account, plan, approval_id, owner_id="other-owner")
)
assert owner_error.value.code is ExecutionErrorCode.BINDING_MISMATCH
with pytest.raises(ExecutionServiceError) as account_error:
await service.execute_approved_plan(
_command(owner_id, account, plan, approval_id, account_id="other-account")
)
assert account_error.value.code is ExecutionErrorCode.BINDING_MISMATCH
conn = connect()
try:
conn.execute("UPDATE plans SET mode='testnet' WHERE plan_id=?", (plan["plan_id"],))
conn.commit()
finally:
conn.close()
with pytest.raises(ExecutionServiceError) as mode_error:
await service.execute_approved_plan(_command(owner_id, account, plan, approval_id))
assert mode_error.value.code is ExecutionErrorCode.MODE_NOT_ALLOWED
conn = connect()
try:
conn.execute("UPDATE plans SET mode='paper' WHERE plan_id=?", (plan["plan_id"],))
row = conn.execute("SELECT payload FROM plans WHERE plan_id=?", (plan["plan_id"],)).fetchone()
payload = json.loads(row[0])
payload["entry"] = 101.0
conn.execute("UPDATE plans SET payload=? WHERE plan_id=?", (json.dumps(payload), plan["plan_id"]))
conn.commit()
finally:
conn.close()
with pytest.raises(ExecutionServiceError) as hash_error:
await service.execute_approved_plan(_command(owner_id, account, plan, approval_id))
assert hash_error.value.code is ExecutionErrorCode.PLAN_INTEGRITY_FAILED
# Restore immutable payload and then prove an expiry/freshness rejection also
# occurs before any adapter account mutation or submission.
conn = connect()
try:
conn.execute("UPDATE plans SET payload=? WHERE plan_id=?", (json.dumps(plan), plan["plan_id"]))
conn.commit()
finally:
conn.close()
monkeypatch.setattr(execution_module, "revalidate_plan", rejected)
with pytest.raises(ExecutionServiceError) as stale_error:
await service.execute_approved_plan(_command(owner_id, account, plan, approval_id))
assert stale_error.value.code is ExecutionErrorCode.REVALIDATION_FAILED
asyncio.run(run())
assert adapter.load_market_calls == 0
assert adapter.configure_calls == 0
assert adapter.create_order_calls == 0
def test_nonfinite_geometry_and_final_risk_fail_before_configuration_or_submission(monkeypatch):
adapter = SpyPaperAdapter()
service = ExecutionService(adapter)
async def run():
with pytest.raises(TradingError, match="finite and positive"):
await service._submit_entry(
symbol="BTCUSDT", side="long", size=float("nan"), price=100.0,
stop_loss=95.0, take_profit=110.0,
)
assert adapter.load_market_calls == 0
def reject_risk(**_kwargs):
raise RiskRejected("final risk rejected")
monkeypatch.setattr(execution_module, "assert_entry_allowed", reject_risk)
with pytest.raises(RiskRejected, match="final risk rejected"):
await service._submit_entry(
symbol="BTCUSDT", side="long", size=1.0, price=100.0,
stop_loss=95.0, take_profit=110.0,
)
asyncio.run(run())
assert adapter.configure_calls == 0
assert adapter.create_order_calls == 0
def test_unverified_market_fails_before_account_configuration_or_submission():
class MissingMarketAdapter(SpyPaperAdapter):
async def load_markets(self):
self.load_market_calls += 1
return {}
adapter = MissingMarketAdapter()
service = ExecutionService(adapter)
async def run():
with pytest.raises(TradingError, match="market metadata unavailable"):
await service._submit_entry(
symbol="BTCUSDT", side="long", size=1.0, price=100.0,
stop_loss=95.0, take_profit=110.0,
)
asyncio.run(run())
assert adapter.load_market_calls == 1
assert adapter.configure_calls == 0
assert adapter.create_order_calls == 0
def test_existing_exposure_is_reconciled_before_second_configuration_or_submission(monkeypatch):
owner_id, account, first_plan, first_approval = _setup("owner-exposure")
adapter = SpyPaperAdapter()
service = ExecutionService(adapter)
async def accepted(plan_id, **_kwargs):
return _accepted(plan_id)
monkeypatch.setattr(execution_module, "revalidate_plan", accepted)
async def run():
first = await service.execute_approved_plan(
_command(owner_id, account, first_plan, first_approval)
)
assert first["status"] == "protected"
baseline = (adapter.load_market_calls, adapter.configure_calls, adapter.create_order_calls)
second_plan = create_plan(
_plan(entry=101.0, stop_loss=96.0, take_profit=111.0),
owner_id=owner_id,
account_id=account.account_id,
)
second_approval = create_approval(
second_plan["plan_id"], second_plan["plan_hash"], owner_id,
account_id=account.account_id,
)
with pytest.raises(ExecutionServiceError, match="existing exposure") as caught:
await service.execute_approved_plan(
_command(owner_id, account, second_plan, second_approval)
)
assert caught.value.code is ExecutionErrorCode.EXECUTION_FAILED
assert (adapter.load_market_calls, adapter.configure_calls, adapter.create_order_calls) == baseline
asyncio.run(run())
|