8acc1e18f8
2026-08-04 Fable 5 QA audit, Batch A. All fixes are execution-robustness only — no signal code touched (git diff scope: daemon/executor/tests). Findings verified by runnable repros before fixing (h3 harness): - close_trade: a 200 whose close order was created but NOT filled (e.g. MARKET_HALTED during the settlement pause) now raises instead of returning; the daemon's timeout path keeps tracking and retries. The old path popped state and orphaned a live position forever (reconciliation was boot-only). - place_market_order: positionFill=OPEN_ONLY — on a netting account an opposite-side order can no longer silently close an untracked position; the divergence surfaces as an order cancel. - _execute_trade: a fill without tradeOpened (netting close/reduce) and any placement OandaAPIError (server may have filled before a network timeout) now trigger _reconcile_positions instead of silent return. - _discover_existing_positions → lock-guarded _reconcile_positions, callable mid-run; adoption of a position with NO broker stop now screams (CRITICAL + per-bar warning) instead of computing sl=entry, risk=0 and silently never trailing. - _manage_trailing: snapshot deep-copies per-trade dicts (no mutation of live state outside the lock); write-back skips trades popped by _check_closed_trades mid-iteration (no ghost resurrection). - Fail-closed config: unknown OANDA_QUALITY_GATE refuses to start (previously a typo silently became the most permissive gate "C"); non-integer OANDA_LOT_SIZE/MAX_HOLD_BARS exit with a clear message. Suite: 302 → 312 tests (Module 21), all green. Claude-Session: https://claude.ai/code/session_01UnZkzeFcTu9agFg8BDh2tn
231 lines
9.6 KiB
Python
231 lines
9.6 KiB
Python
"""
|
|
ForexBot2 — Oanda v20 Order Executor
|
|
======================================
|
|
Handles all Oanda account operations: market orders, trade queries,
|
|
SL/TP modification, and trade closure. Uses raw ``requests`` against
|
|
the Oanda v20 REST API — no extra dependencies.
|
|
"""
|
|
|
|
import logging
|
|
import time
|
|
from typing import Dict, List, Optional
|
|
|
|
import requests
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class OandaAPIError(Exception):
|
|
"""Raised when an Oanda API call fails."""
|
|
|
|
def __init__(self, message: str, status_code: int = 0, body: str = ""):
|
|
super().__init__(message)
|
|
self.status_code = status_code
|
|
self.body = body
|
|
|
|
|
|
class OandaExecutor:
|
|
"""Oanda v20 order execution and trade management."""
|
|
|
|
MAX_RETRIES = 1
|
|
RETRY_DELAY = 2.0
|
|
|
|
def __init__(
|
|
self,
|
|
account_id: str,
|
|
api_token: str,
|
|
base_url: str = "https://api-fxpractice.oanda.com",
|
|
lot_size: int = 1,
|
|
price_precision: int = 2,
|
|
):
|
|
self._account_id = account_id
|
|
self._base_url = base_url.rstrip("/")
|
|
self._lot_size = lot_size
|
|
self._price_precision = price_precision
|
|
self._session = requests.Session()
|
|
self._session.headers.update({
|
|
"Authorization": f"Bearer {api_token}",
|
|
"Accept-Datetime-Format": "RFC3339",
|
|
"Content-Type": "application/json",
|
|
})
|
|
|
|
# ── Order Placement ────────────────────────────────────────────
|
|
|
|
def place_market_order(
|
|
self,
|
|
instrument: str,
|
|
direction: str,
|
|
stop_loss: float,
|
|
take_profit: Optional[float] = None,
|
|
units: Optional[int] = None,
|
|
) -> Dict:
|
|
if units is None:
|
|
units = self._lot_size
|
|
signed_units = str(units) if direction.upper() == "BUY" else str(-units)
|
|
|
|
order_body = {
|
|
"order": {
|
|
"type": "MARKET",
|
|
"instrument": instrument,
|
|
"units": signed_units,
|
|
"timeInForce": "FOK",
|
|
# The book model is one position total; on a netting
|
|
# account an opposite-side order would silently CLOSE an
|
|
# existing (possibly untracked) position instead of opening
|
|
# the signal trade. OPEN_ONLY makes that case fail loudly
|
|
# (order cancelled) so the divergence surfaces instead of
|
|
# executing an unintended close.
|
|
"positionFill": "OPEN_ONLY",
|
|
"stopLossOnFill": {
|
|
"price": self._fmt_price(stop_loss),
|
|
},
|
|
}
|
|
}
|
|
if take_profit is not None:
|
|
order_body["order"]["takeProfitOnFill"] = {
|
|
"price": self._fmt_price(take_profit),
|
|
}
|
|
|
|
url = f"{self._base_url}/v3/accounts/{self._account_id}/orders"
|
|
# Never retry order placement: a timeout after the server already
|
|
# filled would open a SECOND position on retry. Fail loudly instead;
|
|
# the next candle boundary re-evaluates.
|
|
resp = self._request_with_retry("POST", url, json=order_body, retries=0)
|
|
data = self._parse_json(resp)
|
|
|
|
fill_tx = data.get("orderFillTransaction")
|
|
if fill_tx:
|
|
trade_id = fill_tx.get("tradeOpened", {}).get("tradeID", "unknown")
|
|
fill_price = float(fill_tx.get("price", 0))
|
|
logger.info(
|
|
"ORDER FILLED: %s %s %s units @ %.2f — trade %s, SL %.2f%s",
|
|
direction.upper(), instrument, signed_units, fill_price,
|
|
trade_id, stop_loss,
|
|
f", TP {take_profit:.2f}" if take_profit else "")
|
|
else:
|
|
cancel_tx = data.get("orderCancelTransaction", {})
|
|
reason = cancel_tx.get("reason", "unknown")
|
|
logger.warning(
|
|
"ORDER NOT FILLED: %s %s — reason: %s",
|
|
direction.upper(), instrument, reason)
|
|
|
|
return data
|
|
|
|
# ── Trade Queries ──────────────────────────────────────────────
|
|
|
|
def get_open_trades(self, instrument: Optional[str] = None) -> List[Dict]:
|
|
url = f"{self._base_url}/v3/accounts/{self._account_id}/openTrades"
|
|
resp = self._request_with_retry("GET", url)
|
|
trades = self._parse_json(resp).get("trades", [])
|
|
if instrument:
|
|
trades = [t for t in trades if t.get("instrument") == instrument]
|
|
return trades
|
|
|
|
def get_trade(self, trade_id: str) -> Dict:
|
|
url = (f"{self._base_url}/v3/accounts/{self._account_id}"
|
|
f"/trades/{trade_id}")
|
|
resp = self._request_with_retry("GET", url)
|
|
return self._parse_json(resp).get("trade", {})
|
|
|
|
def get_account_summary(self) -> Dict:
|
|
url = f"{self._base_url}/v3/accounts/{self._account_id}/summary"
|
|
resp = self._request_with_retry("GET", url)
|
|
account = self._parse_json(resp).get("account", {})
|
|
logger.info(
|
|
"Account: balance=%.2f, NAV=%.2f, unrealizedPL=%.2f, openTrades=%s",
|
|
float(account.get("balance", 0)),
|
|
float(account.get("NAV", 0)),
|
|
float(account.get("unrealizedPL", 0)),
|
|
account.get("openTradeCount", 0))
|
|
return account
|
|
|
|
# ── Trade Modification ─────────────────────────────────────────
|
|
|
|
def modify_trade_sl(self, trade_id: str, new_sl: float) -> Dict:
|
|
url = (f"{self._base_url}/v3/accounts/{self._account_id}"
|
|
f"/trades/{trade_id}/orders")
|
|
body = {"stopLoss": {"price": self._fmt_price(new_sl)}}
|
|
resp = self._request_with_retry("PUT", url, json=body)
|
|
logger.info(
|
|
"TRAIL UPDATE: trade %s — new SL %.2f", trade_id, new_sl)
|
|
return self._parse_json(resp)
|
|
|
|
def modify_trade_tp(self, trade_id: str, new_tp: float) -> Dict:
|
|
url = (f"{self._base_url}/v3/accounts/{self._account_id}"
|
|
f"/trades/{trade_id}/orders")
|
|
body = {"takeProfit": {"price": self._fmt_price(new_tp)}}
|
|
resp = self._request_with_retry("PUT", url, json=body)
|
|
logger.info("TP UPDATE: trade %s — new TP %.2f", trade_id, new_tp)
|
|
return self._parse_json(resp)
|
|
|
|
def close_trade(self, trade_id: str) -> Dict:
|
|
url = (f"{self._base_url}/v3/accounts/{self._account_id}"
|
|
f"/trades/{trade_id}/close")
|
|
resp = self._request_with_retry("PUT", url, json={"units": "ALL"})
|
|
data = self._parse_json(resp)
|
|
close_tx = data.get("orderFillTransaction")
|
|
if not close_tx:
|
|
# A 200 whose close order was created but NOT filled (e.g.
|
|
# cancelled with MARKET_HALTED during the settlement pause)
|
|
# means the position is STILL OPEN. Raising keeps the caller
|
|
# tracking it and retrying — silently returning here would
|
|
# orphan a live position.
|
|
reason = data.get("orderCancelTransaction", {}).get(
|
|
"reason", "no orderFillTransaction in response")
|
|
raise OandaAPIError(
|
|
f"Close of trade {trade_id} did not fill: {reason}",
|
|
resp.status_code, str(data)[:300])
|
|
close_price = float(close_tx.get("price", 0))
|
|
pl = float(close_tx.get("pl", 0))
|
|
logger.info(
|
|
"TRADE CLOSED: trade %s @ %.2f — PL %.2f",
|
|
trade_id, close_price, pl)
|
|
return data
|
|
|
|
# ── Internals ──────────────────────────────────────────────────
|
|
|
|
@staticmethod
|
|
def _parse_json(resp: requests.Response) -> Dict:
|
|
try:
|
|
return resp.json()
|
|
except ValueError as e:
|
|
raise OandaAPIError(
|
|
f"Oanda returned a non-JSON response (HTTP {resp.status_code})",
|
|
resp.status_code, resp.text[:300]) from e
|
|
|
|
def _fmt_price(self, price: float) -> str:
|
|
# Oanda rejects prices with more decimals than the instrument's
|
|
# displayPrecision (XAU_USD: sub-cent precision is invalid).
|
|
return f"{price:.{self._price_precision}f}"
|
|
|
|
def _request_with_retry(
|
|
self, method: str, url: str, retries: Optional[int] = None, **kwargs
|
|
) -> requests.Response:
|
|
if retries is None:
|
|
retries = self.MAX_RETRIES
|
|
last_err = None
|
|
for attempt in range(1 + retries):
|
|
try:
|
|
resp = self._session.request(method, url, timeout=15, **kwargs)
|
|
if resp.status_code >= 500:
|
|
raise OandaAPIError(
|
|
f"Oanda server error {resp.status_code}",
|
|
resp.status_code, resp.text)
|
|
if resp.status_code >= 400:
|
|
raise OandaAPIError(
|
|
f"Oanda API error {resp.status_code}: {resp.text}",
|
|
resp.status_code, resp.text)
|
|
return resp
|
|
except (requests.ConnectionError, requests.Timeout,
|
|
OandaAPIError) as e:
|
|
last_err = e
|
|
if isinstance(e, OandaAPIError) and 400 <= e.status_code < 500:
|
|
raise
|
|
if attempt < retries:
|
|
logger.warning(
|
|
"Oanda request failed (attempt %d/%d): %s — retrying in %.0fs",
|
|
attempt + 1, 1 + retries, e,
|
|
self.RETRY_DELAY)
|
|
time.sleep(self.RETRY_DELAY)
|
|
raise OandaAPIError(f"Oanda request failed after retries: {last_err}")
|