Sleepyfx's picture
download
raw
12.4 kB
"""api/models.py — SleepyFX Elite.
All Pydantic v2 request and response models for the FastAPI layer.
Engine dataclasses (engine/*.py) are converted to these models in
api/main.py before returning to the frontend.
Engine result dataclasses map 1-to-1 with the corresponding
Pydantic model — field names are identical so vars(engine_result)
can be unpacked directly after stripping the 'error' key.
Example input (to route handler):
GET /api/analysis?ticker=EURUSD
Example output (AnalysisResponse JSON snippet):
{
"cycles": { "daily": { "phase": "Q3 Distribution", "bias": "bear", ... }, ... },
"smt": { "signals": [{ "cycle": "daily", "type": "normal", ... }] },
"decision": { "state": "TRADE", "reason": "SMT + bias aligned", ... },
"lastUpdated": 1700000000000
}
"""
from __future__ import annotations
from typing import Any, Optional
from pydantic import BaseModel, ConfigDict, Field
# ─────────────────────────────────────────────────────────────────────────────
# SYSTEM
# ─────────────────────────────────────────────────────────────────────────────
class HealthResponse(BaseModel):
"""GET /api/health response."""
status: str # always 'ok'
timestamp: int # Unix ms
# ─────────────────────────────────────────────────────────────────────────────
# MARKET DATA
# ─────────────────────────────────────────────────────────────────────────────
class OHLCBar(BaseModel):
"""Single OHLC bar as returned by the API (Pydantic, for JSON transport)."""
timestamp: float # Unix ms
open: float
high: float
low: float
close: float
volume: float = 0.0
class OHLCData(BaseModel):
"""HTF OHLC snapshot for a single timeframe (used inside PricesResponse)."""
open: float
high: float
low: float
close: float
class PricesResponse(BaseModel):
"""GET /api/prices response."""
ticker: str
price: float
bid: float
ask: float
change: float # absolute price change
changePercent: float # percentage change
volume: float
vwap: float
zScore: float # rolling z-score vs 20-period SMA
ohlc: OHLCData # current-day OHLC
htf: dict[str, OHLCData] = {} # {'1H': OHLCData, '4H': ..., 'D': ..., 'W': ...}
class OHLCResponse(BaseModel):
"""GET /api/ohlc response."""
ticker: str
timeframe: str
bars: list[OHLCBar] # newest LAST
class DXYResponse(BaseModel):
"""GET /api/dxy response."""
price: float
change: float # percentage change
bias: str # 'bull'|'bear'|'neutral'
class NewsEvent(BaseModel):
"""Single economic calendar event."""
time: str # ISO8601 datetime string NY time
currency: str # 'USD'|'EUR'|'GBP' etc.
impact: str # 'high'|'medium'|'low'
title: str
forecast: Optional[str] = None
prev: Optional[str] = None
actual: Optional[str] = None
class NewsResponse(BaseModel):
"""GET /api/news response."""
upcoming: list[NewsEvent] = []
recent: list[NewsEvent] = []
class CurrencyResponse(BaseModel):
"""GET /api/currency response."""
base: str
rates: dict[str, float] # { 'EUR': 0.92, 'GBP': 0.79, ... }
# ─────────────────────────────────────────────────────────────────────────────
# ANALYSIS — mirrors SFX.state.analysis exactly
# ─────────────────────────────────────────────────────────────────────────────
class CycleLevel(BaseModel):
"""OHLC + phase/bias for a single cycle timeframe."""
phase: Optional[str] = None # 'Q1 Accumulation'|'Q2 Manipulation'|'Q3 Distribution'|'Q4 Expansion'
bias: Optional[str] = None # 'bull'|'bear'|'inside_range'
open: Optional[float] = None
high: Optional[float] = None
low: Optional[float] = None
close: Optional[float] = None
class CyclesResult(BaseModel):
"""engine/cycle.py output → analysis.cycles."""
yearly: CycleLevel = Field(default_factory=CycleLevel)
quarterly: CycleLevel = Field(default_factory=CycleLevel)
monthly: CycleLevel = Field(default_factory=CycleLevel)
weekly: CycleLevel = Field(default_factory=CycleLevel)
daily: CycleLevel = Field(default_factory=CycleLevel)
ninety: CycleLevel = Field(default_factory=CycleLevel)
micro: CycleLevel = Field(default_factory=CycleLevel)
class SMTSignal(BaseModel):
"""Single active SMT divergence signal."""
cycle: str # cycle timeframe label
type: str # 'normal'|'hidden'
direction: str # 'bull'|'bear'
pair: str # correlated asset ticker
priceLevel: float
active: bool
class SMTResult(BaseModel):
"""engine/smt.py output → analysis.smt."""
signals: list[SMTSignal] = []
class QCISDLevel(BaseModel):
"""Single QCISD price level."""
level: float
direction: str # 'bull'|'bear'
isConfirmed: bool
cycle: str
isHp: bool = False # is high-probability level
class QCISDResult(BaseModel):
"""engine/qcisd.py output → analysis.qcisd."""
levels: list[QCISDLevel] = []
class GapLevel(BaseModel):
"""Opening gap box (NWOG or NDOG)."""
high: Optional[float] = None
low: Optional[float] = None
tapped: bool = False
mode: str = 'auto' # 'auto'|'manual'
class NDOGLevel(BaseModel):
"""New Day Opening Gap — no mode field."""
high: Optional[float] = None
low: Optional[float] = None
tapped: bool = False
class TrueOpenResult(BaseModel):
"""engine/nwog.py output → analysis.trueOpen."""
nwog: GapLevel = Field(default_factory=GapLevel)
ndog: NDOGLevel = Field(default_factory=NDOGLevel)
class LiquidityLevel(BaseModel):
"""Single HTF liquidity sweep level."""
price: float
timeframe: str
swept: bool
active: bool
class LiquidityResult(BaseModel):
"""engine/sweep.py output → analysis.liquidity."""
buySide: list[LiquidityLevel] = []
sellSide: list[LiquidityLevel] = []
class OrderBlock(BaseModel):
"""Single order block or breaker block."""
type: str # 'OB'|'BB'
direction: str # 'bull'|'bear'
top: float
bottom: float
timeframe: str
mitigated: bool
class MSSLevel(BaseModel):
"""Single market structure shift level."""
price: float
timeframe: str
confirmed: bool
class MSSResult(BaseModel):
"""engine/mss.py output → analysis.mss."""
bullish: list[MSSLevel] = []
bearish: list[MSSLevel] = []
class DFRTimeframe(BaseModel):
"""DFR levels for one timeframe (daily or weekly)."""
levels: list[float] = [] # ±1, ±2, ±2.5, ±4 std dev from anchor
class DFRResult(BaseModel):
"""engine/dfr.py output → analysis.dfr."""
daily: DFRTimeframe = Field(default_factory=DFRTimeframe)
weekly: DFRTimeframe = Field(default_factory=DFRTimeframe)
class DXYCorrelation(BaseModel):
"""DXY data snapshot inside correlation result."""
price: Optional[float] = None
change: Optional[float] = None
bias: Optional[str] = None # 'bull'|'bear'|'neutral'
class CorrelationResult(BaseModel):
"""engine/correlation.py output → analysis.correlation."""
dxy: DXYCorrelation = Field(default_factory=DXYCorrelation)
pairs: dict[str, Any] = {}
lowConfidence: bool = False # True when DXY contradicts pair bias
class SessionBiasResult(BaseModel):
"""engine/bias.py output → analysis.sessionBias."""
direction: Optional[str] = None # 'bull'|'bear'|'neutral'
confidence: float = 0.0
reasons: list[str] = []
class DecisionResult(BaseModel):
"""engine/decision.py output → analysis.decision."""
state: str = 'WAIT' # 'TRADE'|'PREPARE'|'WATCH'|'WAIT'|'AVOID'|'MANAGE'
reason: str = ''
entry: Optional[float] = None
sl: Optional[float] = None
tp: Optional[float] = None
rr: Optional[float] = None
class AnalysisResponse(BaseModel):
"""GET /api/analysis response — full ICT signal state.
Mirrors SFX.state.analysis exactly. The frontend's priceEngine.js
merges this response into SFX.state.analysis on every 15s poll.
"""
model_config = ConfigDict(arbitrary_types_allowed=True)
cycles: CyclesResult = Field(default_factory=CyclesResult)
smt: SMTResult = Field(default_factory=SMTResult)
qcisd: QCISDResult = Field(default_factory=QCISDResult)
trueOpen: TrueOpenResult = Field(default_factory=TrueOpenResult)
liquidity: LiquidityResult = Field(default_factory=LiquidityResult)
orderblocks: list[OrderBlock] = []
mss: MSSResult = Field(default_factory=MSSResult)
dfr: DFRResult = Field(default_factory=DFRResult)
correlation: CorrelationResult = Field(default_factory=CorrelationResult)
sessionBias: SessionBiasResult = Field(default_factory=SessionBiasResult)
decision: DecisionResult = Field(default_factory=DecisionResult)
lastUpdated: int = 0 # Unix ms
# ─────────────────────────────────────────────────────────────────────────────
# AI DECISION
# ─────────────────────────────────────────────────────────────────────────────
class AIDecisionResponse(BaseModel):
"""GET /api/ai-decision response."""
summary: str
bias: Optional[str] = None # 'bull'|'bear'|'neutral'
confidence: float = 0.0 # 0.0–10.0
# ─────────────────────────────────────────────────────────────────────────────
# HELPER — engine result → Pydantic model conversion
# ─────────────────────────────────────────────────────────────────────────────
def engine_dict(result: Any, default: Any = None) -> Any:
"""Convert an engine result dataclass to a dict for Pydantic validation.
Strips the 'error' key. Returns `default` when result.error is set.
All engine compute() functions return a dataclass with an error field.
Args:
result: Engine result dataclass (has .error: Optional[str]).
default: Value to return when result.error is not None.
Returns:
vars(result) without 'error' key, or default on engine error.
Example:
cycles_dict = engine_dict(cycles_r, default={})
cycles = CyclesResult.model_validate(cycles_dict)
"""
if default is None:
default = {}
if getattr(result, 'error', None):
return default
return {k: v for k, v in vars(result).items() if k != 'error'}

Xet Storage Details

Size:
12.4 kB
·
Xet hash:
d045d565b82a1ab7e90eeb1093284a15163b5d1d52585a9c41a518542ca51089

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.