Oanda demo daemon: auto-execution on practice account (XAU/USD)
New independent trading daemon (oanda_daemon.py) that places orders on an Oanda v20 practice account instead of sending Telegram alerts. Oanda-only market data (oanda_provider.py, mid candles + real bid/ask spread) through the unchanged signal pipeline; order execution and trade management via oanda_executor.py (raw requests, no new deps). Book parity with the backtester: no broker-side TP (exits = SL/TRAIL/ TIMEOUT only), bar-close-only trail ratchet with each closed bar processed exactly once, 5-bar per-TF entry cooldown, structural SL from the setup. Accepted divergence: one position total (skipped signals logged for book reconciliation). Safety/ops: fail-fast boot on rejected credentials (transient outages continue), market orders never retried (double-fill risk), entry lock against aligned-boundary races, restart recovery + adoption via oanda_state.json, hourly heartbeat, asyncio exception handler, every failure path logged. Prices formatted at instrument precision. Config: env OANDA_* -> config.json "oanda" section (validated in app_config). Tests: Module 15 (30 tests), suite 240 green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VUnCqjWBuvKRSjLwHeB9BJ
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
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",
|
||||
"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", {})
|
||||
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}")
|
||||
Reference in New Issue
Block a user