From 354c3d484a9fdc1c711f2c7f6c16e41d39d2fd6a Mon Sep 17 00:00:00 2001 From: Celes Renata Date: Thu, 16 Apr 2026 15:17:49 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20fetch=20current=20prices=20from=20market?= =?UTF-8?q?=5Fsnapshots=20before=20evaluating=20recommendations=20?= =?UTF-8?q?=E2=80=94=20fixes=20'Invalid=20current=20price'=20skip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/trading/engine.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/services/trading/engine.py b/services/trading/engine.py index 74e967c..63bfea2 100644 --- a/services/trading/engine.py +++ b/services/trading/engine.py @@ -599,6 +599,28 @@ class TradingEngine: "Polled %d recommendations (highest confidence=%.3f)", len(recs), recs[0].get("confidence", 0), ) + + # Fetch current prices for all tickers in this batch + batch_tickers = list({r.get("ticker", "") for r in recs if r.get("ticker")}) + price_map: dict[str, float] = {} + if batch_tickers and self.pool is not None: + try: + price_rows = await self.pool.fetch( + """SELECT DISTINCT ON (ticker) ticker, (data->>'c')::float AS price + FROM market_snapshots + WHERE ticker = ANY($1) AND snapshot_type = 'bar' + ORDER BY ticker, captured_at DESC""", + batch_tickers, + ) + price_map = {r["ticker"]: r["price"] for r in price_rows if r["price"]} + except Exception: + logger.debug("Could not fetch prices from market_snapshots") + + # Fall back to Polygon API for any missing prices + missing = [t for t in batch_tickers if t not in price_map] + if missing: + fetched = await self._fetch_current_prices(missing) + price_map.update(fetched) except Exception: logger.debug("Could not poll recommendations — table may not exist yet") continue @@ -606,6 +628,15 @@ class TradingEngine: for rec in recs: try: rec_id = str(rec.get("recommendation_id", rec.get("id", ""))) + ticker = rec.get("ticker", "") + + # Inject current price from market data + if not rec.get("current_price") and ticker in price_map: + rec["current_price"] = price_map[ticker] + + # Skip if no price available + if not rec.get("current_price") or rec["current_price"] <= 0: + continue # Redis deduplication check if self.redis is not None: