Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): own unresolved Alpaca submissions

Mirandaddee2b9f823c
diff --git a/agent/src/live/audit.py b/agent/src/live/audit.py
index d8d6809d1..fea431b61 100644
--- a/agent/src/live/audit.py
+++ b/agent/src/live/audit.py
@@ -251,6 +251,7 @@ def write_live_action(
event_callback: EventCallback | None = None,
trace_writer: _TraceWriterLike | None = None,
chain: bool = True,
+ require_durable: bool = False,
) -> dict[str, Any]:
"""Fan a redacted live-action record out to up to three sinks (SPEC §5).
@@ -290,6 +291,7 @@ def write_live_action(
exact historical record shape and ledger file. Raises
:class:`src.governance.ledger.LedgerCorruptionError` if that
chain ledger's existing history is already broken.
+ require_durable: Raise when the classic ledger fsync fails.
Returns:
The redacted record dict — identical to what was written to every sink —
@@ -312,6 +314,8 @@ def write_live_action(
os.fsync(handle.fileno())
except OSError as exc:
_warn_fsync_failure(exc, path)
+ if require_durable:
+ raise
if chain:
from src.governance.ledger import append_record
diff --git a/agent/src/live/pending_action.py b/agent/src/live/pending_action.py
new file mode 100644
index 000000000..e56746033
--- /dev/null
+++ b/agent/src/live/pending_action.py
@@ -0,0 +1,175 @@
+"""Crash-safe ownership marker for one unresolved broker side effect."""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Literal, Mapping, Self
+
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
+
+from src.live.paths import broker_dir
+
+_FILENAME = "pending_action.json"
+
+
+class PendingActionError(RuntimeError):
+ """Raised when pending state cannot be trusted or durably changed."""
+
+
+class PendingOrderRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ symbol: str = Field(min_length=1)
+ side: Literal["buy", "sell"]
+ quantity: float | int | None
+ notional: float | int | None
+ order_type: Literal["market", "limit"]
+ limit_price: float | int | None
+ time_in_force: Literal["day", "gtc"]
+
+ @model_validator(mode="after")
+ def validate_order(self) -> Self:
+ if (self.quantity is None) == (self.notional is None):
+ raise ValueError("exactly one order size is required")
+ for value in (self.quantity, self.notional, self.limit_price):
+ if value is not None and (not math.isfinite(value) or value <= 0):
+ raise ValueError("order numerics must be finite and positive")
+ if (self.order_type == "limit") != (self.limit_price is not None):
+ raise ValueError("limit price must match the order type")
+ return self
+
+
+class PendingAction(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ schema_version: Literal[1]
+ broker: Literal["alpaca"]
+ action_id: str = Field(pattern=r"^act_[0-9a-f]{32}$")
+ phase: Literal["pending_write"]
+ kind: Literal["place_order"]
+ created_at: datetime
+ client_order_id: str = Field(min_length=1, max_length=48)
+ broker_order_id: None = None
+ request: PendingOrderRequest
+ pre_position_qty: float | int | None
+ remediation_attempts: Literal[0]
+
+ @model_validator(mode="after")
+ def validate_evidence(self) -> Self:
+ if self.created_at.tzinfo is None:
+ raise ValueError("created_at requires a timezone")
+ if self.pre_position_qty is not None and not math.isfinite(
+ self.pre_position_qty
+ ):
+ raise ValueError("pre-position quantity must be finite")
+ return self
+
+
+def new_pending_order(
+ broker: str,
+ request: Mapping[str, object],
+ *,
+ pre_position_qty: float | None,
+) -> PendingAction:
+ """Build the redaction-safe marker written immediately before submission."""
+ key = _broker_key(broker)
+ return PendingAction(
+ schema_version=1,
+ broker=key,
+ action_id=f"act_{uuid.uuid4().hex}",
+ phase="pending_write",
+ kind="place_order",
+ created_at=datetime.now(timezone.utc),
+ client_order_id=f"vt-{uuid.uuid4().hex}",
+ request=PendingOrderRequest(
+ symbol=str(request.get("symbol") or "").strip().upper(),
+ side=str(request.get("side") or "").strip().lower(),
+ quantity=request.get("quantity"),
+ notional=request.get("notional"),
+ order_type=str(request.get("order_type") or "market").strip().lower(),
+ limit_price=request.get("limit_price"),
+ time_in_force=str(request.get("time_in_force") or "day").strip().lower(),
+ ),
+ pre_position_qty=pre_position_qty,
+ remediation_attempts=0,
+ )
+
+
+def pending_action_path(broker: str) -> Path:
+ return broker_dir(_broker_key(broker)) / _FILENAME
+
+
+def load_pending_action(broker: str) -> PendingAction | None:
+ """Load strict pending evidence; malformed state raises and fails closed."""
+ path = pending_action_path(broker)
+ try:
+ payload = path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return None
+ except OSError as exc:
+ raise PendingActionError("pending action cannot be read") from exc
+ try:
+ return PendingAction.model_validate_json(payload)
+ except ValidationError as exc:
+ raise PendingActionError("pending action has an invalid schema") from exc
+
+
+def save_pending_action(action: PendingAction) -> None:
+ """Durably create pending evidence without replacing an existing marker."""
+ path = pending_action_path(action.broker)
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ if path.exists() or path.is_symlink():
+ raise PendingActionError("a pending broker action already exists")
+ payload = json.dumps(
+ action.model_dump(mode="json"),
+ allow_nan=False,
+ separators=(",", ":"),
+ sort_keys=True,
+ )
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
+ try:
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(payload + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ _fsync_directory(path.parent)
+ except Exception:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+ raise
+
+
+def clear_pending_action(broker: str, action_id: str) -> None:
+ """Durably remove exactly the marker whose resolution was audited."""
+ action = load_pending_action(broker)
+ if action is None or action.action_id != action_id:
+ raise PendingActionError("pending action changed before clear")
+ path = pending_action_path(broker)
+ path.unlink()
+ _fsync_directory(path.parent)
+
+
+def _broker_key(broker: str) -> str:
+ key = str(broker or "").strip().lower()
+ if key != "alpaca":
+ raise ValueError("pending submit ownership currently supports Alpaca only")
+ return key
+
+
+def _fsync_directory(directory: Path) -> None:
+ if os.name == "nt": # Windows has no portable directory fsync.
+ return
+ descriptor = os.open(directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
diff --git a/agent/src/live/sdk_order_gate.py b/agent/src/live/sdk_order_gate.py
index 4cb498e30..dc3e88016 100644
--- a/agent/src/live/sdk_order_gate.py
+++ b/agent/src/live/sdk_order_gate.py
@@ -27,6 +27,7 @@ import logging
from datetime import datetime, timezone
from typing import Any
+from src.live import pending_action
from src.live.audit import LiveActionEvent, write_live_action
from src.live.daily_count import (
DailyOrderLockUnavailable,
@@ -122,6 +123,22 @@ def execute_live_order(
try:
with daily_order_lock(broker):
+ if broker == "alpaca":
+ try:
+ unresolved = pending_action.load_pending_action(broker)
+ except pending_action.PendingActionError:
+ return _deny(
+ broker, session_id,
+ "pending broker action is invalid and requires recovery",
+ ["mandate", "expiry", "halt_flag", "pending_action"], mandate,
+ intent=intent, reason_code="pending_action_invalid",
+ )
+ if unresolved is not None:
+ return _deny(
+ broker, session_id, "pending broker action requires recovery",
+ ["mandate", "expiry", "halt_flag", "pending_action"], mandate,
+ intent=intent, reason_code="pending_action_unresolved",
+ )
daily_count = read_daily_count(broker)
breach = check_mandate(
mandate,
@@ -142,6 +159,7 @@ def execute_live_order(
intent,
place_kwargs,
mandate,
+ positions,
)
except DailyOrderLockUnavailable as exc:
return _deny(
@@ -384,8 +402,25 @@ def _execute_and_audit_live_action(
# --------------------------------------------------------------------------- #
-def _allow(broker, session_id, connector_module, config, intent, place_kwargs, mandate) -> dict[str, Any]:
+def _allow(broker, session_id, connector_module, config, intent, place_kwargs, mandate, positions) -> dict[str, Any]:
"""Execute the order; consume a count + audit only on a non-error result."""
+ pending = None
+ if broker == "alpaca":
+ try:
+ pending = pending_action.new_pending_order(
+ broker, place_kwargs,
+ pre_position_qty=_pre_position_qty(positions, intent.symbol),
+ )
+ pending_action.save_pending_action(pending)
+ except Exception as exc: # noqa: BLE001 - missing evidence forbids the write
+ logger.warning("pending action write failed for %s: %s", broker, exc)
+ return _deny(
+ broker, session_id, "pending broker action could not be persisted",
+ ["mandate", "expiry", "halt_flag", "pending_action"], mandate,
+ intent=intent, reason_code="pending_action_persist_failed",
+ )
+ place_kwargs = {**place_kwargs, "client_order_id": pending.client_order_id}
+
try:
result = connector_module.place_order(config, **place_kwargs)
except Exception as exc: # noqa: BLE001 - a connector raise must not escape the gate
@@ -417,7 +452,8 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
intent=intent,
broker_request=dict(place_kwargs),
broker_response=result if isinstance(result, dict) else {"raw": result},
- gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},
+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked,
+ **({"reason_code": "pending_action_unresolved"} if pending else {})},
error=_error_message(result),
)
else:
@@ -435,10 +471,25 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
)
if isinstance(result, dict) and record is not None:
result = {**result, LIVE_ACTION_RESULT_KEY: record}
+ if pending is not None:
+ cleared = False
+ if not is_error and record is not None:
+ try:
+ pending_action.clear_pending_action(broker, pending.action_id)
+ cleared = True
+ except Exception as exc: # noqa: BLE001 - retain the recovery block
+ logger.warning("pending action clear failed for %s: %s", broker, exc)
+ if not cleared:
+ result = {
+ **(result if isinstance(result, dict) else {"status": "error"}),
+ "client_order_id": pending.client_order_id,
+ "recovery_pending": True,
+ "reason_code": "pending_action_unresolved",
+ }
return result if isinstance(result, dict) else {"status": "error", "error": "non-dict broker result"}
-def _deny(broker, session_id, reason, checked, mandate, *, intent, reauth=False) -> dict[str, Any]:
+def _deny(broker, session_id, reason, checked, mandate, *, intent, reauth=False, reason_code=None) -> dict[str, Any]:
"""Audit + return a refusal for a pre-check / structural DENY."""
record = _audit(
broker,
@@ -449,10 +500,14 @@ def _deny(broker, session_id, reason, checked, mandate, *, intent, reauth=False)
intent=intent,
broker_request=None,
broker_response=None,
- gate_decision={"allowed": False, "decision": _DECISION_DENY, "checked_limits": checked},
+ gate_decision={"allowed": False, "decision": _DECISION_DENY, "checked_limits": checked,
+ **({"reason_code": reason_code} if reason_code else {})},
error=reason,
)
- return _refusal(broker, decision=_DECISION_DENY, reason=reason, reauth=reauth, record=record)
+ result = _refusal(broker, decision=_DECISION_DENY, reason=reason, reauth=reauth, record=record)
+ if reason_code:
+ result["reason_code"] = reason_code
+ return result
def _deny_breach(broker, session_id, breach, mandate, intent, reauth) -> dict[str, Any]:
@@ -631,6 +686,24 @@ def _safe_read(connector_module: Any, fn_name: str, config: Any) -> object:
return result
+def _pre_position_qty(positions: object, symbol: str) -> float | None:
+ rows = positions.get("positions", positions.get("data")) if isinstance(positions, dict) else positions
+ if not isinstance(rows, list):
+ return None
+ target = str(symbol or "").strip().upper()
+ for row in rows:
+ if not isinstance(row, dict) or str(row.get("symbol") or "").strip().upper() != target:
+ continue
+ try:
+ quantity = float(row.get("quantity", row.get("qty")))
+ except (TypeError, ValueError):
+ return None
+ if str(row.get("side") or "").strip().lower() in {"short", "sell"} and quantity > 0:
+ quantity = -quantity
+ return quantity
+ return 0.0
+
+
# --------------------------------------------------------------------------- #
# Audit + misc
# --------------------------------------------------------------------------- #
@@ -651,6 +724,7 @@ def _audit(
broker_response=broker_response,
gate_decision=gate_decision,
error=error,
+ require_durable=broker == "alpaca",
)
@@ -667,6 +741,7 @@ def _audit_action(
broker_response,
gate_decision,
error=None,
+ require_durable=False,
) -> dict | None:
consent = mandate.consent if mandate is not None else None
try:
@@ -685,9 +760,9 @@ def _audit_action(
error=error,
)
try:
- return write_live_action(event, event_callback=None, trace_writer=None)
+ return write_live_action(event, event_callback=None, trace_writer=None, require_durable=require_durable)
except TypeError:
- return write_live_action(event)
+ return None if require_durable else write_live_action(event)
except Exception as exc: # auditing must never block a decision
logger.warning("live-action audit write failed (%s): %s", kind, exc)
return None
diff --git a/agent/src/trading/connectors/alpaca/sdk.py b/agent/src/trading/connectors/alpaca/sdk.py
index d3e7120bb..f3173bdca 100644
--- a/agent/src/trading/connectors/alpaca/sdk.py
+++ b/agent/src/trading/connectors/alpaca/sdk.py
@@ -436,6 +436,7 @@ def place_order(
order_type: str = "market",
limit_price: float | None = None,
time_in_force: str = "day",
+ client_order_id: str | None = None,
) -> dict[str, Any]:
"""Submit an order to the configured Alpaca account.
@@ -454,6 +455,7 @@ def place_order(
order_type: ``market`` or ``limit``.
limit_price: Required when ``order_type`` is ``limit``.
time_in_force: ``day`` or ``gtc``.
+ client_order_id: Optional caller-owned exact order identity.
Returns:
On success ``{"status": "ok", "order_id", "symbol", "side", "profile",
@@ -480,6 +482,10 @@ def place_order(
if tif_token not in ("day", "gtc"):
return {"status": "error", "error": "time_in_force must be 'day' or 'gtc'"}
+ client_id = str(client_order_id).strip() if client_order_id is not None else None
+ if client_id is not None and not (1 <= len(client_id) <= 48):
+ return {"status": "error", "error": "client_order_id must contain 1-48 characters"}
+
has_qty = quantity is not None
has_notional = notional is not None
if has_qty == has_notional:
@@ -524,6 +530,7 @@ def place_order(
order_type=type_token,
limit_price=limit_value,
time_in_force=tif_token,
+ client_order_id=client_id,
)
try:
@@ -537,6 +544,7 @@ def place_order(
order_side = OrderSide.BUY if side_token == "buy" else OrderSide.SELL
tif = TimeInForce.DAY if tif_token == "day" else TimeInForce.GTC
amount = {"qty": qty_value} if has_qty else {"notional": notional_value}
+ identity = {"client_order_id": client_id} if client_id is not None else {}
if type_token == "limit":
req = LimitOrderRequest(
@@ -545,6 +553,7 @@ def place_order(
time_in_force=tif,
limit_price=limit_value,
**amount,
+ **identity,
)
else:
req = MarketOrderRequest(
@@ -552,6 +561,7 @@ def place_order(
side=order_side,
time_in_force=tif,
**amount,
+ **identity,
)
order = client.submit_order(order_data=req)
@@ -587,6 +597,7 @@ def _submit_via_tap(
order_type: str,
limit_price: float | None,
time_in_force: str,
+ client_order_id: str | None,
) -> dict[str, Any]:
"""Place the order through the TAP proxy instead of the Alpaca SDK.
@@ -617,12 +628,14 @@ def _submit_via_tap(
# forwarded the order but the agent saw a timeout) is deduplicated by Alpaca
# — a duplicate id is rejected, never double-placed. Trade-off: two
# intentionally-identical orders collide; vary any field for a real duplicate.
- order["client_order_id"] = "tap-" + hashlib.sha256(
- "|".join(
- str(x)
- for x in (cfg.profile, symbol, side, quantity, notional, order_type, limit_price, time_in_force)
- ).encode()
- ).hexdigest()[:24]
+ order["client_order_id"] = client_order_id or (
+ "tap-" + hashlib.sha256(
+ "|".join(
+ str(x)
+ for x in (cfg.profile, symbol, side, quantity, notional, order_type, limit_price, time_in_force)
+ ).encode()
+ ).hexdigest()[:24]
+ )
cred_headers = _tap_cred_headers()
target = f"{cfg.host}/v2/orders"
diff --git a/agent/tests/test_sdk_order_gate.py b/agent/tests/test_sdk_order_gate.py
index 802498a92..46ef3e711 100644
--- a/agent/tests/test_sdk_order_gate.py
+++ b/agent/tests/test_sdk_order_gate.py
@@ -7,16 +7,22 @@ connector module + a stubbed mandate/halt so they need no broker SDK.
from __future__ import annotations
+import json
+import sys
import threading
from contextlib import nullcontext
+from types import ModuleType, SimpleNamespace
import pytest
import src.live.paths as live_paths
from src.config.accessor import reset_env_config
+from src.live import audit as live_audit
+from src.live import pending_action as pending_state
from src.live import sdk_order_gate as gate
from src.live.daily_count import read_daily_count
from src.live.enforcement import OrderIntent
+from src.live.pending_action import load_pending_action, pending_action_path
from src.live.mandate.model import (
AssetClass,
ConsentMeta,
@@ -26,7 +32,9 @@ from src.live.mandate.model import (
UniverseConstraint,
)
from src.trading import service
+from src.trading.connectors.alpaca import sdk as alpaca_sdk
from src.trading.connectors.longbridge import credentials as lb_credentials
+from tests.module_os_helpers import patch_module_os
pytestmark = pytest.mark.unit
@@ -42,6 +50,7 @@ def _isolate_longbridge_credentials(monkeypatch, tmp_path):
monkeypatch.delenv(env_name, raising=False)
reset_env_config()
monkeypatch.setattr(lb_credentials, "get_runtime_root", lambda: tmp_path)
+ monkeypatch.setattr(live_paths, "get_runtime_root", lambda: tmp_path)
class _FakeConnector:
@@ -116,6 +125,14 @@ def _intent(notional=500.0, qty=None, asset=AssetClass.US_EQUITY):
)
+def _place(connector, **place_kwargs):
+ return gate.execute_live_order(
+ broker="alpaca", connector_module=connector, config=object(),
+ intent=_intent(),
+ place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0, **place_kwargs},
+ )
+
+
# --------------------------------------------------------------------------- #
# Gate decisions
# --------------------------------------------------------------------------- #
@@ -157,6 +174,150 @@ def test_gate_allows_in_bounds_and_places(monkeypatch) -> None:
assert "live_action" in out
+def test_alpaca_marker_precedes_submit_and_audit_precedes_clear(monkeypatch) -> None:
+ events: list[str] = []
+
+ class _OrderingConnector(_FakeConnector):
+ def place_order(self, config, **kwargs):
+ pending = load_pending_action("alpaca")
+ assert pending is not None and pending.phase == "pending_write"
+ assert pending.client_order_id == kwargs["client_order_id"]
+ events.append("submit")
+ return super().place_order(config, **kwargs)
+
+ _patch_gate(monkeypatch, mandate=_mandate())
+ def audited(*args, **kwargs):
+ record = live_audit.write_live_action(*args, **kwargs)
+ events.append("audit")
+ return record
+
+ monkeypatch.setattr(gate, "write_live_action", audited)
+ real_clear = pending_state.clear_pending_action
+ monkeypatch.setattr(pending_state, "clear_pending_action",
+ lambda broker, action_id: events.append("clear") or real_clear(broker, action_id))
+
+ connector = _OrderingConnector()
+ first = _place(connector)
+ second = _place(connector)
+
+ assert first["status"] == second["status"] == "ok"
+ assert events == ["submit", "audit", "clear"] * 2
+ assert connector.placed[0]["client_order_id"] != connector.placed[1]["client_order_id"]
+ assert live_audit.audit_ledger_path().is_file()
+ assert load_pending_action("alpaca") is None
+
+
+def test_pending_persist_failure_makes_zero_broker_calls(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+ connector = _FakeConnector()
+ patch_module_os(
+ monkeypatch, pending_state,
+ fsync=lambda descriptor: (_ for _ in ()).throw(OSError("disk full")),
+ )
+
+ result = _place(connector)
+
+ assert result["status"] == "blocked"
+ assert result["reason_code"] == "pending_action_persist_failed"
+ assert connector.placed == []
+ assert load_pending_action("alpaca") is None
+
+
+def test_uncertain_submit_survives_restart_and_blocks_new_risk(monkeypatch) -> None:
+ class _TimeoutConnector(_FakeConnector):
+ def place_order(self, config, **kwargs):
+ self.placed.append(kwargs)
+ raise TimeoutError("response lost")
+
+ _patch_gate(monkeypatch, mandate=_mandate())
+ connector = _TimeoutConnector()
+ first = _place(connector, api_key="must-not-persist")
+ restarted = load_pending_action("alpaca")
+ second = _place(connector)
+ raw = pending_action_path("alpaca").read_text(encoding="utf-8")
+
+ assert first["status"] == "error" and first["recovery_pending"] is True
+ assert first["reason_code"] == "pending_action_unresolved"
+ assert restarted is not None and restarted.client_order_id == connector.placed[0]["client_order_id"]
+ assert second["status"] == "blocked" and second["reason_code"] == "pending_action_unresolved"
+ assert len(connector.placed) == 1
+ assert "must-not-persist" not in raw and "api_key" not in raw
+ assert set(json.loads(raw)["request"]) == {
+ "symbol", "side", "quantity", "notional", "order_type", "limit_price", "time_in_force"
+ }
+
+
+def test_corrupt_pending_marker_and_failed_audit_both_fail_closed(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+ connector = _FakeConnector()
+ monkeypatch.setattr(gate, "write_live_action", lambda *a, **k: None)
+
+ result = _place(connector)
+ assert result["status"] == "ok" and result["recovery_pending"] is True
+ assert len(connector.placed) == 1
+
+ pending_action_path("alpaca").write_text('{"schema_version":999}\n', encoding="utf-8")
+ blocked = _place(connector)
+ assert blocked["status"] == "blocked" and blocked["reason_code"] == "pending_action_invalid"
+ assert len(connector.placed) == 1
+
+
+def test_audit_durability_failure_retains_pending_marker(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+ monkeypatch.setattr(gate, "write_live_action", live_audit.write_live_action)
+ connector = _FakeConnector()
+ patch_module_os(monkeypatch, live_audit, fsync=lambda fd: (_ for _ in ()).throw(OSError("disk")))
+
+ result = _place(connector)
+
+ assert result["status"] == "ok" and result["recovery_pending"] is True
+ assert result["reason_code"] == "pending_action_unresolved"
+ assert len(connector.placed) == 1 and load_pending_action("alpaca") is not None
+
+
+def test_external_client_id_reaches_direct_sdk_and_tap(monkeypatch) -> None:
+ captured: dict[str, object] = {}
+
+ class _Request:
+ def __init__(self, **kwargs):
+ captured["request"] = kwargs
+
+ class _Client:
+ def submit_order(self, *, order_data):
+ return SimpleNamespace(id="oid", status="accepted", filled_qty="0")
+
+ enums = ModuleType("alpaca.trading.enums")
+ enums.OrderSide = SimpleNamespace(BUY="buy", SELL="sell")
+ enums.TimeInForce = SimpleNamespace(DAY="day", GTC="gtc")
+ requests = ModuleType("alpaca.trading.requests")
+ requests.LimitOrderRequest = requests.MarketOrderRequest = _Request
+ monkeypatch.setitem(sys.modules, "alpaca.trading.enums", enums)
+ monkeypatch.setitem(sys.modules, "alpaca.trading.requests", requests)
+ monkeypatch.setattr(alpaca_sdk, "_trading_client", lambda cfg: _Client())
+ monkeypatch.setattr(alpaca_sdk.tap_forward, "tap_enabled", lambda: False)
+
+ direct = alpaca_sdk.place_order(
+ alpaca_sdk.AlpacaConfig(profile="paper"), symbol="AAPL", side="buy",
+ quantity=1, client_order_id="vt-direct",
+ )
+ assert direct["status"] == "ok" and captured["request"]["client_order_id"] == "vt-direct"
+ alpaca_sdk.place_order(alpaca_sdk.AlpacaConfig(profile="paper"),
+ symbol="AAPL", side="buy", quantity=1)
+ assert "client_order_id" not in captured["request"]
+
+ monkeypatch.setattr(alpaca_sdk.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(
+ alpaca_sdk.tap_forward, "forward",
+ lambda target, method, body, headers: captured.update(tap=json.loads(body))
+ or {"ok": True, "body": {"id": "tap-oid", "status": "accepted"}},
+ )
+ tap = alpaca_sdk.place_order(
+ alpaca_sdk.AlpacaConfig(profile="paper"), symbol="AAPL", side="buy",
+ quantity=1, client_order_id="vt-tap",
+ )
+ assert tap["status"] == "ok" and captured["tap"]["client_order_id"] == "vt-tap"
+
+
def test_gate_blocks_oversized_order(monkeypatch) -> None:
_patch_gate(monkeypatch, mandate=_mandate(max_order=100.0))
conn = _FakeConnector()
@@ -291,6 +452,8 @@ def test_gate_count_consumed_only_on_success(monkeypatch) -> None:
)
assert out["status"] == "error"
assert increments == [] # failed placement must not consume a daily count
+ assert out["recovery_pending"] is True
+ assert load_pending_action("alpaca") is not None
def test_concurrent_orders_share_one_daily_cap_permit(