Spaces:
No application file
No application file
Upload 11 files
Browse filesFiles changed (11)
- __init__.pyAdded
- config.pyAdded+29
- deriv_client.pyAdded+119
- main.pyAdded+251
- paper_trader.pyAdded+79
- prediction_engine.pyAdded+70
- qwen_reasoner.pyAdded+132
- risk.pyAdded+35
- schemas.pyAdded+104
- strategy_ob_fvg.pyAdded+245
- supabase_client.pyAdded+46
1234567891011121314151617181920212223242526272829import os
from functools import lru_cache
from dotenv import load_dotenv
load_dotenv()
class Settings:
HF_TOKEN: str = os.getenv("HF_TOKEN", "")
QWEN_MODEL: str = os.getenv("QWEN_MODEL", "Qwen/Qwen2.5-7B-Instruct")
SUPABASE_URL: str = os.getenv("SUPABASE_URL", "")
SUPABASE_SERVICE_ROLE_KEY: str = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
DERIV_APP_ID: str = os.getenv("DERIV_APP_ID", "1089")
DERIV_API_TOKEN: str = os.getenv("DERIV_API_TOKEN", "")
DERIV_WS_URL: str = "wss://ws.derivws.com/websockets/v3"
ENCRYPTION_KEY: str = os.getenv("ENCRYPTION_KEY", "")
CORS_ORIGINS: list[str] = [o.strip() for o in os.getenv("CORS_ORIGINS", "*").split(",")]
DEMO_STARTING_BALANCE: float = 10_000.0
MAX_DAILY_LOSS_DEFAULT: float = 500.0
MAX_OPEN_TRADES_DEFAULT: int = 5
@lru_cache
def get_settings() -> Settings:
return Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""
Minimal async Deriv WebSocket client.
Supports the read-only operations needed by the strategy engine plus
contract buy for live mode. Token is only attached when the operation
requires it (balance, buy, portfolio).
Docs: https://api.deriv.com/api-explorer/
"""
from __future__ import annotations
import asyncio
import json
import uuid
from contextlib import asynccontextmanager
from typing import Any, Optional
import websockets
from .config import get_settings
from .schemas import Candle
class DerivError(RuntimeError):
pass
class DerivClient:
def __init__(self, app_id: Optional[str] = None,
token: Optional[str] = None):
s = get_settings()
self.app_id = app_id or s.DERIV_APP_ID
self.token = token # may be None for public ops
self.url = f"{s.DERIV_WS_URL}?app_id={self.app_id}"
@asynccontextmanager
async def _connect(self):
async with websockets.connect(self.url, max_size=2**22) as ws:
if self.token:
await self._call(ws, {"authorize": self.token})
yield ws
async def _call(self, ws, payload: dict[str, Any]) -> dict[str, Any]:
req_id = payload.get("req_id") or str(uuid.uuid4())
payload = {**payload, "req_id": req_id}
await ws.send(json.dumps(payload))
while True:
msg = json.loads(await ws.recv())
if msg.get("req_id") == req_id or msg.get("echo_req", {}).get("req_id") == req_id:
if "error" in msg:
raise DerivError(msg["error"].get("message", "Deriv error"))
return msg
# ---------- public ----------
async def candles(self, symbol: str, granularity: int = 60,
count: int = 200) -> list[Candle]:
async with self._connect() as ws:
resp = await self._call(ws, {
"ticks_history": symbol,
"adjust_start_time": 1,
"count": count,
"end": "latest",
"granularity": granularity,
"style": "candles",
})
rows = resp.get("candles", [])
return [Candle(epoch=r["epoch"], open=float(r["open"]),
high=float(r["high"]), low=float(r["low"]),
close=float(r["close"]), volume=float(r.get("volume", 0)))
for r in rows]
async def tick(self, symbol: str) -> dict[str, Any]:
async with self._connect() as ws:
resp = await self._call(ws, {"ticks": symbol})
return resp.get("tick", {})
async def active_symbols(self) -> list[dict[str, Any]]:
async with self._connect() as ws:
resp = await self._call(ws, {
"active_symbols": "brief", "product_type": "basic"})
return resp.get("active_symbols", [])
# ---------- authenticated ----------
async def balance(self) -> dict[str, Any]:
if not self.token:
raise DerivError("Token required for balance()")
async with self._connect() as ws:
resp = await self._call(ws, {"balance": 1})
return resp.get("balance", {})
async def buy_contract(self, *, symbol: str, contract_type: str,
amount: float, duration: int = 5,
duration_unit: str = "m",
currency: str = "USD") -> dict[str, Any]:
"""
contract_type: 'CALL' (BUY) or 'PUT' (SELL) for rise/fall contracts.
"""
if not self.token:
raise DerivError("Token required for buy_contract()")
proposal = {
"proposal": 1, "amount": amount, "basis": "stake",
"contract_type": contract_type, "currency": currency,
"duration": duration, "duration_unit": duration_unit,
"symbol": symbol,
}
async with self._connect() as ws:
p = await self._call(ws, proposal)
prop = p.get("proposal", {})
if "id" not in prop:
raise DerivError("No proposal id returned")
b = await self._call(ws, {"buy": prop["id"], "price": amount})
return b.get("buy", {})
async def portfolio(self) -> dict[str, Any]:
if not self.token:
raise DerivError("Token required for portfolio()")
async with self._connect() as ws:
resp = await self._call(ws, {"portfolio": 1})
return resp.get("portfolio", {})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251"""
AI Trading Backend — FastAPI entry point.
Endpoints:
GET /health
GET /models
GET /portfolio?mode=demo
GET /history?mode=demo&limit=50
GET /performance?mode=demo
GET /confidence?symbol=R_10
POST /predict
POST /reason
POST /paper-trade
POST /trade (live, requires DERIV_API_TOKEN)
POST /feedback
POST /retrain-request
"""
from __future__ import annotations
import logging
from typing import Optional
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from . import supabase_client as sb
from .config import get_settings
from .deriv_client import DerivClient, DerivError
from .paper_trader import (open_paper_trade, close_paper_trade,
get_or_create_portfolio)
from .prediction_engine import ensemble, heuristic_forecast
from .qwen_reasoner import reason as qwen_reason
from .risk import validate_trade
from .schemas import (PredictRequest, ReasonRequest, PaperTradeRequest,
TradeRequest, TradeResponse, FeedbackRequest,
RetrainRequest, StrategySignal)
from .strategy_ob_fvg import generate_signal
log = logging.getLogger("uvicorn.error")
settings = get_settings()
app = FastAPI(title="AI Trading Backend", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# -------------------------- system ------------------------------------------
@app.get("/health")
async def health():
return {
"ok": True,
"qwen_configured": bool(settings.HF_TOKEN),
"supabase_configured": bool(sb.sb()),
"deriv_live_enabled": bool(settings.DERIV_API_TOKEN),
"model": settings.QWEN_MODEL,
}
@app.get("/models")
async def models():
return {
"reasoner": settings.QWEN_MODEL,
"forecasters": ["heuristic-momentum-v1", "lstm-stub", "xgboost-stub",
"ensemble-v1"],
"strategies": ["ob_fvg"],
}
# -------------------------- portfolio / history ------------------------------
@app.get("/portfolio")
async def portfolio(mode: str = "demo"):
return await get_or_create_portfolio(None, mode)
@app.get("/history")
async def history(mode: str = "demo", limit: int = 50):
return sb.select("trade_history", eq={"mode": mode},
order="opened_at", desc=True, limit=limit)
@app.get("/performance")
async def performance(mode: str = "demo"):
trades = sb.select("trade_history", eq={"mode": mode, "status": "closed"},
order="closed_at", desc=True, limit=500)
if not trades:
return {"total_trades": 0, "win_rate": 0, "total_pnl": 0,
"profit_factor": 0}
wins = [t for t in trades if (t.get("pnl") or 0) > 0]
losses = [t for t in trades if (t.get("pnl") or 0) < 0]
gross_win = sum(t["pnl"] for t in wins) or 0.0
gross_loss = abs(sum(t["pnl"] for t in losses)) or 1e-9
return {
"total_trades": len(trades),
"winning_trades": len(wins),
"losing_trades": len(losses),
"win_rate": len(wins) / len(trades),
"total_pnl": sum(t["pnl"] or 0 for t in trades),
"profit_factor": gross_win / gross_loss,
}
@app.get("/confidence")
async def confidence(symbol: str = "R_10"):
rows = sb.select("predictions", eq={"symbol": symbol},
order="created_at", desc=True, limit=20)
if not rows:
return {"symbol": symbol, "avg_confidence": 0, "samples": 0}
avg = sum(float(r.get("confidence") or 0) for r in rows) / len(rows)
return {"symbol": symbol, "avg_confidence": avg, "samples": len(rows)}
# -------------------------- core AI loop ------------------------------------
@app.post("/predict", response_model=StrategySignal)
async def predict(req: PredictRequest):
"""Run OB+FVG strategy on latest Deriv candles and emit a signal."""
granularity = _granularity_seconds(req.timeframe)
client = DerivClient()
try:
candles = await client.candles(req.symbol, granularity=granularity,
count=req.lookback)
except DerivError as e:
raise HTTPException(502, f"Deriv error: {e}")
signal = generate_signal(req.symbol, req.timeframe, candles)
forecast = ensemble(candles)
# persist
pred = sb.insert("predictions", {
"symbol": req.symbol,
"timeframe": req.timeframe,
"decision": signal.decision,
"confidence": round(signal.confidence, 3),
"risk_score": round(1 - signal.confidence, 3),
"success_probability": round(signal.confidence, 3),
"reasoning": signal.rationale,
"trade_plan": {"entry": signal.entry, "sl": signal.sl, "tp": signal.tp},
"indicators": signal.indicators,
"market_state": {"forecast": forecast},
"suggested_entry": signal.entry,
"suggested_sl": signal.sl,
"suggested_tp": signal.tp,
"model_version": "ob_fvg-v1",
})
sb.insert("live_signals", {
"symbol": req.symbol,
"decision": signal.decision,
"confidence": round(signal.confidence, 3),
"price": signal.price,
"ob_zone": signal.ob.model_dump() if signal.ob else None,
"fvg_zone": signal.fvg.model_dump() if signal.fvg else None,
"reasoning": signal.rationale,
})
return signal
@app.post("/reason")
async def reason_endpoint(req: ReasonRequest):
return await qwen_reason(req.symbol, req.timeframe,
req.indicators, req.prediction, req.market_state)
# -------------------------- trading ------------------------------------------
@app.post("/paper-trade", response_model=TradeResponse)
async def paper_trade(req: PaperTradeRequest):
client = DerivClient()
tick = await client.tick(req.symbol)
price = float(tick.get("quote") or 0)
if not price:
raise HTTPException(502, "Could not fetch current price")
pf = await get_or_create_portfolio(None, "demo")
check = validate_trade(
balance=float(pf.get("balance") or 0),
open_positions=int(pf.get("open_positions") or 0),
today_pnl=float(pf.get("realized_pnl") or 0),
trade_size=req.size,
confidence=0.7, # passed when called from /predict; user override OK
max_daily_loss=settings.MAX_DAILY_LOSS_DEFAULT,
max_open_trades=settings.MAX_OPEN_TRADES_DEFAULT,
risk_percent=2.0,
)
if not check.ok:
return TradeResponse(ok=False, message=check.reason or "Rejected")
row = await open_paper_trade(req, current_price=price)
return TradeResponse(ok=True, trade_id=row.get("id"),
message="Paper trade opened")
@app.post("/trade", response_model=TradeResponse)
async def live_trade(req: TradeRequest):
if not settings.DERIV_API_TOKEN:
raise HTTPException(403,
"Live trading disabled: set DERIV_API_TOKEN in Space secrets.")
client = DerivClient(token=settings.DERIV_API_TOKEN)
contract_type = "CALL" if req.side == "BUY" else "PUT"
try:
buy = await client.buy_contract(
symbol=req.symbol, contract_type=contract_type,
amount=req.size, duration=5, duration_unit="m",
)
except DerivError as e:
raise HTTPException(502, f"Deriv: {e}")
row = sb.insert("trade_history", {
"mode": "live",
"symbol": req.symbol,
"side": req.side,
"entry_price": float(buy.get("buy_price") or 0),
"size": req.size,
"stop_loss": req.sl,
"take_profit": req.tp,
"status": "open",
"deriv_contract_id": str(buy.get("contract_id") or ""),
"prediction_id": req.prediction_id,
})
return TradeResponse(ok=True, trade_id=(row or {}).get("id"),
contract_id=str(buy.get("contract_id") or ""),
message="Live contract bought")
# -------------------------- feedback / retrain -------------------------------
@app.post("/feedback")
async def feedback(req: FeedbackRequest):
sb.insert("feedback", req.model_dump())
return {"ok": True}
@app.post("/retrain-request")
async def retrain(req: RetrainRequest):
sb.insert("logs", {
"level": "info", "source": "retrain",
"message": f"Retrain requested for {req.model_name}",
"meta": req.model_dump(),
})
return {"ok": True, "queued": True}
# -------------------------- helpers ------------------------------------------
def _granularity_seconds(tf: str) -> int:
table = {"1m": 60, "5m": 300, "15m": 900, "30m": 1800,
"1h": 3600, "4h": 14400, "1d": 86400}
return table.get(tf, 60)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Virtual paper-trading engine. Uses live Deriv prices but never executes."""
from __future__ import annotations
from typing import Any, Optional
from datetime import datetime, timezone
import uuid
from . import supabase_client as sb
from .config import get_settings
from .schemas import PaperTradeRequest
async def get_or_create_portfolio(user_id: Optional[str], mode: str = "demo") -> dict:
rows = sb.select("portfolio", eq={"mode": mode, "user_id": user_id} if user_id
else {"mode": mode}, limit=1)
if rows:
return rows[0]
s = get_settings()
created = sb.insert("portfolio", {
"user_id": user_id, "mode": mode,
"balance": s.DEMO_STARTING_BALANCE,
"equity": s.DEMO_STARTING_BALANCE,
})
return created or {
"balance": s.DEMO_STARTING_BALANCE,
"equity": s.DEMO_STARTING_BALANCE,
"open_positions": 0, "realized_pnl": 0, "unrealized_pnl": 0,
}
async def open_paper_trade(req: PaperTradeRequest, current_price: float,
user_id: Optional[str] = None) -> dict[str, Any]:
portfolio = await get_or_create_portfolio(user_id, "demo")
entry = req.entry or current_price
row = sb.insert("trade_history", {
"id": str(uuid.uuid4()),
"user_id": user_id,
"prediction_id": req.prediction_id,
"mode": "demo",
"symbol": req.symbol,
"side": req.side,
"entry_price": entry,
"size": req.size,
"stop_loss": req.sl,
"take_profit": req.tp,
"status": "open",
"reason_opened": "AI signal accepted",
"opened_at": datetime.now(timezone.utc).isoformat(),
})
if portfolio.get("id"):
sb.update("portfolio", portfolio["id"], {
"open_positions": (portfolio.get("open_positions") or 0) + 1,
})
return row or {}
async def close_paper_trade(trade_id: str, exit_price: float,
reason: str = "manual close") -> dict[str, Any]:
rows = sb.select("trade_history", eq={"id": trade_id}, limit=1)
if not rows:
return {"ok": False, "message": "Trade not found"}
t = rows[0]
sign = 1 if t["side"] == "BUY" else -1
pnl = sign * (exit_price - float(t["entry_price"])) * float(t["size"])
sb.update("trade_history", trade_id, {
"exit_price": exit_price,
"pnl": pnl,
"status": "closed",
"reason_closed": reason,
"closed_at": datetime.now(timezone.utc).isoformat(),
})
pf = await get_or_create_portfolio(t.get("user_id"), "demo")
if pf.get("id"):
sb.update("portfolio", pf["id"], {
"realized_pnl": float(pf.get("realized_pnl") or 0) + pnl,
"balance": float(pf.get("balance") or 0) + pnl,
"equity": float(pf.get("equity") or 0) + pnl,
"open_positions": max(0, (pf.get("open_positions") or 1) - 1),
})
return {"ok": True, "pnl": pnl}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""
Prediction engine — numerical forecasters.
For the initial slice we ship one pure-Python heuristic forecaster + stubs
for LSTM / XGBoost / Transformer slots. Heavy models load lazily so the
Space starts fast.
"""
from __future__ import annotations
from typing import Any
import numpy as np
import pandas as pd
from .schemas import Candle
def _df(candles: list[Candle]) -> pd.DataFrame:
return pd.DataFrame([c.model_dump() for c in candles])
def heuristic_forecast(candles: list[Candle], horizon: int = 5) -> dict[str, Any]:
"""Quick momentum + mean-reversion blend, returns next-N candle direction."""
if len(candles) < 20:
return {"direction": "flat", "expected_return": 0.0, "confidence": 0.0,
"horizon": horizon, "model": "heuristic"}
df = _df(candles)
rets = df["close"].pct_change().dropna()
momentum = rets.tail(10).mean()
vol = rets.tail(20).std() or 1e-9
z = momentum / vol
expected = float(np.tanh(z) * vol * horizon)
direction = "up" if expected > 0 else "down" if expected < 0 else "flat"
confidence = float(min(abs(z) / 3, 0.9))
return {
"direction": direction,
"expected_return": expected,
"confidence": confidence,
"horizon": horizon,
"model": "heuristic-momentum-v1",
}
# ---- stubs for future swap-in -----
def lstm_forecast(candles: list[Candle], horizon: int = 5) -> dict[str, Any]:
"""Placeholder — same contract as heuristic. Swap in a trained LSTM."""
base = heuristic_forecast(candles, horizon)
base["model"] = "lstm-stub"
return base
def xgboost_forecast(candles: list[Candle], horizon: int = 5) -> dict[str, Any]:
base = heuristic_forecast(candles, horizon)
base["model"] = "xgboost-stub"
return base
def ensemble(candles: list[Candle], horizon: int = 5) -> dict[str, Any]:
"""Average available models. Currently only the heuristic is real."""
models = [heuristic_forecast(candles, horizon)]
expected = float(np.mean([m["expected_return"] for m in models]))
conf = float(np.mean([m["confidence"] for m in models]))
direction = "up" if expected > 0 else "down" if expected < 0 else "flat"
return {
"direction": direction,
"expected_return": expected,
"confidence": conf,
"horizon": horizon,
"components": [m["model"] for m in models],
"model": "ensemble-v1",
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""
Qwen reasoning engine via Hugging Face Inference API (chat completions).
Qwen is NOT a forecaster — it ingests structured market context and emits
a trading decision with rationale.
"""
from __future__ import annotations
import json
import re
from typing import Any
import httpx
from .config import get_settings
from .schemas import ReasonResponse
SYSTEM_PROMPT = """You are the reasoning engine of an autonomous trading system.
You receive structured market context (indicators, prediction model output,
detected Order Blocks / Fair Value Gaps) and must decide BUY, SELL, or WAIT.
Be conservative. WAIT is always a valid output. Never invent prices.
Respond ONLY with a single minified JSON object matching this schema:
{
"decision": "BUY" | "SELL" | "WAIT",
"confidence": <float 0..1>,
"risk_score": <float 0..1>, // 0 = low risk, 1 = high risk
"success_probability": <float 0..1>,
"reasoning": "<concise plain-English rationale, 1-3 sentences>",
"trade_plan": {
"entry": <float>, "sl": <float>, "tp": <float>,
"size_hint": <float 0..1> // fraction of risk budget
}
}
"""
def _build_user_prompt(symbol: str, timeframe: str,
indicators: dict, prediction: dict,
market_state: dict) -> str:
payload = {
"symbol": symbol,
"timeframe": timeframe,
"indicators": indicators,
"prediction_model_output": prediction,
"market_state": market_state,
}
return (
"Market context:\n"
f"{json.dumps(payload, default=str)}\n\n"
"Return the JSON decision now."
)
def _fallback(prediction: dict, indicators: dict) -> ReasonResponse:
"""Deterministic fallback when the LLM call fails or returns garbage."""
direction = prediction.get("direction", "flat")
decision = "BUY" if direction == "up" else "SELL" if direction == "down" else "WAIT"
conf = float(prediction.get("confidence", 0.3))
return ReasonResponse(
decision=decision if conf > 0.4 else "WAIT",
confidence=conf,
risk_score=1.0 - conf,
success_probability=conf,
reasoning=("Qwen unavailable — fell back to deterministic rule using "
f"prediction direction={direction}, conf={conf:.2f}."),
trade_plan={
"entry": indicators.get("price", 0),
"sl": 0, "tp": 0, "size_hint": min(conf, 0.5),
},
)
def _extract_json(text: str) -> dict[str, Any] | None:
# Try direct
try:
return json.loads(text)
except Exception:
pass
# Try first {...} block
m = re.search(r"\{.*\}", text, re.DOTALL)
if m:
try:
return json.loads(m.group(0))
except Exception:
return None
return None
async def reason(symbol: str, timeframe: str,
indicators: dict, prediction: dict,
market_state: dict) -> ReasonResponse:
s = get_settings()
if not s.HF_TOKEN:
return _fallback(prediction, indicators)
url = f"https://api-inference.huggingface.co/models/{s.QWEN_MODEL}/v1/chat/completions"
headers = {"Authorization": f"Bearer {s.HF_TOKEN}",
"Content-Type": "application/json"}
body = {
"model": s.QWEN_MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": _build_user_prompt(
symbol, timeframe, indicators, prediction, market_state)},
],
"temperature": 0.2,
"max_tokens": 400,
"response_format": {"type": "json_object"},
}
try:
async with httpx.AsyncClient(timeout=30) as client:
r = await client.post(url, headers=headers, json=body)
r.raise_for_status()
data = r.json()
content = data["choices"][0]["message"]["content"]
parsed = _extract_json(content)
if not parsed:
return _fallback(prediction, indicators)
return ReasonResponse(
decision=parsed.get("decision", "WAIT"),
confidence=float(parsed.get("confidence", 0.3)),
risk_score=float(parsed.get("risk_score", 0.5)),
success_probability=float(parsed.get("success_probability", 0.5)),
reasoning=str(parsed.get("reasoning", "")),
trade_plan=parsed.get("trade_plan", {}) or {},
)
except Exception as e:
fb = _fallback(prediction, indicators)
fb.reasoning = f"[Qwen error: {type(e).__name__}] " + fb.reasoning
return fb1234567891011121314151617181920212223242526272829303132333435"""Pre-trade risk gates. Reject before any execution."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
@dataclass
class RiskCheckResult:
ok: bool
reason: Optional[str] = None
def validate_trade(*, balance: float, open_positions: int, today_pnl: float,
trade_size: float, confidence: float,
max_daily_loss: float, max_open_trades: int,
risk_percent: float,
confidence_threshold: float = 0.6) -> RiskCheckResult:
if balance <= 0:
return RiskCheckResult(False, "Zero balance.")
if trade_size <= 0:
return RiskCheckResult(False, "Trade size must be positive.")
if trade_size > balance:
return RiskCheckResult(False, "Trade size exceeds balance.")
if open_positions >= max_open_trades:
return RiskCheckResult(False, f"Max open trades reached ({max_open_trades}).")
if today_pnl <= -abs(max_daily_loss):
return RiskCheckResult(False, f"Daily loss limit hit ({today_pnl:.2f}).")
if confidence < confidence_threshold:
return RiskCheckResult(False,
f"Confidence {confidence:.2f} below threshold {confidence_threshold:.2f}.")
max_risk = balance * (risk_percent / 100.0)
if trade_size > max_risk:
return RiskCheckResult(False,
f"Trade size {trade_size:.2f} exceeds {risk_percent}% risk cap ({max_risk:.2f}).")
return RiskCheckResult(True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from __future__ import annotations
from typing import Any, Optional, Literal
from pydantic import BaseModel, Field
Decision = Literal["BUY", "SELL", "WAIT"]
Mode = Literal["demo", "live"]
Side = Literal["BUY", "SELL"]
class Candle(BaseModel):
epoch: int
open: float
high: float
low: float
close: float
volume: float = 0.0
class FVG(BaseModel):
kind: Literal["bullish", "bearish"]
top: float
bottom: float
index: int # index of middle candle in series
filled: bool = False
class OrderBlock(BaseModel):
kind: Literal["bullish", "bearish"]
top: float
bottom: float
index: int # index of OB candle
fvg_index: int # the FVG this OB anchors
mitigated: bool = False
class StrategySignal(BaseModel):
symbol: str
timeframe: str
decision: Decision
confidence: float = Field(ge=0, le=1)
price: float
entry: Optional[float] = None
sl: Optional[float] = None
tp: Optional[float] = None
ob: Optional[OrderBlock] = None
fvg: Optional[FVG] = None
rationale: str
indicators: dict[str, Any] = {}
class PredictRequest(BaseModel):
symbol: str = "R_10"
timeframe: str = "1m"
lookback: int = 200
class ReasonRequest(BaseModel):
symbol: str
timeframe: str = "1m"
indicators: dict[str, Any]
prediction: dict[str, Any]
market_state: dict[str, Any] = {}
class ReasonResponse(BaseModel):
decision: Decision
confidence: float
risk_score: float
success_probability: float
reasoning: str
trade_plan: dict[str, Any]
class PaperTradeRequest(BaseModel):
symbol: str
side: Side
size: float
entry: Optional[float] = None
sl: Optional[float] = None
tp: Optional[float] = None
prediction_id: Optional[str] = None
class TradeRequest(PaperTradeRequest):
pass
class TradeResponse(BaseModel):
ok: bool
trade_id: Optional[str] = None
contract_id: Optional[str] = None
message: str
pnl: Optional[float] = None
class FeedbackRequest(BaseModel):
prediction_id: str
rating: int = Field(ge=1, le=5)
comment: Optional[str] = None
class RetrainRequest(BaseModel):
model_name: str
reason: Optional[str] = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245"""
Order Block + Fair Value Gap strategy.
Definitions
-----------
Fair Value Gap (3-candle imbalance):
- Bullish FVG: candle[i-1].high < candle[i+1].low
=> gap zone = (candle[i-1].high, candle[i+1].low)
- Bearish FVG: candle[i-1].low > candle[i+1].high
=> gap zone = (candle[i+1].high, candle[i-1].low)
Order Block (anchor candle):
- Bullish OB = last bearish candle (close < open) immediately preceding
the bullish impulse that created the FVG.
- Bearish OB = last bullish candle (close > open) immediately preceding
the bearish impulse.
- OB zone = (low, high) of that candle.
Signal logic
------------
When current price retraces into an unmitigated OB zone of the same direction
and the FVG anchoring it is still (at least partially) unfilled, emit a signal:
Bullish OB tag -> BUY
Bearish OB tag -> SELL
Risk plan
---------
entry = midpoint of OB zone
SL = OB extreme on the protected side - 1 * ATR(14) buffer
TP = nearest swing liquidity in trade direction, capped at 3R / floored at 1.5R
"""
from __future__ import annotations
from dataclasses import dataclass, asdict
from typing import Optional
import numpy as np
import pandas as pd
from .schemas import Candle, FVG, OrderBlock, StrategySignal
# ----------------------------- helpers --------------------------------------
def candles_to_df(candles: list[Candle]) -> pd.DataFrame:
return pd.DataFrame([c.model_dump() for c in candles])
def atr(df: pd.DataFrame, period: int = 14) -> float:
if len(df) < period + 1:
return float((df["high"] - df["low"]).mean() or 0.0)
h, l, c = df["high"].values, df["low"].values, df["close"].values
tr = np.maximum.reduce([
h[1:] - l[1:],
np.abs(h[1:] - c[:-1]),
np.abs(l[1:] - c[:-1]),
])
return float(pd.Series(tr).rolling(period).mean().iloc[-1])
def ema(series: pd.Series, period: int) -> float:
return float(series.ewm(span=period, adjust=False).mean().iloc[-1])
def rsi(series: pd.Series, period: int = 14) -> float:
delta = series.diff()
up = delta.clip(lower=0).rolling(period).mean()
down = (-delta.clip(upper=0)).rolling(period).mean()
rs = up / down.replace(0, np.nan)
val = 100 - (100 / (1 + rs.iloc[-1]))
return float(val) if not np.isnan(val) else 50.0
def swing_high(df: pd.DataFrame, lookback: int = 50) -> float:
return float(df["high"].tail(lookback).max())
def swing_low(df: pd.DataFrame, lookback: int = 50) -> float:
return float(df["low"].tail(lookback).min())
# ----------------------------- detectors ------------------------------------
def detect_fvgs(df: pd.DataFrame, max_age: int = 100) -> list[FVG]:
fvgs: list[FVG] = []
n = len(df)
start = max(1, n - max_age - 1)
end = n - 1 # need i+1 to exist
h = df["high"].values
l = df["low"].values
for i in range(start, end):
# bullish: gap between prev high and next low
if h[i - 1] < l[i + 1]:
fvgs.append(FVG(kind="bullish", bottom=float(h[i - 1]),
top=float(l[i + 1]), index=i))
# bearish: gap between next high and prev low
elif l[i - 1] > h[i + 1]:
fvgs.append(FVG(kind="bearish", bottom=float(h[i + 1]),
top=float(l[i - 1]), index=i))
# mark filled if price has since traded through
last_close = float(df["close"].iloc[-1])
last_high = float(df["high"].max())
last_low = float(df["low"].min())
for f in fvgs:
post = df.iloc[f.index + 1:]
if f.kind == "bullish":
f.filled = bool((post["low"] <= f.bottom).any())
else:
f.filled = bool((post["high"] >= f.top).any())
return fvgs
def detect_order_blocks(df: pd.DataFrame, fvgs: list[FVG]) -> list[OrderBlock]:
obs: list[OrderBlock] = []
o = df["open"].values
c = df["close"].values
h = df["high"].values
l = df["low"].values
for f in fvgs:
# search backwards from FVG anchor for last opposite-color candle
ob_kind = "bullish" if f.kind == "bullish" else "bearish"
# bullish OB = last bearish (red) candle before bullish impulse
# bearish OB = last bullish (green) candle before bearish impulse
want_red = (ob_kind == "bullish")
idx = None
for j in range(f.index - 1, max(f.index - 10, -1), -1):
is_red = c[j] < o[j]
if want_red and is_red:
idx = j
break
if (not want_red) and (c[j] > o[j]):
idx = j
break
if idx is None:
continue
ob = OrderBlock(
kind=ob_kind,
top=float(h[idx]),
bottom=float(l[idx]),
index=idx,
fvg_index=f.index,
)
# mitigated if price has revisited the zone after creation
post = df.iloc[idx + 1:]
if ob.kind == "bullish":
ob.mitigated = bool((post["low"] <= ob.top).any() and
(post["low"] <= ob.bottom).any())
else:
ob.mitigated = bool((post["high"] >= ob.bottom).any() and
(post["high"] >= ob.top).any())
obs.append(ob)
return obs
# ----------------------------- signal generator -----------------------------
def generate_signal(symbol: str, timeframe: str,
candles: list[Candle]) -> StrategySignal:
if len(candles) < 30:
return StrategySignal(
symbol=symbol, timeframe=timeframe, decision="WAIT",
confidence=0.0, price=candles[-1].close if candles else 0.0,
rationale="Insufficient candle history (need >= 30).",
)
df = candles_to_df(candles)
price = float(df["close"].iloc[-1])
a = atr(df)
rsi_v = rsi(df["close"])
ema20 = ema(df["close"], 20)
ema50 = ema(df["close"], 50)
trend = "up" if ema20 > ema50 else "down"
fvgs = detect_fvgs(df)
obs = detect_order_blocks(df, fvgs)
# find the most recent valid (unmitigated) OB whose FVG is unfilled
candidate: Optional[OrderBlock] = None
paired_fvg: Optional[FVG] = None
for ob in reversed(obs):
f = next((x for x in fvgs if x.index == ob.fvg_index), None)
if not f or f.filled or ob.mitigated:
continue
# require current price near OB (within 2 ATR)
dist = min(abs(price - ob.top), abs(price - ob.bottom))
if dist > 2 * a and not (ob.bottom <= price <= ob.top):
continue
candidate, paired_fvg = ob, f
break
indicators = {
"ema20": ema20, "ema50": ema50, "rsi14": rsi_v,
"atr14": a, "trend": trend,
"swing_high": swing_high(df), "swing_low": swing_low(df),
"fvg_count": len(fvgs), "ob_count": len(obs),
}
if not candidate or not paired_fvg:
return StrategySignal(
symbol=symbol, timeframe=timeframe, decision="WAIT",
confidence=0.25, price=price,
rationale="No unmitigated OB / unfilled FVG confluence near price.",
indicators=indicators,
)
# build trade plan
if candidate.kind == "bullish":
entry = (candidate.top + candidate.bottom) / 2
sl = candidate.bottom - a
tp_liquidity = indicators["swing_high"]
r = entry - sl
tp = max(min(tp_liquidity, entry + 3 * r), entry + 1.5 * r)
decision = "BUY"
else:
entry = (candidate.top + candidate.bottom) / 2
sl = candidate.top + a
tp_liquidity = indicators["swing_low"]
r = sl - entry
tp = min(max(tp_liquidity, entry - 3 * r), entry - 1.5 * r)
decision = "SELL"
# confidence model: trend alignment + RSI sanity + freshness
trend_align = (decision == "BUY" and trend == "up") or \
(decision == "SELL" and trend == "down")
rsi_ok = (decision == "BUY" and rsi_v < 65) or \
(decision == "SELL" and rsi_v > 35)
freshness = max(0.0, 1.0 - (len(df) - 1 - candidate.index) / 50)
confidence = float(np.clip(
0.40 + 0.20 * trend_align + 0.15 * rsi_ok + 0.25 * freshness, 0, 0.95
))
rationale = (
f"{candidate.kind.title()} OB at [{candidate.bottom:.5f}, "
f"{candidate.top:.5f}] anchors an unfilled {paired_fvg.kind} FVG. "
f"Price {price:.5f} is reacting to the zone. Trend {trend.upper()} "
f"(EMA20 {ema20:.5f} vs EMA50 {ema50:.5f}), RSI14 {rsi_v:.1f}, "
f"ATR14 {a:.5f}. Plan: entry {entry:.5f}, SL {sl:.5f}, TP {tp:.5f}."
)
return StrategySignal(
symbol=symbol, timeframe=timeframe, decision=decision,
confidence=confidence, price=price,
entry=entry, sl=sl, tp=tp,
ob=candidate, fvg=paired_fvg, rationale=rationale,
indicators=indicators,
)12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Thin Supabase wrapper used by the backend."""
from __future__ import annotations
from functools import lru_cache
from typing import Any, Optional
from supabase import create_client, Client
from .config import get_settings
@lru_cache
def sb() -> Optional[Client]:
s = get_settings()
if not s.SUPABASE_URL or not s.SUPABASE_SERVICE_ROLE_KEY:
return None
return create_client(s.SUPABASE_URL, s.SUPABASE_SERVICE_ROLE_KEY)
def insert(table: str, row: dict[str, Any]) -> Optional[dict]:
c = sb()
if not c:
return None
res = c.table(table).insert(row).execute()
return (res.data or [None])[0]
def update(table: str, row_id: str, patch: dict[str, Any]) -> Optional[dict]:
c = sb()
if not c:
return None
res = c.table(table).update(patch).eq("id", row_id).execute()
return (res.data or [None])[0]
def select(table: str, *, eq: Optional[dict] = None,
order: Optional[str] = None, desc: bool = True,
limit: int = 100) -> list[dict]:
c = sb()
if not c:
return []
q = c.table(table).select("*")
for k, v in (eq or {}).items():
q = q.eq(k, v)
if order:
q = q.order(order, desc=desc)
res = q.limit(limit).execute()
return res.data or []__init__.pyAdded
config.pyAdded+29
deriv_client.pyAdded+119
main.pyAdded+251
paper_trader.pyAdded+79
prediction_engine.pyAdded+70
qwen_reasoner.pyAdded+132
risk.pyAdded+35
schemas.pyAdded+104
strategy_ob_fvg.pyAdded+245
supabase_client.pyAdded+46