mabdullahsibghatullah123 commited on
Commit
b2cc431
Β·
verified Β·
1 Parent(s): 868b4b2

Upload 5 files

Browse files
backend/agent.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import urllib.request
4
+ import xml.etree.ElementTree as ET
5
+ import logging
6
+ import random
7
+ from typing import Dict, Any, List, Optional, Tuple
8
+ from backend.alpaca_helper import AlpacaHelper
9
+ from backend.risk_engine import RiskEngine
10
+
11
+ logger = logging.getLogger("SentryTheta.Agent")
12
+
13
+ class SentryThetaAgent:
14
+ def __init__(self, alpaca_helper: AlpacaHelper, risk_engine: RiskEngine):
15
+ self.alpaca = alpaca_helper
16
+ self.risk_engine = risk_engine
17
+
18
+ # Initialize Gemini API
19
+ self.gemini_api_key = os.getenv("GEMINI_API_KEY", "")
20
+ self.use_gemini = bool(self.gemini_api_key and self.gemini_api_key != "your_gemini_key_here")
21
+
22
+ if self.use_gemini:
23
+ try:
24
+ import google.generativeai as genai
25
+ genai.configure(api_key=self.gemini_api_key)
26
+ self.model = genai.GenerativeModel("gemini-1.5-flash")
27
+ logger.info("Gemini AI Client configured successfully for Market Analyst.")
28
+ except Exception as e:
29
+ logger.error(f"Failed to configure Gemini AI: {e}. Falling back to rule-based sentiment.")
30
+ self.use_gemini = False
31
+ else:
32
+ logger.info("No Gemini API key detected. Using rule-based sentiment analysis.")
33
+
34
+ def fetch_ticker_news(self, ticker: str) -> List[str]:
35
+ """Fetch real-time news headlines from Yahoo Finance RSS feed."""
36
+ headlines = []
37
+ try:
38
+ url = f"https://finance.yahoo.com/rss/headline?s={ticker}"
39
+ headers = {'User-Agent': 'Mozilla/5.0'}
40
+ req = urllib.request.Request(url, headers=headers)
41
+ with urllib.request.urlopen(req, timeout=5) as response:
42
+ xml_data = response.read()
43
+
44
+ root = ET.fromstring(xml_data)
45
+ for item in root.findall('.//item'):
46
+ title = item.find('title')
47
+ if title is not None and title.text:
48
+ headlines.append(title.text)
49
+
50
+ logger.info(f"Fetched {len(headlines)} headlines for {ticker} from RSS feed.")
51
+ except Exception as e:
52
+ logger.error(f"Error fetching RSS news for {ticker}: {e}")
53
+ # Fallback mock headlines if network fails
54
+ headlines = self._get_mock_headlines(ticker)
55
+
56
+ return headlines if headlines else self._get_mock_headlines(ticker)
57
+
58
+ def _get_mock_headlines(self, ticker: str) -> List[str]:
59
+ """Provide mock headlines for fallback."""
60
+ mocks = {
61
+ "AAPL": [
62
+ "Apple signs new deal with chip supplier for advanced AI integration",
63
+ "App Store revenue increases as services business grows in Europe",
64
+ "Apple Stock faces downgrade over short-term supply chain delays",
65
+ "Why Apple Intelligence will drive the next multi-year upgrade cycle"
66
+ ],
67
+ "NVDA": [
68
+ "NVIDIA chip demand reaches record high ahead of data center expansion",
69
+ "Competitor launches new AI accelerator targeting NVIDIA market share",
70
+ "NVIDIA stock hits new high as analyst raises target price",
71
+ "Taiwan semiconductor supply chain disruptions pose risk to NVIDIA shipments"
72
+ ],
73
+ "MSFT": [
74
+ "Microsoft cloud services report massive quarterly growth fueled by Azure AI",
75
+ "Security patches issued after Windows exploit detected in corporate networks",
76
+ "Microsoft announces partnership with energy startup to power AI data centers",
77
+ "Analysts positive on Microsoft ahead of key developer conference"
78
+ ],
79
+ "SPY": [
80
+ "Federal Reserve signals potential rate cut in upcoming economic report",
81
+ "US inflation numbers come in cooler than expected, boosting indices",
82
+ "Geopolitical tensions spark brief sell-off in major index funds",
83
+ "Wall Street rallies as retail sales figures beat expectations"
84
+ ],
85
+ "QQQ": [
86
+ "Nasdaq 100 leads rally as tech giants continue strong earnings momentum",
87
+ "Treasury yields surge, placing pressure on high-growth tech stocks",
88
+ "Tech sector volatility spikes as option volume hits quarterly record",
89
+ "Semiconductor index rallies, lifting tech ETFs to weekly highs"
90
+ ]
91
+ }
92
+ return mocks.get(ticker, [
93
+ f"Analysts hold neutral outlook on {ticker} amid macro uncertainties",
94
+ f"{ticker} announces new efficiency plans and expansion to cut costs",
95
+ f"Trading volume for {ticker} increases ahead of quarterly earnings announcement"
96
+ ])
97
+
98
+ def analyze_market_sentiment(self, ticker: str) -> Tuple[float, str]:
99
+ """
100
+ Analyze news headlines to output a sentiment score (-1.0 to +1.0) and justification.
101
+ """
102
+ headlines = self.fetch_ticker_news(ticker)
103
+ headlines_str = "\n".join([f"- {h}" for h in headlines[:5]])
104
+
105
+ if self.use_gemini:
106
+ try:
107
+ prompt = (
108
+ f"You are a professional financial market analyst evaluating {ticker}.\n"
109
+ f"Analyze the following recent news headlines:\n\n{headlines_str}\n\n"
110
+ f"Based ONLY on these headlines, score the market sentiment for {ticker} between -1.0 (strongly bearish) and +1.0 (strongly bullish).\n"
111
+ f"Format your response exactly as follows and nothing else:\n"
112
+ f"SCORE: [score between -1.0 and 1.0]\n"
113
+ f"ANALYSIS: [1-2 sentences explaining why, summarizing the main positive or negative drivers]"
114
+ )
115
+
116
+ response = self.model.generate_content(prompt)
117
+ text = response.text.strip()
118
+
119
+ score_match = re.search(r"SCORE:\s*(-?\d+(\.\d+)?)", text)
120
+ analysis_match = re.search(r"ANALYSIS:\s*(.*)", text, re.DOTALL)
121
+
122
+ score = float(score_match.group(1)) if score_match else 0.0
123
+ analysis = analysis_match.group(1).strip() if analysis_match else "Could not extract analysis from LLM output."
124
+
125
+ # Constrain score
126
+ score = max(-1.0, min(1.0, score))
127
+ return score, analysis
128
+
129
+ except Exception as e:
130
+ logger.error(f"Gemini sentiment analysis failed: {e}. Falling back to rule-based.")
131
+
132
+ # Rule-based fallback (reads positive/negative keywords in headlines)
133
+ pos_words = ["high", "grow", "surge", "gain", "buy", "up", "beat", "rally", "positive", "expand", "deal", "deal with"]
134
+ neg_words = ["drop", "downgrade", "exploit", "delay", "sell", "pressure", "disruption", "risk", "short-term", "down"]
135
+
136
+ score_sum = 0.0
137
+ for h in headlines:
138
+ h_lower = h.lower()
139
+ for w in pos_words:
140
+ if w in h_lower:
141
+ score_sum += 0.25
142
+ for w in neg_words:
143
+ if w in h_lower:
144
+ score_sum -= 0.25
145
+
146
+ # Apply some random market noise to make it dynamic
147
+ score_sum += random.uniform(-0.15, 0.15)
148
+ score = round(max(-1.0, min(1.0, score_sum)), 2)
149
+
150
+ driver = "positive updates on AI and partnerships" if score > 0 else "supply chain delays or analyst pressure"
151
+ if abs(score) < 0.2:
152
+ driver = "mixed or balanced recent headlines"
153
+
154
+ analysis = f"Rule-based sentiment shows {ticker} at {score} driven by {driver} observed in recent headlines."
155
+ return score, analysis
156
+
157
+ def propose_options_trade(self, ticker: str, sentiment_score: float) -> Optional[Dict[str, Any]]:
158
+ """
159
+ Formulate an option strategy based on sentiment score and available option chain.
160
+ """
161
+ # Fetch option chain
162
+ chain = self.alpaca.get_option_chain(ticker)
163
+ if not chain:
164
+ logger.warning(f"No option contracts found in chain for {ticker}.")
165
+ return None
166
+
167
+ # Determine strategy direction based on sentiment
168
+ # Strong Bullish: Buy Call
169
+ # Strong Bearish: Buy Put
170
+ # Mildly Bullish/Bearish/Neutral: Sell OTM Credit Spreads or Sell Covered Call/Cash-Secured Put
171
+
172
+ if sentiment_score >= 0.25:
173
+ # Bullish Strategy: Buy Call Option
174
+ target_type = "call"
175
+ strategy_name = "Long Call Strategy"
176
+ side = "buy"
177
+ elif sentiment_score <= -0.25:
178
+ # Bearish Strategy: Buy Put Option
179
+ target_type = "put"
180
+ strategy_name = "Long Put Strategy"
181
+ side = "buy"
182
+ else:
183
+ # Neutral/Range-bound Strategy: Sell out-of-the-money Call option (Covered Call simulation)
184
+ # or sell Cash-Secured Put to collect premium. Let's do Cash-Secured Put (Sell Put)
185
+ target_type = "put"
186
+ strategy_name = "Cash-Secured Put (Income)"
187
+ side = "sell"
188
+
189
+ # Select best contract (expiry near-term, strike near-the-money)
190
+ # For buying Call/Put, we want Strike near the stock price (ATM)
191
+ # For writing Cash-Secured Put, we want Strike 3-5% Out-of-the-money (OTM)
192
+
193
+ # Find current stock price from the chain snapshot
194
+ stock_price = chain[0].get("stock_price", 100.0) if chain else 100.0
195
+
196
+ eligible_contracts = [c for c in chain if c["type"] == target_type]
197
+ if not eligible_contracts:
198
+ return None
199
+
200
+ # Filter contract based on strategy criteria
201
+ best_contract = None
202
+ if side == "buy":
203
+ # Find closest to stock price (ATM)
204
+ best_contract = min(eligible_contracts, key=lambda c: abs(c["strike"] - stock_price))
205
+ else:
206
+ # Sell OTM put: strike should be slightly below stock price
207
+ otm_puts = [c for c in eligible_contracts if c["strike"] <= stock_price * 0.96]
208
+ if otm_puts:
209
+ # Get the one closest to the 4% OTM boundary
210
+ best_contract = max(otm_puts, key=lambda c: c["strike"])
211
+ else:
212
+ best_contract = min(eligible_contracts, key=lambda c: abs(c["strike"] - stock_price))
213
+
214
+ if not best_contract:
215
+ return None
216
+
217
+ premium = best_contract["last_price"]
218
+ # Default Quantity based on a standard position sizing approach
219
+ # Buy 1-5 contracts depending on pricing (aim for ~$500-$1000 premium total)
220
+ qty = max(1, min(5, int(1000 / (premium * 100))))
221
+
222
+ proposed_trade = {
223
+ "ticker": ticker,
224
+ "strategy": strategy_name,
225
+ "symbol": best_contract["symbol"],
226
+ "type": best_contract["type"],
227
+ "strike": best_contract["strike"],
228
+ "expiration": best_contract["expiration"],
229
+ "side": side,
230
+ "qty": qty,
231
+ "premium": premium,
232
+ "total_value": round(premium * qty * 100, 2),
233
+ "stock_price": stock_price,
234
+ "sentiment_score": sentiment_score
235
+ }
236
+
237
+ return proposed_trade
238
+
239
+ def run_agent_scan(self, target_tickers: List[str]) -> Tuple[List[Dict[str, Any]], List[str]]:
240
+ """
241
+ Execute one complete agent scanning cycle over target tickers.
242
+ Returns:
243
+ (list of approved proposals, list of execution logs)
244
+ """
245
+ logs = []
246
+ proposals = []
247
+
248
+ logs.append(f"πŸ€– Agent Scan Cycle started at {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
249
+
250
+ # 1. Fetch current account info & positions
251
+ acc_info = self.alpaca.get_account_info()
252
+ positions = self.alpaca.get_active_positions()
253
+
254
+ logs.append(f"[Portfolio] Balance: ${acc_info['equity']:.2f} | Buying Power: ${acc_info['buying_power']:.2f}")
255
+
256
+ # 2. Portfolio Risk Check (Stop Loss / Take Profit)
257
+ exit_trades = self.risk_engine.check_portfolio_risk(positions)
258
+ if exit_trades:
259
+ for exit in exit_trades:
260
+ logs.append(f"⚠️ [Risk Officer] Safety Breach Detected! closing position {exit['symbol']}. Reason: {exit['reason']}")
261
+ # Execute liquidation immediately
262
+ res = self.alpaca.execute_options_trade(exit["symbol"], exit["qty"], exit["side"], "Liquidation")
263
+ if res["success"]:
264
+ logs.append(f"βœ… [Executor] Closed contract {exit['symbol']}. Received filling ID: {res['order_id']}")
265
+ else:
266
+ logs.append(f"❌ [Executor] Failed to close contract: {res.get('error')}")
267
+ else:
268
+ logs.append("[Risk Officer] No stop-loss or take-profit targets triggered on active positions.")
269
+
270
+ # 3. Analyze and Propose Trades for Tickers
271
+ held_tickers = {pos["underlying_symbol"] for pos in positions}
272
+ available_tickers = [t for t in target_tickers if t not in held_tickers]
273
+
274
+ if not available_tickers:
275
+ logs.append("[Strategist] Already holding positions in all target tickers. Monitoring active positions for exits.")
276
+ return proposals, logs
277
+
278
+ selected_ticker = random.choice(available_tickers)
279
+ logs.append(f"[Analyst] Starting analysis on target ticker: {selected_ticker}")
280
+
281
+ sentiment, analysis = self.analyze_market_sentiment(selected_ticker)
282
+ logs.append(f"[Analyst] {selected_ticker} Sentiment: {sentiment:+.2f} | {analysis}")
283
+
284
+ proposed_trade = self.propose_options_trade(selected_ticker, sentiment)
285
+
286
+ if proposed_trade:
287
+ logs.append(
288
+ f"[Strategist] Proposing {proposed_trade['strategy']} on {selected_ticker}: "
289
+ f"{proposed_trade['side'].upper()} {proposed_trade['qty']}x {proposed_trade['symbol']} "
290
+ f"at Premium ${proposed_trade['premium']:.2f} (Total: ${proposed_trade['total_value']:.2f})"
291
+ )
292
+
293
+ # Run Sentry Risk Evaluation
294
+ approved, risk_reason = self.risk_engine.evaluate_trade(
295
+ symbol=proposed_trade["symbol"],
296
+ qty=proposed_trade["qty"],
297
+ premium_per_contract=proposed_trade["premium"],
298
+ side=proposed_trade["side"],
299
+ account_info=acc_info
300
+ )
301
+
302
+ if approved:
303
+ logs.append(f"πŸ›‘οΈ [Risk Officer] Approved. {risk_reason}")
304
+ proposed_trade["risk_checked"] = True
305
+ proposals.append(proposed_trade)
306
+ else:
307
+ logs.append(f"πŸ›‘οΈ [Risk Officer] REJECTED. Reason: {risk_reason}")
308
+ else:
309
+ logs.append(f"[Strategist] No viable option strategy identified for {selected_ticker}.")
310
+
311
+ return proposals, logs
312
+ import datetime
backend/alpaca_helper.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import datetime
4
+ from typing import Dict, List, Any, Optional
5
+ from dotenv import load_dotenv
6
+ from backend.db_helper import DBHelper
7
+
8
+ # Try importing Alpaca Py SDK
9
+ try:
10
+ from alpaca.trading.client import TradingClient
11
+ from alpaca.trading.requests import GetOptionContractsRequest, MarketOrderRequest, LimitOrderRequest
12
+ from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass
13
+ from alpaca.data.historical.option import OptionHistoricalDataClient
14
+ from alpaca.data.requests import OptionChainRequest
15
+ ALPACA_SDK_AVAILABLE = True
16
+ except ImportError:
17
+ ALPACA_SDK_AVAILABLE = False
18
+
19
+ load_dotenv()
20
+
21
+ logger = logging.getLogger("SentryTheta.AlpacaHelper")
22
+
23
+ class AlpacaHelper:
24
+ def __init__(self):
25
+ self.db = DBHelper()
26
+ self.api_key = os.getenv("ALPACA_API_KEY", "your_alpaca_key_here")
27
+ self.secret_key = os.getenv("ALPACA_SECRET_KEY", "your_alpaca_secret_here")
28
+ self.paper = os.getenv("ALPACA_PAPER", "true").lower() == "true"
29
+
30
+ # Check if keys are placeholders or empty
31
+ self.is_mock = (
32
+ not ALPACA_SDK_AVAILABLE or
33
+ self.api_key == "your_alpaca_key_here" or
34
+ self.secret_key == "your_alpaca_secret_here" or
35
+ not self.api_key or
36
+ not self.secret_key
37
+ )
38
+
39
+ if self.is_mock:
40
+ logger.warning("Alpaca API keys are missing or invalid. Running in MOCK MODE.")
41
+ self._init_mock_data()
42
+ else:
43
+ try:
44
+ self.trading_client = TradingClient(self.api_key, self.secret_key, paper=self.paper)
45
+ self.data_client = OptionHistoricalDataClient(self.api_key, self.secret_key)
46
+ logger.info(f"Alpaca Client initialized successfully (Paper={self.paper})")
47
+ except Exception as e:
48
+ logger.error(f"Failed to initialize Alpaca Client: {e}. Falling back to MOCK MODE.")
49
+ self.is_mock = True
50
+ self._init_mock_data()
51
+
52
+ def _init_mock_data(self):
53
+ """Initialize mock portfolio state for fallback demonstration, loading from SQLite."""
54
+ # Load cash and initial equity from DB
55
+ self.mock_cash, self.mock_initial_equity = self.db.get_mock_portfolio()
56
+ self.mock_buying_power = self.mock_cash * 2.0
57
+
58
+ # Load positions from DB
59
+ positions_list = self.db.get_mock_positions()
60
+
61
+ if not positions_list:
62
+ # First time setup: populate with initial sample data
63
+ initial_data = {
64
+ "NVDA260904C00125000": {
65
+ "symbol": "NVDA260904C00125000",
66
+ "underlying_symbol": "NVDA",
67
+ "qty": 2,
68
+ "entry_price": 4.50,
69
+ "current_price": 5.20,
70
+ "side": "buy",
71
+ "type": "call",
72
+ "strike": 125.0,
73
+ "expiration": "2026-09-04",
74
+ "market_value": 1040.0,
75
+ "cost_basis": 900.0,
76
+ "unrealized_pl": 140.0,
77
+ "unrealized_plpc": 0.1556
78
+ },
79
+ "AAPL260911P00215000": {
80
+ "symbol": "AAPL260911P00215000",
81
+ "underlying_symbol": "AAPL",
82
+ "qty": 1,
83
+ "entry_price": 3.20,
84
+ "current_price": 2.80,
85
+ "side": "buy",
86
+ "type": "put",
87
+ "strike": 215.0,
88
+ "expiration": "2026-09-11",
89
+ "market_value": 280.0,
90
+ "cost_basis": 320.0,
91
+ "unrealized_pl": -40.0,
92
+ "unrealized_plpc": -0.125
93
+ }
94
+ }
95
+ self.mock_positions = initial_data
96
+ for pos in initial_data.values():
97
+ self.db.save_mock_position(pos["symbol"], pos)
98
+ self._recalculate_mock_totals()
99
+ self.mock_initial_equity = self.mock_equity
100
+ self.db.save_mock_portfolio(self.mock_cash, self.mock_initial_equity)
101
+ else:
102
+ self.mock_positions = {pos["symbol"]: pos for pos in positions_list}
103
+ self._recalculate_mock_totals()
104
+
105
+ def _recalculate_mock_totals(self):
106
+ """Update mock portfolio cash/equity/P&L values and save to DB."""
107
+ positions_value = sum(pos["market_value"] for pos in self.mock_positions.values())
108
+ self.mock_equity = self.mock_cash + positions_value
109
+ self.mock_buying_power = self.mock_cash * 2.0
110
+ self.db.save_mock_portfolio(self.mock_cash, self.mock_initial_equity)
111
+
112
+ def get_account_info(self) -> Dict[str, Any]:
113
+ """Fetch account equity, cash, buying power and today's P&L."""
114
+ if self.is_mock:
115
+ # Simulate slight drift in current prices to make UI dynamic
116
+ import random
117
+ for sym, pos in self.mock_positions.items():
118
+ change = random.uniform(-0.05, 0.07) # slightly upward drift
119
+ pos["current_price"] = max(0.05, round(pos["current_price"] + change, 2))
120
+ pos["market_value"] = pos["current_price"] * pos["qty"] * 100
121
+ pos["unrealized_pl"] = pos["market_value"] - pos["cost_basis"]
122
+ pos["unrealized_plpc"] = pos["unrealized_pl"] / pos["cost_basis"]
123
+ # Save drifted price to SQLite
124
+ self.db.save_mock_position(sym, pos)
125
+
126
+ self._recalculate_mock_totals()
127
+ today_pl = self.mock_equity - self.mock_initial_equity
128
+ today_plpc = today_pl / self.mock_initial_equity
129
+
130
+ return {
131
+ "equity": round(self.mock_equity, 2),
132
+ "cash": round(self.mock_cash, 2),
133
+ "buying_power": round(self.mock_buying_power, 2),
134
+ "today_pl": round(today_pl, 2),
135
+ "today_plpc": round(today_plpc, 4),
136
+ "currency": "USD",
137
+ "is_mock": True
138
+ }
139
+
140
+ try:
141
+ acc = self.trading_client.get_account()
142
+ # Fetch equity, cash, etc.
143
+ equity = float(acc.equity)
144
+ cash = float(acc.cash)
145
+ buying_power = float(acc.buying_power)
146
+
147
+ # Calculate daily P&L
148
+ last_equity = float(acc.last_equity)
149
+ today_pl = equity - last_equity
150
+ today_plpc = today_pl / last_equity if last_equity > 0 else 0
151
+
152
+ # Cache live values
153
+ self._cached_equity = equity
154
+ self._cached_cash = cash
155
+ self._cached_buying_power = buying_power
156
+ self._cached_today_pl = today_pl
157
+ self._cached_today_plpc = today_plpc
158
+
159
+ return {
160
+ "equity": round(equity, 2),
161
+ "cash": round(cash, 2),
162
+ "buying_power": round(buying_power, 2),
163
+ "today_pl": round(today_pl, 2),
164
+ "today_plpc": round(today_plpc, 4),
165
+ "currency": "USD",
166
+ "is_mock": False
167
+ }
168
+ except Exception as e:
169
+ logger.error(f"Error fetching real account info: {e}.")
170
+ return {
171
+ "equity": round(getattr(self, "_cached_equity", self.mock_equity), 2),
172
+ "cash": round(getattr(self, "_cached_cash", self.mock_cash), 2),
173
+ "buying_power": round(getattr(self, "_cached_buying_power", self.mock_buying_power), 2),
174
+ "today_pl": round(getattr(self, "_cached_today_pl", 0.0), 2),
175
+ "today_plpc": round(getattr(self, "_cached_today_plpc", 0.0), 4),
176
+ "currency": "USD",
177
+ "is_mock": False
178
+ }
179
+
180
+ def get_active_positions(self) -> List[Dict[str, Any]]:
181
+ """Fetch current open options positions."""
182
+ if self.is_mock:
183
+ return list(self.mock_positions.values())
184
+
185
+ try:
186
+ positions = self.trading_client.get_all_positions()
187
+ formatted = []
188
+ for pos in positions:
189
+ # Filter for options positions (symbol length > 6 and format includes numbers/expiry)
190
+ # Alpaca represents option positions in standard OCC formatting
191
+ if len(pos.symbol) > 6 and any(c.isdigit() for c in pos.symbol):
192
+ # Extract contract details from symbol if possible
193
+ # Symbol e.g. AAPL260911P00215000
194
+ qty = int(pos.qty)
195
+ entry_price = float(pos.avg_entry_price)
196
+ current_price = float(pos.current_price)
197
+ market_value = float(pos.market_value)
198
+ unrealized_pl = float(pos.unrealized_intraday_pl)
199
+ unrealized_plpc = float(pos.unrealized_intraday_plpc)
200
+
201
+ # Parse OCC
202
+ ticker = pos.symbol[:4].strip()
203
+ # We can attempt to parse strike/expiry for display
204
+ # AAPL 260911 P 00215000
205
+ # Expiry YYMMDD
206
+ expiry = f"20{pos.symbol[4:6]}-{pos.symbol[6:8]}-{pos.symbol[8:10]}"
207
+ opt_type = "call" if pos.symbol[10].upper() == 'C' else "put"
208
+ strike = float(pos.symbol[11:]) / 1000.0
209
+
210
+ formatted.append({
211
+ "symbol": pos.symbol,
212
+ "underlying_symbol": ticker,
213
+ "qty": qty,
214
+ "entry_price": entry_price,
215
+ "current_price": current_price,
216
+ "side": pos.side,
217
+ "type": opt_type,
218
+ "strike": strike,
219
+ "expiration": expiry,
220
+ "market_value": market_value,
221
+ "cost_basis": entry_price * qty * 100,
222
+ "unrealized_pl": unrealized_pl,
223
+ "unrealized_plpc": unrealized_plpc
224
+ })
225
+ return formatted
226
+ except Exception as e:
227
+ logger.error(f"Error fetching real positions: {e}. Using mock positions.")
228
+ return list(self.mock_positions.values())
229
+
230
+ def get_option_chain(self, ticker: str) -> List[Dict[str, Any]]:
231
+ """Fetch active option contracts and snapshots for a stock ticker."""
232
+ if self.is_mock:
233
+ return self._generate_mock_option_chain(ticker)
234
+
235
+ try:
236
+ current_date = datetime.date.today()
237
+ expiry_limit = current_date + datetime.timedelta(days=30)
238
+
239
+ # 1. Fetch metadata for active options with expiration >= today
240
+ req = GetOptionContractsRequest(
241
+ underlying_symbols=[ticker],
242
+ status="active",
243
+ expiration_date_gte=current_date
244
+ )
245
+ response = self.trading_client.get_option_contracts(req)
246
+ contracts = getattr(response, "option_contracts", response) or []
247
+
248
+ valid_contracts = []
249
+ for c in contracts:
250
+ exp_val = c.expiration_date
251
+ if isinstance(exp_val, str):
252
+ expiry = datetime.datetime.strptime(exp_val, "%Y-%m-%d").date()
253
+ else:
254
+ expiry = exp_val
255
+
256
+ if current_date <= expiry <= expiry_limit:
257
+ valid_contracts.append((c, expiry))
258
+
259
+ if not valid_contracts:
260
+ logger.warning(f"No valid future contracts returned by Alpaca for {ticker}. Using fallback chain.")
261
+ return self._generate_mock_option_chain(ticker)
262
+
263
+ # Limit to top 20 contracts for performance
264
+ valid_contracts = valid_contracts[:20]
265
+
266
+ # 2. Fetch market snapshots if available (using historical data client)
267
+ # In the basic paper plan, get_option_chain might have feed constraints, so we handle it gracefully
268
+ chain_list = []
269
+ for c, expiry in valid_contracts:
270
+ # We can fetch latest price/quotes
271
+ # If chain API fails, we populate with a default price based on strike
272
+ chain_list.append({
273
+ "symbol": c.symbol,
274
+ "underlying_symbol": ticker,
275
+ "strike": float(c.strike_price),
276
+ "expiration": expiry.strftime("%Y-%m-%d"),
277
+ "type": str(c.type.value) if hasattr(c.type, "value") else str(c.type),
278
+ "bid": float(c.strike_price) * 0.02, # default estimation
279
+ "ask": float(c.strike_price) * 0.022,
280
+ "last_price": float(c.strike_price) * 0.021
281
+ })
282
+
283
+ return chain_list
284
+ except Exception as e:
285
+ logger.error(f"Error fetching real option chain for {ticker}: {e}. Generating mock chain.")
286
+ return self._generate_mock_option_chain(ticker)
287
+
288
+ def _generate_mock_option_chain(self, ticker: str) -> List[Dict[str, Any]]:
289
+ """Generate mock option chain details based on current index prices."""
290
+ import random
291
+ # Base prices for target tickers
292
+ base_prices = {"AAPL": 220.0, "MSFT": 415.0, "NVDA": 120.0, "SPY": 560.0, "QQQ": 480.0}
293
+ base_price = base_prices.get(ticker, 150.0)
294
+
295
+ # Current stock price simulated drift
296
+ stock_price = base_price + random.uniform(-2.0, 2.0)
297
+
298
+ chain = []
299
+ today = datetime.date.today()
300
+ # Expiry Friday of this week
301
+ days_to_friday = (4 - today.weekday()) % 7
302
+ if days_to_friday == 0:
303
+ days_to_friday = 7
304
+ friday_expiry = today + datetime.timedelta(days=days_to_friday)
305
+ expiry_str = friday_expiry.strftime("%Y-%m-%d")
306
+
307
+ # Generate strikes around current stock price
308
+ strike_step = 5.0 if stock_price >= 200 else (1.0 if stock_price <= 150 else 2.5)
309
+ center_strike = round(stock_price / strike_step) * strike_step
310
+
311
+ strikes = [center_strike + i * strike_step for i in range(-4, 5)]
312
+
313
+ for strike in strikes:
314
+ for opt_type in ["call", "put"]:
315
+ # Simple Black-Scholes approximation for pricing mock premium
316
+ dist = strike - stock_price
317
+ if opt_type == "call":
318
+ intrinsic = max(0.0, -dist)
319
+ extrinsic = max(0.5, 8.0 - abs(dist) * 0.8)
320
+ else:
321
+ intrinsic = max(0.0, dist)
322
+ extrinsic = max(0.5, 8.0 - abs(dist) * 0.8)
323
+
324
+ premium = round(intrinsic + extrinsic, 2)
325
+ bid = max(0.05, round(premium - 0.10, 2))
326
+ ask = round(premium + 0.10, 2)
327
+
328
+ # OCC Symbol formatting: AAPL260904C00220000
329
+ expiry_code = friday_expiry.strftime("%y%m%d")
330
+ strike_code = f"{int(strike * 1000):08d}"
331
+ symbol = f"{ticker:<6}{expiry_code}{'C' if opt_type == 'call' else 'P'}{strike_code}".replace(" ", "")
332
+
333
+ chain.append({
334
+ "symbol": symbol,
335
+ "underlying_symbol": ticker,
336
+ "strike": strike,
337
+ "expiration": expiry_str,
338
+ "type": opt_type,
339
+ "bid": bid,
340
+ "ask": ask,
341
+ "last_price": premium,
342
+ "stock_price": round(stock_price, 2)
343
+ })
344
+ return chain
345
+
346
+ def execute_options_trade(self, symbol: str, qty: int, side: str, strategy_name: str = "Single Option") -> Dict[str, Any]:
347
+ """Place an option order on Alpaca or execute in Mock portfolio."""
348
+ side_enum = OrderSide.BUY if side.lower() == "buy" else OrderSide.SELL
349
+
350
+ if self.is_mock:
351
+ # Execute mock order
352
+ # 1. Parse symbol details
353
+ ticker = symbol[:4].strip()
354
+ opt_type = "call" if "C" in symbol else "put"
355
+ # simple mock price calculation
356
+ price = 3.50
357
+
358
+ # Find in mock chain if exists
359
+ mock_chain = self._generate_mock_option_chain(ticker)
360
+ for contract in mock_chain:
361
+ if contract["symbol"] == symbol:
362
+ price = contract["last_price"]
363
+ break
364
+
365
+ cost = price * qty * 100
366
+
367
+ if side.lower() == "buy":
368
+ if cost > self.mock_cash:
369
+ return {"success": False, "error": "Insufficient cash for buying option."}
370
+
371
+ self.mock_cash -= cost
372
+ if symbol in self.mock_positions:
373
+ pos = self.mock_positions[symbol]
374
+ old_qty = pos["qty"]
375
+ pos["qty"] += qty
376
+ pos["cost_basis"] += cost
377
+ pos["entry_price"] = pos["cost_basis"] / (pos["qty"] * 100)
378
+ else:
379
+ expiry = "2026-09-04"
380
+ strike = 120.0
381
+ # Parse strike/expiry from symbol
382
+ try:
383
+ # AAPL260904C00220000
384
+ # 0123456789012345678
385
+ # 0-3: AAPL, 4-9: 260904, 10: C, 11+: 00220000
386
+ expiry = f"20{symbol[4:6]}-{symbol[6:8]}-{symbol[8:10]}"
387
+ strike = float(symbol[11:]) / 1000.0
388
+ except:
389
+ pass
390
+
391
+ self.mock_positions[symbol] = {
392
+ "symbol": symbol,
393
+ "underlying_symbol": ticker,
394
+ "qty": qty,
395
+ "entry_price": price,
396
+ "current_price": price,
397
+ "side": "buy",
398
+ "type": opt_type,
399
+ "strike": strike,
400
+ "expiration": expiry,
401
+ "market_value": cost,
402
+ "cost_basis": cost,
403
+ "unrealized_pl": 0.0,
404
+ "unrealized_plpc": 0.0
405
+ }
406
+ self.db.save_mock_position(symbol, self.mock_positions[symbol])
407
+ else: # SELL to close
408
+ if symbol not in self.mock_positions:
409
+ # Allow selling (writing call/put)
410
+ proceeds = cost
411
+ self.mock_cash += proceeds
412
+ # For simplicity, we just add it as a short position
413
+ expiry = "2026-09-04"
414
+ strike = 120.0
415
+ try:
416
+ expiry = f"20{symbol[4:6]}-{symbol[6:8]}-{symbol[8:10]}"
417
+ strike = float(symbol[11:]) / 1000.0
418
+ except:
419
+ pass
420
+
421
+ self.mock_positions[symbol] = {
422
+ "symbol": symbol,
423
+ "underlying_symbol": ticker,
424
+ "qty": -qty,
425
+ "entry_price": price,
426
+ "current_price": price,
427
+ "side": "sell",
428
+ "type": opt_type,
429
+ "strike": strike,
430
+ "expiration": expiry,
431
+ "market_value": -cost,
432
+ "cost_basis": -cost,
433
+ "unrealized_pl": 0.0,
434
+ "unrealized_plpc": 0.0
435
+ }
436
+ self.db.save_mock_position(symbol, self.mock_positions[symbol])
437
+ else:
438
+ pos = self.mock_positions[symbol]
439
+ if pos["qty"] > 0:
440
+ # Selling to close existing long
441
+ sell_qty = min(qty, pos["qty"])
442
+ pos["qty"] -= sell_qty
443
+ self.mock_cash += price * sell_qty * 100
444
+ if pos["qty"] == 0:
445
+ del self.mock_positions[symbol]
446
+ self.db.delete_mock_position(symbol)
447
+ else:
448
+ pos["cost_basis"] = pos["entry_price"] * pos["qty"] * 100
449
+ pos["market_value"] = pos["current_price"] * pos["qty"] * 100
450
+ self.db.save_mock_position(symbol, pos)
451
+ else:
452
+ # Adding to short position
453
+ pos["qty"] -= qty
454
+ self.mock_cash += cost
455
+ pos["cost_basis"] -= cost
456
+ pos["market_value"] = pos["current_price"] * pos["qty"] * 100
457
+ self.db.save_mock_position(symbol, pos)
458
+
459
+ self._recalculate_mock_totals()
460
+ return {
461
+ "success": True,
462
+ "order_id": f"mock_order_{datetime.datetime.now().strftime('%H%M%S%f')}",
463
+ "symbol": symbol,
464
+ "qty": qty,
465
+ "price": price,
466
+ "side": side,
467
+ "status": "filled",
468
+ "is_mock": True
469
+ }
470
+
471
+ try:
472
+ # Check if Level 3 spreads order can be executed as individual legs
473
+ # Alpaca Py SDK provides MarketOrderRequest and OptionLegRequest for multi-leg option orders
474
+ # But for simplicity, we submit standard single-leg option orders first, which handles Level 2
475
+ # For spreads, we can submit multiple orders or use the multi-leg order requests
476
+
477
+ # Basic single leg submission
478
+ order_data = MarketOrderRequest(
479
+ symbol=symbol,
480
+ qty=qty,
481
+ side=side_enum,
482
+ time_in_force=TimeInForce.DAY
483
+ )
484
+ order = self.trading_client.submit_order(order_data=order_data)
485
+
486
+ return {
487
+ "success": True,
488
+ "order_id": str(order.id),
489
+ "symbol": symbol,
490
+ "qty": qty,
491
+ "side": side,
492
+ "status": str(order.status),
493
+ "is_mock": False
494
+ }
495
+ except Exception as e:
496
+ logger.error(f"Failed to execute option trade for {symbol}: {e}")
497
+ return {"success": False, "error": str(e)}
backend/db_helper.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+ import datetime
4
+ import logging
5
+ from typing import Dict, Any, List, Optional, Tuple
6
+
7
+ logger = logging.getLogger("SentryTheta.DBHelper")
8
+ DB_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "sentrytheta.db"))
9
+
10
+ class DBHelper:
11
+ def __init__(self):
12
+ self.db_path = DB_PATH
13
+ self.init_db()
14
+
15
+ def get_connection(self):
16
+ """Returns a connection to the SQLite database."""
17
+ conn = sqlite3.connect(self.db_path)
18
+ conn.row_factory = sqlite3.Row # Access columns by name
19
+ return conn
20
+
21
+ def init_db(self):
22
+ """Initialize SQLite database tables if they do not exist."""
23
+ logger.info(f"Initializing database at: {self.db_path}")
24
+ conn = self.get_connection()
25
+ cursor = conn.cursor()
26
+
27
+ # 1. Settings Table
28
+ cursor.execute("""
29
+ CREATE TABLE IF NOT EXISTS settings (
30
+ key TEXT PRIMARY KEY,
31
+ value TEXT
32
+ )
33
+ """)
34
+
35
+ # 2. Terminal Logs Table
36
+ cursor.execute("""
37
+ CREATE TABLE IF NOT EXISTS terminal_logs (
38
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
39
+ timestamp TEXT,
40
+ message TEXT
41
+ )
42
+ """)
43
+
44
+ # 3. Mock Portfolio Table
45
+ cursor.execute("""
46
+ CREATE TABLE IF NOT EXISTS mock_portfolio (
47
+ id INTEGER PRIMARY KEY CHECK (id = 1),
48
+ cash REAL,
49
+ initial_equity REAL
50
+ )
51
+ """)
52
+
53
+ # Initialize default mock portfolio if empty
54
+ cursor.execute("SELECT COUNT(*) FROM mock_portfolio")
55
+ if cursor.fetchone()[0] == 0:
56
+ cursor.execute(
57
+ "INSERT INTO mock_portfolio (id, cash, initial_equity) VALUES (1, 95000.0, 100000.0)"
58
+ )
59
+
60
+ # 4. Mock Positions Table
61
+ cursor.execute("""
62
+ CREATE TABLE IF NOT EXISTS mock_positions (
63
+ symbol TEXT PRIMARY KEY,
64
+ underlying_symbol TEXT,
65
+ qty INTEGER,
66
+ entry_price REAL,
67
+ current_price REAL,
68
+ side TEXT,
69
+ type TEXT,
70
+ strike REAL,
71
+ expiration TEXT,
72
+ market_value REAL,
73
+ cost_basis REAL,
74
+ unrealized_pl REAL,
75
+ unrealized_plpc REAL
76
+ )
77
+ """)
78
+
79
+ conn.commit()
80
+ conn.close()
81
+ logger.info("Database tables initialized successfully.")
82
+
83
+ # --- Settings Handlers ---
84
+ def get_setting(self, key: str, default: Any = None) -> Any:
85
+ conn = self.get_connection()
86
+ cursor = conn.cursor()
87
+ cursor.execute("SELECT value FROM settings WHERE key = ?", (key,))
88
+ row = cursor.fetchone()
89
+ conn.close()
90
+ return row[0] if row else default
91
+
92
+ def set_setting(self, key: str, value: Any):
93
+ conn = self.get_connection()
94
+ cursor = conn.cursor()
95
+ cursor.execute(
96
+ "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
97
+ (key, str(value))
98
+ )
99
+ conn.commit()
100
+ conn.close()
101
+
102
+ def get_all_settings(self) -> Dict[str, str]:
103
+ conn = self.get_connection()
104
+ cursor = conn.cursor()
105
+ cursor.execute("SELECT key, value FROM settings")
106
+ rows = cursor.fetchall()
107
+ conn.close()
108
+ return {row["key"]: row["value"] for row in rows}
109
+
110
+ # --- Logs Handlers ---
111
+ def add_log(self, message: str):
112
+ conn = self.get_connection()
113
+ cursor = conn.cursor()
114
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
115
+ cursor.execute(
116
+ "INSERT INTO terminal_logs (timestamp, message) VALUES (?, ?)",
117
+ (timestamp, message)
118
+ )
119
+ conn.commit()
120
+ conn.close()
121
+
122
+ def get_logs(self, limit: int = 100) -> List[str]:
123
+ conn = self.get_connection()
124
+ cursor = conn.cursor()
125
+ cursor.execute(
126
+ "SELECT message FROM terminal_logs ORDER BY id DESC LIMIT ?",
127
+ (limit,)
128
+ )
129
+ rows = cursor.fetchall()
130
+ conn.close()
131
+ # Return in chronological order
132
+ return [row["message"] for row in reversed(rows)]
133
+
134
+ def clear_all_logs(self):
135
+ conn = self.get_connection()
136
+ cursor = conn.cursor()
137
+ cursor.execute("DELETE FROM terminal_logs")
138
+ conn.commit()
139
+ conn.close()
140
+
141
+ # --- Mock Portfolio Handlers ---
142
+ def get_mock_portfolio(self) -> Tuple[float, float]:
143
+ conn = self.get_connection()
144
+ cursor = conn.cursor()
145
+ cursor.execute("SELECT cash, initial_equity FROM mock_portfolio WHERE id = 1")
146
+ row = cursor.fetchone()
147
+ conn.close()
148
+ if row:
149
+ return float(row["cash"]), float(row["initial_equity"])
150
+ return 95000.0, 100000.0
151
+
152
+ def save_mock_portfolio(self, cash: float, initial_equity: float):
153
+ conn = self.get_connection()
154
+ cursor = conn.cursor()
155
+ cursor.execute(
156
+ "UPDATE mock_portfolio SET cash = ?, initial_equity = ? WHERE id = 1",
157
+ (cash, initial_equity)
158
+ )
159
+ conn.commit()
160
+ conn.close()
161
+
162
+ # --- Mock Positions Handlers ---
163
+ def get_mock_positions(self) -> List[Dict[str, Any]]:
164
+ conn = self.get_connection()
165
+ cursor = conn.cursor()
166
+ cursor.execute("SELECT * FROM mock_positions")
167
+ rows = cursor.fetchall()
168
+ conn.close()
169
+
170
+ positions = []
171
+ for row in rows:
172
+ positions.append({
173
+ "symbol": row["symbol"],
174
+ "underlying_symbol": row["underlying_symbol"],
175
+ "qty": int(row["qty"]),
176
+ "entry_price": float(row["entry_price"]),
177
+ "current_price": float(row["current_price"]),
178
+ "side": row["side"],
179
+ "type": row["type"],
180
+ "strike": float(row["strike"]),
181
+ "expiration": row["expiration"],
182
+ "market_value": float(row["market_value"]),
183
+ "cost_basis": float(row["cost_basis"]),
184
+ "unrealized_pl": float(row["unrealized_pl"]),
185
+ "unrealized_plpc": float(row["unrealized_plpc"])
186
+ })
187
+ return positions
188
+
189
+ def save_mock_position(self, symbol: str, pos: Dict[str, Any]):
190
+ conn = self.get_connection()
191
+ cursor = conn.cursor()
192
+ cursor.execute("""
193
+ INSERT OR REPLACE INTO mock_positions (
194
+ symbol, underlying_symbol, qty, entry_price, current_price,
195
+ side, type, strike, expiration, market_value, cost_basis,
196
+ unrealized_pl, unrealized_plpc
197
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
198
+ """, (
199
+ symbol,
200
+ pos["underlying_symbol"],
201
+ int(pos["qty"]),
202
+ float(pos["entry_price"]),
203
+ float(pos["current_price"]),
204
+ pos["side"],
205
+ pos["type"],
206
+ float(pos["strike"]),
207
+ pos["expiration"],
208
+ float(pos["market_value"]),
209
+ float(pos["cost_basis"]),
210
+ float(pos["unrealized_pl"]),
211
+ float(pos["unrealized_plpc"])
212
+ ))
213
+ conn.commit()
214
+ conn.close()
215
+
216
+ def delete_mock_position(self, symbol: str):
217
+ conn = self.get_connection()
218
+ cursor = conn.cursor()
219
+ cursor.execute("DELETE FROM mock_positions WHERE symbol = ?", (symbol,))
220
+ conn.commit()
221
+ conn.close()
backend/risk_engine.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from typing import Dict, Any, List, Tuple
4
+
5
+ logger = logging.getLogger("SentryTheta.RiskEngine")
6
+
7
+ class RiskEngine:
8
+ def __init__(self):
9
+ # Risk settings from env or defaults
10
+ self.max_position_size_pct = float(os.getenv("MAX_POSITION_SIZE_PERCENT", "5.0"))
11
+ self.max_daily_drawdown_pct = float(os.getenv("MAX_DAILY_DRAWDOWN_PERCENT", "3.0"))
12
+ self.stop_loss_pct = float(os.getenv("STOP_LOSS_PERCENT", "15.0"))
13
+ self.take_profit_pct = float(os.getenv("TAKE_PROFIT_PERCENT", "30.0"))
14
+
15
+ logger.info(
16
+ f"Risk Engine initialized: MaxPos={self.max_position_size_pct}%, "
17
+ f"MaxDrawdown={self.max_daily_drawdown_pct}%, "
18
+ f"SL={self.stop_loss_pct}%, TP={self.take_profit_pct}%"
19
+ )
20
+
21
+ def evaluate_trade(
22
+ self,
23
+ symbol: str,
24
+ qty: int,
25
+ premium_per_contract: float,
26
+ side: str,
27
+ account_info: Dict[str, Any]
28
+ ) -> Tuple[bool, str]:
29
+ """
30
+ Evaluate if a proposed trade satisfies risk parameters.
31
+ Returns:
32
+ (is_approved: bool, reason: str)
33
+ """
34
+ equity = account_info.get("equity", 100000.0)
35
+ cash = account_info.get("cash", 100000.0)
36
+ today_pl = account_info.get("today_pl", 0.0)
37
+
38
+ # Calculate cost/credit of trade
39
+ # Option contract represents 100 shares
40
+ trade_value = premium_per_contract * qty * 100
41
+
42
+ # 1. Daily Drawdown Check
43
+ # Reject new trades if today's drawdown exceeds limit
44
+ drawdown_limit = equity * (self.max_daily_drawdown_pct / 100.0)
45
+ if today_pl < 0 and abs(today_pl) >= drawdown_limit:
46
+ reason = f"Daily drawdown limit of {self.max_daily_drawdown_pct}% exceeded (Current today's P&L: ${today_pl:.2f}). Trading blocked."
47
+ logger.warning(reason)
48
+ return False, reason
49
+
50
+ # 2. Position Size Limit Check
51
+ # A single position should not exceed MAX_POSITION_SIZE_PERCENT of total equity
52
+ max_position_size = equity * (self.max_position_size_pct / 100.0)
53
+
54
+ if side.lower() == "buy":
55
+ # For buying options, the risk is the premium paid
56
+ if trade_value > max_position_size:
57
+ reason = (
58
+ f"Position size exceeds limit. Proposed cost: ${trade_value:.2f}, "
59
+ f"Max allowed ({self.max_position_size_pct}% of equity): ${max_position_size:.2f}."
60
+ )
61
+ logger.warning(reason)
62
+ return False, reason
63
+
64
+ # Cash availability check
65
+ if trade_value > cash:
66
+ reason = f"Insufficient cash to execute trade. Cost: ${trade_value:.2f}, Cash: ${cash:.2f}."
67
+ logger.warning(reason)
68
+ return False, reason
69
+
70
+ else: # Selling option (premium collection / write)
71
+ # In short options, margin requirement or collateral must be evaluated.
72
+ # For simplicity, we limit short premium trades to the same position size
73
+ # based on collateral value or margin impact.
74
+ if trade_value > max_position_size:
75
+ reason = (
76
+ f"Premium size exceeds limit. Proposed margin value: ${trade_value:.2f}, "
77
+ f"Max allowed ({self.max_position_size_pct}% of equity): ${max_position_size:.2f}."
78
+ )
79
+ logger.warning(reason)
80
+ return False, reason
81
+
82
+ return True, "Trade satisfies all Sentry Risk limits."
83
+
84
+ def check_portfolio_risk(self, active_positions: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
85
+ """
86
+ Scan active positions and return positions that breach Stop Loss or Take Profit targets.
87
+ Returns a list of trade suggestions to close positions.
88
+ """
89
+ exit_signals = []
90
+
91
+ for pos in active_positions:
92
+ unrealized_plpc = pos.get("unrealized_plpc", 0.0) * 100 # convert to %
93
+ symbol = pos.get("symbol")
94
+ qty = pos.get("qty", 0)
95
+
96
+ # Stop Loss (SL) check (Negative P&L)
97
+ if unrealized_plpc <= -self.stop_loss_pct:
98
+ logger.warning(f"Stop Loss breached for {symbol}: {unrealized_plpc:.2f}% (Limit: -{self.stop_loss_pct}%)")
99
+ exit_signals.append({
100
+ "symbol": symbol,
101
+ "qty": abs(qty),
102
+ "side": "sell" if qty > 0 else "buy",
103
+ "reason": f"Stop Loss target (-{self.stop_loss_pct}%) hit at {unrealized_plpc:.2f}%."
104
+ })
105
+
106
+ # Take Profit (TP) check (Positive P&L)
107
+ elif unrealized_plpc >= self.take_profit_pct:
108
+ logger.info(f"Take Profit hit for {symbol}: {unrealized_plpc:.2f}% (Limit: +{self.take_profit_pct}%)")
109
+ exit_signals.append({
110
+ "symbol": symbol,
111
+ "qty": abs(qty),
112
+ "side": "sell" if qty > 0 else "buy",
113
+ "reason": f"Take Profit target (+{self.take_profit_pct}%) hit at {unrealized_plpc:.2f}%."
114
+ })
115
+
116
+ return exit_signals
backend/server.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import asyncio
4
+ import logging
5
+ from typing import Dict, Any, List, Optional
6
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
7
+ from fastapi.staticfiles import StaticFiles
8
+ from fastapi.responses import FileResponse
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from pydantic import BaseModel
11
+ from dotenv import load_dotenv
12
+
13
+ from backend.alpaca_helper import AlpacaHelper
14
+ from backend.risk_engine import RiskEngine
15
+ from backend.agent import SentryThetaAgent
16
+
17
+ load_dotenv()
18
+
19
+ # Setup Logging
20
+ logging.basicConfig(
21
+ level=logging.INFO,
22
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
23
+ )
24
+ logger = logging.getLogger("SentryTheta.Server")
25
+
26
+ # FastAPI App Setup
27
+ app = FastAPI()
28
+
29
+ # Enable CORS for local development
30
+ app.add_middleware(
31
+ CORSMiddleware,
32
+ allow_origins=["*"],
33
+ allow_credentials=True,
34
+ allow_methods=["*"],
35
+ allow_headers=["*"],
36
+ )
37
+
38
+ # Initialize components
39
+ alpaca = AlpacaHelper()
40
+ risk_engine = RiskEngine()
41
+ agent = SentryThetaAgent(alpaca, risk_engine)
42
+
43
+ # Active WebSockets connection pool
44
+ class ConnectionManager:
45
+ def __init__(self):
46
+ self.active_connections: List[WebSocket] = []
47
+
48
+ async def connect(self, websocket: WebSocket):
49
+ await websocket.accept()
50
+ self.active_connections.append(websocket)
51
+ logger.info(f"New client connected. Active connections: {len(self.active_connections)}")
52
+
53
+ def disconnect(self, websocket: WebSocket):
54
+ if websocket in self.active_connections:
55
+ self.active_connections.remove(websocket)
56
+ logger.info(f"Client disconnected. Active connections: {len(self.active_connections)}")
57
+
58
+ async def broadcast(self, message: Dict[str, Any]):
59
+ for connection in self.active_connections:
60
+ try:
61
+ await connection.send_text(json.dumps(message))
62
+ except Exception as e:
63
+ # Connection might be dead
64
+ pass
65
+
66
+ manager = ConnectionManager()
67
+
68
+ db = alpaca.db
69
+
70
+ # Load settings from DB with fallback to env/defaults
71
+ db_settings = db.get_all_settings()
72
+
73
+ trading_mode = db_settings.get("trading_mode", os.getenv("TRADING_MODE", "copilot")).lower()
74
+ scan_interval = int(db_settings.get("scan_interval", os.getenv("SCAN_INTERVAL_SECONDS", "60")))
75
+
76
+ tickers_str = db_settings.get("tickers", os.getenv("TARGET_TICKERS", "AAPL,MSFT,NVDA,SPY,QQQ"))
77
+ tickers = [t.strip() for t in tickers_str.split(",")]
78
+
79
+ # Load risk parameters into RiskEngine
80
+ risk_engine.max_position_size_pct = float(db_settings.get("max_position_size_pct", os.getenv("MAX_POSITION_SIZE_PERCENT", "5.0")))
81
+ risk_engine.max_daily_drawdown_pct = float(db_settings.get("max_daily_drawdown_pct", os.getenv("MAX_DAILY_DRAWDOWN_PERCENT", "3.0")))
82
+ risk_engine.stop_loss_pct = float(db_settings.get("stop_loss_pct", os.getenv("STOP_LOSS_PERCENT", "15.0")))
83
+ risk_engine.take_profit_pct = float(db_settings.get("take_profit_pct", os.getenv("TAKE_PROFIT_PERCENT", "30.0")))
84
+
85
+ # Load historical logs from DB
86
+ terminal_logs = db.get_logs(100)
87
+ if not terminal_logs:
88
+ terminal_logs = ["SentryTheta Server initialized. Waiting for scanner cycle..."]
89
+ db.add_log(terminal_logs[0])
90
+
91
+ # Global State
92
+ state = {
93
+ "trading_mode": trading_mode,
94
+ "scan_interval": scan_interval,
95
+ "tickers": tickers,
96
+ "pending_proposal": None,
97
+ "terminal_logs": terminal_logs,
98
+ "optionable_assets": ["AAPL", "MSFT", "NVDA", "SPY", "QQQ"] # default fallback
99
+ }
100
+
101
+ # Settings Schema
102
+ class SettingsRequest(BaseModel):
103
+ trading_mode: str
104
+ scan_interval: int
105
+ tickers: List[str]
106
+ max_position_size_pct: float
107
+ max_daily_drawdown_pct: float
108
+ stop_loss_pct: float
109
+ take_profit_pct: float
110
+
111
+ # Append terminal log and broadcast
112
+ async def log_and_broadcast(message: str):
113
+ logger.info(message)
114
+ state["terminal_logs"].append(message)
115
+ if len(state["terminal_logs"]) > 100:
116
+ state["terminal_logs"].pop(0)
117
+ db.add_log(message) # Persist log to SQLite
118
+ await manager.broadcast({"type": "log", "data": message})
119
+
120
+ # REST API Endpoints
121
+ @app.get("/api/status")
122
+ async def get_status():
123
+ acc_info = alpaca.get_account_info()
124
+ positions = alpaca.get_active_positions()
125
+ return {
126
+ "account": acc_info,
127
+ "positions": positions,
128
+ "settings": {
129
+ "trading_mode": state["trading_mode"],
130
+ "scan_interval": state["scan_interval"],
131
+ "tickers": state["tickers"],
132
+ "max_position_size_pct": risk_engine.max_position_size_pct,
133
+ "max_daily_drawdown_pct": risk_engine.max_daily_drawdown_pct,
134
+ "stop_loss_pct": risk_engine.stop_loss_pct,
135
+ "take_profit_pct": risk_engine.take_profit_pct,
136
+ },
137
+ "pending_proposal": state["pending_proposal"],
138
+ "logs": state["terminal_logs"]
139
+ }
140
+
141
+ @app.get("/api/assets")
142
+ async def get_assets_endpoint():
143
+ return state.get("optionable_assets", ["AAPL", "MSFT", "NVDA", "SPY", "QQQ"])
144
+
145
+ @app.post("/api/settings")
146
+ async def update_settings(req: SettingsRequest):
147
+ if req.trading_mode not in ["copilot", "autopilot"]:
148
+ raise HTTPException(status_code=400, detail="Invalid trading mode.")
149
+
150
+ state["trading_mode"] = req.trading_mode
151
+ state["scan_interval"] = max(10, req.scan_interval) # minimum 10 seconds
152
+ state["tickers"] = [t.upper().strip() for t in req.tickers]
153
+
154
+ risk_engine.max_position_size_pct = req.max_position_size_pct
155
+ risk_engine.max_daily_drawdown_pct = req.max_daily_drawdown_pct
156
+ risk_engine.stop_loss_pct = req.stop_loss_pct
157
+ risk_engine.take_profit_pct = req.take_profit_pct
158
+
159
+ # Save settings to SQLite
160
+ db.set_setting("trading_mode", state["trading_mode"])
161
+ db.set_setting("scan_interval", state["scan_interval"])
162
+ db.set_setting("tickers", ",".join(state["tickers"]))
163
+ db.set_setting("max_position_size_pct", risk_engine.max_position_size_pct)
164
+ db.set_setting("max_daily_drawdown_pct", risk_engine.max_daily_drawdown_pct)
165
+ db.set_setting("stop_loss_pct", risk_engine.stop_loss_pct)
166
+ db.set_setting("take_profit_pct", risk_engine.take_profit_pct)
167
+
168
+ await log_and_broadcast(
169
+ f"βš™οΈ System settings updated. Mode={state['trading_mode'].upper()}, "
170
+ f"Tickers={state['tickers']}"
171
+ )
172
+
173
+ # Broadcast updated status to all clients
174
+ await broadcast_state()
175
+ return {"status": "success"}
176
+
177
+ @app.post("/api/copilot/approve")
178
+ async def approve_trade():
179
+ proposal = state["pending_proposal"]
180
+ if not proposal:
181
+ raise HTTPException(status_code=400, detail="No pending proposal to approve.")
182
+
183
+ await log_and_broadcast(f"πŸ‘ User APPROVED proposal for {proposal['symbol']}")
184
+
185
+ # Execute order
186
+ res = alpaca.execute_options_trade(
187
+ symbol=proposal["symbol"],
188
+ qty=proposal["qty"],
189
+ side=proposal["side"],
190
+ strategy_name=proposal["strategy"]
191
+ )
192
+
193
+ if res["success"]:
194
+ await log_and_broadcast(
195
+ f"βœ… [Executor] Order filled: {res['side'].upper()} {res['qty']}x {res['symbol']} "
196
+ f"at ${res.get('price', proposal['premium']):.2f}. Order ID: {res['order_id']}"
197
+ )
198
+ state["pending_proposal"] = None
199
+ await broadcast_state()
200
+ return {"status": "success", "detail": res}
201
+ else:
202
+ await log_and_broadcast(f"❌ [Executor] Order failed: {res.get('error')}")
203
+ state["pending_proposal"] = None
204
+ await broadcast_state()
205
+ raise HTTPException(status_code=500, detail=res.get("error"))
206
+
207
+ @app.post("/api/copilot/reject")
208
+ async def reject_trade():
209
+ proposal = state["pending_proposal"]
210
+ if not proposal:
211
+ raise HTTPException(status_code=400, detail="No pending proposal to reject.")
212
+
213
+ await log_and_broadcast(f"πŸ‘Ž User REJECTED proposal for {proposal['symbol']}. Clearing proposal.")
214
+ state["pending_proposal"] = None
215
+ await broadcast_state()
216
+ return {"status": "success"}
217
+
218
+ # WebSocket Handler
219
+ @app.websocket("/ws")
220
+ async def websocket_endpoint(websocket: WebSocket):
221
+ await manager.connect(websocket)
222
+ try:
223
+ # Send initial status
224
+ acc_info = alpaca.get_account_info()
225
+ positions = alpaca.get_active_positions()
226
+ await websocket.send_text(json.dumps({
227
+ "type": "init",
228
+ "data": {
229
+ "account": acc_info,
230
+ "positions": positions,
231
+ "settings": {
232
+ "trading_mode": state["trading_mode"],
233
+ "scan_interval": state["scan_interval"],
234
+ "tickers": state["tickers"],
235
+ "max_position_size_pct": risk_engine.max_position_size_pct,
236
+ "max_daily_drawdown_pct": risk_engine.max_daily_drawdown_pct,
237
+ "stop_loss_pct": risk_engine.stop_loss_pct,
238
+ "take_profit_pct": risk_engine.take_profit_pct,
239
+ },
240
+ "pending_proposal": state["pending_proposal"],
241
+ "logs": state["terminal_logs"]
242
+ }
243
+ }))
244
+
245
+ while True:
246
+ # Keep connection alive
247
+ await websocket.receive_text()
248
+ except WebSocketDisconnect:
249
+ manager.disconnect(websocket)
250
+
251
+ async def broadcast_state():
252
+ """Broadcast current portfolio state, positions and settings to all websockets."""
253
+ try:
254
+ acc_info = alpaca.get_account_info()
255
+ positions = alpaca.get_active_positions()
256
+ await manager.broadcast({
257
+ "type": "status_update",
258
+ "data": {
259
+ "account": acc_info,
260
+ "positions": positions,
261
+ "pending_proposal": state["pending_proposal"]
262
+ }
263
+ })
264
+ except Exception as e:
265
+ logger.error(f"Error broadcasting state: {e}")
266
+
267
+ # Background Scanner Loop
268
+ async def scan_market_loop():
269
+ logger.info("Starting agent scanner background loop...")
270
+ while True:
271
+ try:
272
+ # Run scan cycle
273
+ proposals, logs = agent.run_agent_scan(state["tickers"])
274
+
275
+ # Send logs to UI
276
+ for log in logs:
277
+ await log_and_broadcast(log)
278
+ await asyncio.sleep(0.1) # brief pause to simulate real-time printing
279
+
280
+ if proposals:
281
+ proposal = proposals[0] # Handle first approved proposal
282
+
283
+ if state["trading_mode"] == "autopilot":
284
+ # Autonomous execution
285
+ await log_and_broadcast(f"πŸ€– [Executor] Autopilot mode enabled. Executing proposal autonomously...")
286
+ res = alpaca.execute_options_trade(
287
+ symbol=proposal["symbol"],
288
+ qty=proposal["qty"],
289
+ side=proposal["side"],
290
+ strategy_name=proposal["strategy"]
291
+ )
292
+ if res["success"]:
293
+ await log_and_broadcast(
294
+ f"βœ… [Executor] Order filled: {res['side'].upper()} {res['qty']}x {res['symbol']} "
295
+ f"at ${res.get('price', proposal['premium']):.2f}. Order ID: {res['order_id']}"
296
+ )
297
+ else:
298
+ await log_and_broadcast(f"❌ [Executor] Autopilot order execution failed: {res.get('error')}")
299
+ else:
300
+ # Copilot mode (Queue for approval)
301
+ await log_and_broadcast(f"πŸ”” [Strategist] Proposed trade added to Copilot Queue. Awaiting approval...")
302
+ state["pending_proposal"] = proposal
303
+ # Broadcast the trade proposal to trigger UI alerts
304
+ await manager.broadcast({
305
+ "type": "proposal",
306
+ "data": proposal
307
+ })
308
+
309
+ # Periodic P&L/Status updates between scans
310
+ await broadcast_state()
311
+
312
+ except Exception as e:
313
+ logger.error(f"Error in background scanner cycle: {e}")
314
+
315
+ # Sleep for specified interval
316
+ await asyncio.sleep(state["scan_interval"])
317
+
318
+ async def cache_optionable_assets_task():
319
+ logger.info("Background caching of optionable assets started...")
320
+ if alpaca.is_mock:
321
+ # Default mock popular optionable tickers
322
+ state["optionable_assets"] = [
323
+ "AAPL", "MSFT", "NVDA", "AMD", "TSLA", "AMZN", "META", "GOOGL", "NFLX",
324
+ "SPY", "QQQ", "IWM", "DIS", "COIN", "PLTR", "JPM", "WMT", "V", "MA", "UNH"
325
+ ]
326
+ logger.info(f"Loaded {len(state['optionable_assets'])} mock optionable tickers.")
327
+ return
328
+
329
+ try:
330
+ # Run synchronous SDK call in executor to avoid blocking the asyncio event loop!
331
+ loop = asyncio.get_event_loop()
332
+ assets = await loop.run_in_executor(None, alpaca.trading_client.get_all_assets)
333
+
334
+ opt_symbols = [
335
+ a.symbol for a in assets
336
+ if a.tradable and a.attributes and "has_options" in a.attributes
337
+ ]
338
+
339
+ if opt_symbols:
340
+ state["optionable_assets"] = sorted(opt_symbols)
341
+ logger.info(f"Successfully cached {len(opt_symbols)} optionable assets from Alpaca.")
342
+ else:
343
+ logger.warning("Alpaca returned no optionable assets. Using defaults.")
344
+ except Exception as e:
345
+ logger.error(f"Failed to cache Alpaca optionable assets: {e}. Using defaults.")
346
+
347
+ # Start background loop on startup
348
+ @app.on_event("startup")
349
+ async def startup_event():
350
+ asyncio.create_task(cache_optionable_assets_task())
351
+ asyncio.create_task(scan_market_loop())
352
+
353
+ # Serve static frontend files
354
+ # Front-end folder must contain index.html, style.css, app.js
355
+ frontend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "frontend"))
356
+
357
+ if os.path.exists(frontend_dir):
358
+ logger.info(f"Serving static frontend files from: {frontend_dir}")
359
+ # Route for fallback/index.html
360
+ @app.get("/")
361
+ async def read_index():
362
+ return FileResponse(os.path.join(frontend_dir, "index.html"))
363
+
364
+ app.mount("/", StaticFiles(directory=frontend_dir), name="static")
365
+ else:
366
+ logger.error(f"Frontend directory '{frontend_dir}' not found! Backend only mode.")