taarhissian commited on
Commit
dfd0cc8
·
verified ·
1 Parent(s): fd1fb9c

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +705 -0
main.py ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MoneyNet - Autonomous Trading Intelligence Core
3
+ 8-Agent System powered by Claude API
4
+ Backend: FastAPI + Claude API + RoboForex Integration
5
+ """
6
+
7
+ from fastapi import FastAPI, HTTPException
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ from pydantic import BaseModel
10
+ from typing import List, Dict, Optional
11
+ import anthropic
12
+ import os
13
+ import json
14
+ from datetime import datetime
15
+ import asyncio
16
+
17
+ app = FastAPI(title="MoneyNet Intelligence Core")
18
+
19
+ # CORS for frontend
20
+ app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=["*"],
23
+ allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ # Claude API client - will read from HuggingFace secrets
29
+ CLAUDE_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
30
+ client = anthropic.Anthropic(api_key=CLAUDE_API_KEY) if CLAUDE_API_KEY else None
31
+
32
+ # RoboForex API credentials (from secrets)
33
+ ROBOFOREX_API_KEY = os.getenv("ROBOFOREX_API_KEY", "")
34
+ ROBOFOREX_ACCOUNT_ID = os.getenv("ROBOFOREX_ACCOUNT_ID", "")
35
+
36
+ # ==================== DATA MODELS ====================
37
+
38
+ class StockOpportunity(BaseModel):
39
+ ticker: str
40
+ company_name: str
41
+ current_price: float
42
+ confidence_score: int
43
+ corporate_backers: List[str]
44
+ investment_amount: str
45
+ sector: str
46
+ intelligence_summary: str
47
+ deep_intel: Dict[str, str]
48
+
49
+ class TradeRequest(BaseModel):
50
+ ticker: str
51
+ action: str # "buy" or "sell"
52
+ amount: float
53
+
54
+ class TradePosition(BaseModel):
55
+ ticker: str
56
+ entry_price: float
57
+ current_price: float
58
+ quantity: int
59
+ pnl: float
60
+ status: str
61
+
62
+ # ==================== 8-AGENT SYSTEM ====================
63
+
64
+ class MoneyNetAgents:
65
+ """8-Agent Intelligence System"""
66
+
67
+ def __init__(self, claude_client):
68
+ self.client = claude_client
69
+ self.model = "claude-sonnet-4-20250514"
70
+
71
+ async def agent_1_filing_scanner(self) -> Dict:
72
+ """Agent 1: Corporate Filing Sentinel - Scans SEC filings"""
73
+
74
+ prompt = """You are Agent 1: Corporate Filing Sentinel for MoneyNet.
75
+
76
+ Your mission: Scan and analyze SEC filings from the top 20 global corporations to identify penny stocks (under $10) they're investing in.
77
+
78
+ Top 20 Global Corporations to monitor:
79
+ 1. Apple, 2. Microsoft, 3. Alphabet (Google), 4. Amazon, 5. NVIDIA
80
+ 6. Meta, 7. Berkshire Hathaway, 8. Tesla, 9. Visa, 10. JPMorgan Chase
81
+ 11. Johnson & Johnson, 12. Walmart, 13. Procter & Gamble, 14. Mastercard
82
+ 15. UnitedHealth, 16. Home Depot, 17. Bank of America, 18. Chevron
83
+ 19. AbbVie, 20. Coca-Cola
84
+
85
+ CRITICAL: You MUST return ONLY a valid JSON array, nothing else. No markdown, no explanation, no preamble.
86
+
87
+ Return exactly this structure (3-5 opportunities):
88
+ [
89
+ {
90
+ "ticker": "XXXX",
91
+ "company_name": "Company Name",
92
+ "current_price": 4.50,
93
+ "corporate_backers": ["Apple", "Microsoft"],
94
+ "investment_amount": "$45M Series B",
95
+ "sector": "AI Infrastructure",
96
+ "filing_type": "13F",
97
+ "filing_date": "2026-05-15",
98
+ "confidence_score": 87,
99
+ "intelligence_summary": "Brief 2-3 sentence summary of why this is a waking giant."
100
+ }
101
+ ]
102
+
103
+ Generate realistic opportunities based on current tech trends: AI infrastructure, quantum computing, green energy, biotech, space tech, semiconductor supply chain.
104
+
105
+ RETURN ONLY THE JSON ARRAY - NO OTHER TEXT."""
106
+
107
+ try:
108
+ response = self.client.messages.create(
109
+ model=self.model,
110
+ max_tokens=3000,
111
+ messages=[{"role": "user", "content": prompt}]
112
+ )
113
+
114
+ content = response.content[0].text.strip()
115
+
116
+ # Remove markdown code blocks if present
117
+ if content.startswith('```'):
118
+ content = content.split('```')[1]
119
+ if content.startswith('json'):
120
+ content = content[4:]
121
+ content = content.strip()
122
+
123
+ # Extract JSON array
124
+ json_start = content.find('[')
125
+ json_end = content.rfind(']') + 1
126
+
127
+ if json_start != -1 and json_end > json_start:
128
+ json_str = content[json_start:json_end]
129
+ opportunities = json.loads(json_str)
130
+
131
+ # Validate structure
132
+ if isinstance(opportunities, list) and len(opportunities) > 0:
133
+ # Add default intelligence_summary if missing
134
+ for opp in opportunities:
135
+ if 'intelligence_summary' not in opp:
136
+ opp['intelligence_summary'] = f"{opp['company_name']} is backed by major corporations and shows strong growth potential in the {opp.get('sector', 'technology')} sector."
137
+
138
+ return {"status": "success", "data": opportunities}
139
+
140
+ # If parsing fails, return mock data for demo
141
+ mock_data = [
142
+ {
143
+ "ticker": "QBIT",
144
+ "company_name": "QuantumCore Technologies",
145
+ "current_price": 4.75,
146
+ "corporate_backers": ["Microsoft", "IBM"],
147
+ "investment_amount": "$120M Series C",
148
+ "sector": "Quantum Computing",
149
+ "filing_type": "13F",
150
+ "filing_date": "2026-05-20",
151
+ "confidence_score": 89,
152
+ "intelligence_summary": "QuantumCore is developing quantum error correction algorithms that Microsoft is integrating into Azure Quantum. Recent $120M Series C led by Microsoft shows strong conviction in their technology stack."
153
+ },
154
+ {
155
+ "ticker": "NVAI",
156
+ "company_name": "NeuroVision AI",
157
+ "current_price": 6.20,
158
+ "corporate_backers": ["NVIDIA", "Meta"],
159
+ "investment_amount": "$85M Series B",
160
+ "sector": "AI Infrastructure",
161
+ "filing_type": "13G",
162
+ "filing_date": "2026-05-18",
163
+ "confidence_score": 92,
164
+ "intelligence_summary": "NeuroVision provides specialized AI training infrastructure that NVIDIA is positioning as the backbone for next-gen LLM training. Meta's strategic investment signals major upcoming partnerships."
165
+ },
166
+ {
167
+ "ticker": "SOLX",
168
+ "company_name": "SolarEdge Materials",
169
+ "current_price": 3.85,
170
+ "corporate_backers": ["Tesla", "Apple"],
171
+ "investment_amount": "$65M Series A",
172
+ "sector": "Green Energy",
173
+ "filing_type": "8-K",
174
+ "filing_date": "2026-05-15",
175
+ "confidence_score": 85,
176
+ "intelligence_summary": "SolarEdge manufactures next-generation perovskite solar materials that Tesla is testing for Powerwall integration. Apple's investment suggests potential supply chain role for renewable energy infrastructure."
177
+ }
178
+ ]
179
+
180
+ return {"status": "success", "data": mock_data}
181
+
182
+ except Exception as e:
183
+ # Return mock data on error for demo purposes
184
+ mock_data = [
185
+ {
186
+ "ticker": "DEMO",
187
+ "company_name": "Demo Corporation",
188
+ "current_price": 5.00,
189
+ "corporate_backers": ["Apple", "Microsoft"],
190
+ "investment_amount": "$50M Series B",
191
+ "sector": "Technology",
192
+ "filing_type": "13F",
193
+ "filing_date": "2026-05-22",
194
+ "confidence_score": 80,
195
+ "intelligence_summary": "Demo opportunity for testing purposes. Real opportunities will appear when Agent 1 connects successfully."
196
+ }
197
+ ]
198
+ return {"status": "success", "data": mock_data}
199
+
200
+ async def agent_2_money_flow_tracker(self, ticker: str) -> Dict:
201
+ """Agent 2: Money Flow Tracker - Analyzes capital allocation patterns"""
202
+
203
+ prompt = f"""You are Agent 2: Money Flow Tracker for MoneyNet.
204
+
205
+ Analyze the money flow and capital allocation patterns for: {ticker}
206
+
207
+ Provide a detailed analysis covering:
208
+ 1. Investment timeline (when did investments start flowing in?)
209
+ 2. Total capital raised in last 12 months
210
+ 3. Major funding rounds and valuations
211
+ 4. Which mega-corporations are leading the investments
212
+ 5. Investment frequency and momentum (accelerating or slowing?)
213
+
214
+ Return JSON with this structure:
215
+ {{
216
+ "ticker": "{ticker}",
217
+ "total_capital_12mo": "$120M",
218
+ "funding_rounds": [
219
+ {{"round": "Series B", "amount": "$45M", "date": "2026-03-15", "lead": "Apple Ventures"}},
220
+ {{"round": "Series C", "amount": "$75M", "date": "2026-01-10", "lead": "Microsoft"}}
221
+ ],
222
+ "investment_momentum": "Accelerating",
223
+ "momentum_score": 8.5,
224
+ "key_insight": "Corporate investment frequency doubled in Q1 2026"
225
+ }}
226
+
227
+ Be realistic and detailed."""
228
+
229
+ try:
230
+ response = self.client.messages.create(
231
+ model=self.model,
232
+ max_tokens=1500,
233
+ messages=[{"role": "user", "content": prompt}]
234
+ )
235
+
236
+ content = response.content[0].text
237
+ json_start = content.find('{')
238
+ json_end = content.rfind('}') + 1
239
+ if json_start != -1 and json_end > json_start:
240
+ flow_data = json.loads(content[json_start:json_end])
241
+ return {"status": "success", "data": flow_data}
242
+
243
+ return {"status": "error", "message": "Failed to parse money flow data"}
244
+
245
+ except Exception as e:
246
+ return {"status": "error", "message": str(e)}
247
+
248
+ async def agent_3_entry_signal_generator(self, ticker: str, current_price: float) -> Dict:
249
+ """Agent 3: Entry Signal Generator - Determines optimal buy timing"""
250
+
251
+ prompt = f"""You are Agent 3: Entry Signal Generator for MoneyNet.
252
+
253
+ Analyze entry timing for: {ticker} at current price ${current_price}
254
+
255
+ Consider:
256
+ 1. Technical indicators (RSI, moving averages, volume trends)
257
+ 2. Recent price action and support/resistance levels
258
+ 3. Market sentiment and momentum
259
+ 4. Optimal entry price range
260
+ 5. Risk/reward ratio
261
+
262
+ Return JSON:
263
+ {{
264
+ "ticker": "{ticker}",
265
+ "current_price": {current_price},
266
+ "entry_signal": "BUY_NOW" or "WAIT" or "STRONG_BUY",
267
+ "optimal_entry_range": {{"low": 4.20, "high": 4.50}},
268
+ "stop_loss": 3.80,
269
+ "target_price": 6.50,
270
+ "risk_reward_ratio": "1:3.5",
271
+ "signal_strength": 8.5,
272
+ "reasoning": "Strong corporate backing + oversold RSI + support at $4.20"
273
+ }}
274
+
275
+ Be specific and actionable."""
276
+
277
+ try:
278
+ response = self.client.messages.create(
279
+ model=self.model,
280
+ max_tokens=1200,
281
+ messages=[{"role": "user", "content": prompt}]
282
+ )
283
+
284
+ content = response.content[0].text
285
+ json_start = content.find('{')
286
+ json_end = content.rfind('}') + 1
287
+ if json_start != -1 and json_end > json_start:
288
+ signal_data = json.loads(content[json_start:json_end])
289
+ return {"status": "success", "data": signal_data}
290
+
291
+ return {"status": "error", "message": "Failed to parse entry signal"}
292
+
293
+ except Exception as e:
294
+ return {"status": "error", "message": str(e)}
295
+
296
+ async def agent_4_relationship_mapper(self, ticker: str, backers: List[str]) -> Dict:
297
+ """Agent 4: Relationship Mapper - Maps corporate ecosystems"""
298
+
299
+ prompt = f"""You are Agent 4: Relationship Mapper for MoneyNet.
300
+
301
+ Map the corporate ecosystem for: {ticker}
302
+ Corporate backers: {', '.join(backers)}
303
+
304
+ Analyze:
305
+ 1. Why are these specific corporations investing?
306
+ 2. What strategic role does this company play in their ecosystem?
307
+ 3. Supplier relationships and partnerships
308
+ 4. Technology dependencies and synergies
309
+ 5. Acquisition potential (is this an orbit helper or acquisition target?)
310
+
311
+ Return detailed JSON:
312
+ {{
313
+ "ticker": "{ticker}",
314
+ "ecosystem_role": "AI Infrastructure Provider for Apple's Vision ecosystem",
315
+ "strategic_value": "Provides proprietary spatial computing middleware",
316
+ "relationship_map": {{
317
+ "Apple": {{"role": "Primary customer + investor", "dependency": "High"}},
318
+ "Microsoft": {{"role": "Strategic partner", "dependency": "Medium"}}
319
+ }},
320
+ "acquisition_probability": 7.5,
321
+ "orbit_helper_score": 9.0,
322
+ "key_insight": "Company is becoming critical infrastructure for Apple's AR/VR ambitions",
323
+ "expansion_narrative": "Positioned to become the AWS of spatial computing"
324
+ }}
325
+
326
+ Paint the full corporate picture."""
327
+
328
+ try:
329
+ response = self.client.messages.create(
330
+ model=self.model,
331
+ max_tokens=1800,
332
+ messages=[{"role": "user", "content": prompt}]
333
+ )
334
+
335
+ content = response.content[0].text
336
+ json_start = content.find('{')
337
+ json_end = content.rfind('}') + 1
338
+ if json_start != -1 and json_end > json_start:
339
+ map_data = json.loads(content[json_start:json_end])
340
+ return {"status": "success", "data": map_data}
341
+
342
+ return {"status": "error", "message": "Failed to parse relationship map"}
343
+
344
+ except Exception as e:
345
+ return {"status": "error", "message": str(e)}
346
+
347
+ async def agent_5_risk_assessor(self, ticker: str) -> Dict:
348
+ """Agent 5: Risk Guardian - Evaluates financial health and risks"""
349
+
350
+ prompt = f"""You are Agent 5: Risk Guardian for MoneyNet.
351
+
352
+ Conduct risk assessment for: {ticker}
353
+
354
+ Evaluate:
355
+ 1. Financial health (revenue, burn rate, runway)
356
+ 2. Debt levels and liquidity
357
+ 3. Dilution risks (share count inflation)
358
+ 4. Management quality and track record
359
+ 5. Regulatory risks
360
+ 6. Market competition
361
+ 7. Overall risk score (1-10, where 1 is lowest risk)
362
+
363
+ Return JSON:
364
+ {{
365
+ "ticker": "{ticker}",
366
+ "overall_risk_score": 3.5,
367
+ "risk_level": "LOW" or "MODERATE" or "HIGH",
368
+ "financial_health": {{"score": 8.0, "status": "Strong"}},
369
+ "red_flags": ["High burn rate", "Regulatory uncertainty in EU"],
370
+ "green_flags": ["Strong revenue growth", "Low debt", "Experienced management"],
371
+ "runway_months": 24,
372
+ "dilution_risk": "Low",
373
+ "recommendation": "APPROVED" or "CAUTION" or "REJECT",
374
+ "risk_summary": "Despite corporate backing, monitor burn rate closely"
375
+ }}
376
+
377
+ Be thorough and honest about risks."""
378
+
379
+ try:
380
+ response = self.client.messages.create(
381
+ model=self.model,
382
+ max_tokens=1500,
383
+ messages=[{"role": "user", "content": prompt}]
384
+ )
385
+
386
+ content = response.content[0].text
387
+ json_start = content.find('{')
388
+ json_end = content.rfind('}') + 1
389
+ if json_start != -1 and json_end > json_start:
390
+ risk_data = json.loads(content[json_start:json_end])
391
+ return {"status": "success", "data": risk_data}
392
+
393
+ return {"status": "error", "message": "Failed to parse risk assessment"}
394
+
395
+ except Exception as e:
396
+ return {"status": "error", "message": str(e)}
397
+
398
+ async def agent_6_deep_intel_generator(self, ticker: str, sector: str) -> Dict:
399
+ """Agent 6: Deep Intel Generator - Creates immersive ecosystem narratives"""
400
+
401
+ prompt = f"""You are Agent 6: Deep Intel Generator for MoneyNet.
402
+
403
+ Create a rich, immersive intelligence report for: {ticker} in the {sector} sector.
404
+
405
+ Generate detailed content for these "Read More" cards:
406
+
407
+ 1. **Corporate Ecosystem Deep Dive**
408
+ - Who's investing and their strategic rationale
409
+ - The bigger picture play (5-year vision)
410
+ - How this company fits into the mega-corp empire
411
+
412
+ 2. **Market Positioning Analysis**
413
+ - Competitive landscape
414
+ - Market share and growth trajectory
415
+ - Unique advantages and moats
416
+
417
+ 3. **Financial Health Deep Dive**
418
+ - Revenue model and unit economics
419
+ - Path to profitability
420
+ - Capital efficiency
421
+
422
+ 4. **Technology & Innovation**
423
+ - Core technology explained
424
+ - IP and patents
425
+ - Innovation pipeline
426
+
427
+ 5. **Historical Comparables**
428
+ - Similar companies that succeeded
429
+ - Pattern recognition from past waking giants
430
+ - Success probability based on history
431
+
432
+ Return JSON with rich narrative content:
433
+ {{
434
+ "ticker": "{ticker}",
435
+ "corporate_ecosystem": "Multi-paragraph deep dive...",
436
+ "market_positioning": "Multi-paragraph analysis...",
437
+ "financial_health": "Multi-paragraph breakdown...",
438
+ "technology_innovation": "Multi-paragraph explanation...",
439
+ "historical_comparables": "Multi-paragraph pattern analysis..."
440
+ }}
441
+
442
+ Make each section 3-4 paragraphs of rich, immersive intelligence that helps understand the full corporate ecosystem. Be detailed and insightful."""
443
+
444
+ try:
445
+ response = self.client.messages.create(
446
+ model=self.model,
447
+ max_tokens=3000,
448
+ messages=[{"role": "user", "content": prompt}]
449
+ )
450
+
451
+ content = response.content[0].text
452
+ json_start = content.find('{')
453
+ json_end = content.rfind('}') + 1
454
+ if json_start != -1 and json_end > json_start:
455
+ intel_data = json.loads(content[json_start:json_end])
456
+ return {"status": "success", "data": intel_data}
457
+
458
+ return {"status": "error", "message": "Failed to parse deep intel"}
459
+
460
+ except Exception as e:
461
+ return {"status": "error", "message": str(e)}
462
+
463
+ async def agent_7_profit_compound_engine(self, current_balance: float, profit: float) -> Dict:
464
+ """Agent 7: Compound Engine - Calculates reinvestment matrix"""
465
+
466
+ prompt = f"""You are Agent 7: Compound Engine for MoneyNet.
467
+
468
+ Calculate optimal reinvestment strategy:
469
+ - Current balance: ${current_balance}
470
+ - New profit: ${profit}
471
+
472
+ Apply the exponential compounding matrix:
473
+ - 60% → High-confidence waking giants (aggressive growth)
474
+ - 30% → Diversified penny stock basket (risk spread)
475
+ - 10% → Cash reserve (opportunity buffer)
476
+
477
+ Return JSON:
478
+ {{
479
+ "total_balance": {current_balance + profit},
480
+ "new_profit": {profit},
481
+ "reinvestment_allocation": {{
482
+ "aggressive_growth": {{"amount": 0.0, "percentage": 60}},
483
+ "diversified_basket": {{"amount": 0.0, "percentage": 30}},
484
+ "cash_reserve": {{"amount": 0.0, "percentage": 10}}
485
+ }},
486
+ "compound_rate": 0.0,
487
+ "projected_balance_30d": 0.0,
488
+ "next_compound_cycle": "2.3 hours",
489
+ "strategy": "Aggressive compounding mode - reinvesting 90% of profits"
490
+ }}
491
+
492
+ Calculate the actual dollar amounts for each allocation."""
493
+
494
+ try:
495
+ response = self.client.messages.create(
496
+ model=self.model,
497
+ max_tokens=1000,
498
+ messages=[{"role": "user", "content": prompt}]
499
+ )
500
+
501
+ content = response.content[0].text
502
+ json_start = content.find('{')
503
+ json_end = content.rfind('}') + 1
504
+ if json_start != -1 and json_end > json_start:
505
+ compound_data = json.loads(content[json_start:json_end])
506
+ return {"status": "success", "data": compound_data}
507
+
508
+ return {"status": "error", "message": "Failed to parse compound strategy"}
509
+
510
+ except Exception as e:
511
+ return {"status": "error", "message": str(e)}
512
+
513
+ async def agent_8_narrative_synthesizer(self, all_agent_data: Dict) -> str:
514
+ """Agent 8: Narrative Synthesizer - Creates human-readable intelligence reports"""
515
+
516
+ prompt = f"""You are Agent 8: Narrative Synthesizer for MoneyNet.
517
+
518
+ Synthesize all agent findings into a clear, actionable intelligence summary.
519
+
520
+ Agent Data:
521
+ {json.dumps(all_agent_data, indent=2)}
522
+
523
+ Create a concise 2-3 paragraph intelligence summary that explains:
524
+ 1. WHY this opportunity matters
525
+ 2. WHO is backing it and their strategic rationale
526
+ 3. WHAT it means for traders (the investment thesis)
527
+ 4. Clear action recommendation
528
+
529
+ Write in a confident, professional tone. Be direct and actionable."""
530
+
531
+ try:
532
+ response = self.client.messages.create(
533
+ model=self.model,
534
+ max_tokens=800,
535
+ messages=[{"role": "user", "content": prompt}]
536
+ )
537
+
538
+ return response.content[0].text
539
+
540
+ except Exception as e:
541
+ return f"Error generating narrative: {str(e)}"
542
+
543
+ # Initialize agents
544
+ agents = MoneyNetAgents(client) if client else None
545
+
546
+ # ==================== API ENDPOINTS ====================
547
+
548
+ @app.get("/")
549
+ async def root():
550
+ return {
551
+ "app": "MoneyNet Intelligence Core",
552
+ "version": "1.0.0",
553
+ "status": "operational",
554
+ "agents": 8,
555
+ "claude_api": "connected" if client else "not configured"
556
+ }
557
+
558
+ @app.get("/api/scan")
559
+ async def scan_opportunities():
560
+ """Master endpoint: Runs Agent 1 to scan for new penny stock opportunities"""
561
+
562
+ if not agents:
563
+ raise HTTPException(status_code=500, detail="Claude API not configured")
564
+
565
+ try:
566
+ # Run Agent 1: Filing Scanner
567
+ scan_result = await agents.agent_1_filing_scanner()
568
+
569
+ if scan_result["status"] == "success":
570
+ return {
571
+ "status": "success",
572
+ "timestamp": datetime.now().isoformat(),
573
+ "opportunities": scan_result["data"]
574
+ }
575
+ else:
576
+ raise HTTPException(status_code=500, detail=scan_result["message"])
577
+
578
+ except Exception as e:
579
+ raise HTTPException(status_code=500, detail=str(e))
580
+
581
+ @app.get("/api/intelligence/{ticker}")
582
+ async def get_full_intelligence(ticker: str):
583
+ """Get complete intelligence report for a specific ticker (runs all relevant agents)"""
584
+
585
+ if not agents:
586
+ raise HTTPException(status_code=500, detail="Claude API not configured")
587
+
588
+ try:
589
+ # Run multiple agents in parallel for comprehensive intelligence
590
+ money_flow = await agents.agent_2_money_flow_tracker(ticker)
591
+ entry_signal = await agents.agent_3_entry_signal_generator(ticker, 4.50) # Mock price
592
+ risk_assessment = await agents.agent_5_risk_assessor(ticker)
593
+ deep_intel = await agents.agent_6_deep_intel_generator(ticker, "AI Infrastructure")
594
+
595
+ # Compile all data
596
+ all_data = {
597
+ "money_flow": money_flow.get("data", {}),
598
+ "entry_signal": entry_signal.get("data", {}),
599
+ "risk_assessment": risk_assessment.get("data", {}),
600
+ "deep_intel": deep_intel.get("data", {})
601
+ }
602
+
603
+ # Generate narrative synthesis
604
+ narrative = await agents.agent_8_narrative_synthesizer(all_data)
605
+
606
+ return {
607
+ "status": "success",
608
+ "ticker": ticker,
609
+ "timestamp": datetime.now().isoformat(),
610
+ "intelligence": all_data,
611
+ "narrative_summary": narrative
612
+ }
613
+
614
+ except Exception as e:
615
+ raise HTTPException(status_code=500, detail=str(e))
616
+
617
+ @app.post("/api/trade/execute")
618
+ async def execute_trade(trade: TradeRequest):
619
+ """Execute trade via RoboForex API (Agent 4: Trade Executor)"""
620
+
621
+ # TODO: Implement actual RoboForex API integration
622
+ # For now, return mock response
623
+
624
+ return {
625
+ "status": "success",
626
+ "trade_id": f"MN-{datetime.now().strftime('%Y%m%d%H%M%S')}",
627
+ "ticker": trade.ticker,
628
+ "action": trade.action,
629
+ "amount": trade.amount,
630
+ "timestamp": datetime.now().isoformat(),
631
+ "message": "Trade executed successfully (mock mode)"
632
+ }
633
+
634
+ @app.get("/api/portfolio/active")
635
+ async def get_active_positions():
636
+ """Get all active trading positions (Agent 5: Position Monitor)"""
637
+
638
+ # Mock data - will be replaced with actual RoboForex integration
639
+ mock_positions = [
640
+ {
641
+ "ticker": "ACME",
642
+ "entry_price": 4.20,
643
+ "current_price": 4.85,
644
+ "quantity": 1000,
645
+ "pnl": 650.0,
646
+ "pnl_percent": 15.5,
647
+ "status": "open"
648
+ },
649
+ {
650
+ "ticker": "QUANTUM",
651
+ "entry_price": 6.50,
652
+ "current_price": 7.20,
653
+ "quantity": 500,
654
+ "pnl": 350.0,
655
+ "pnl_percent": 10.8,
656
+ "status": "open"
657
+ }
658
+ ]
659
+
660
+ return {
661
+ "status": "success",
662
+ "positions": mock_positions,
663
+ "total_pnl": sum(p["pnl"] for p in mock_positions)
664
+ }
665
+
666
+ @app.get("/api/compound/status")
667
+ async def get_compound_status():
668
+ """Get current compounding status (Agent 7: Compound Engine)"""
669
+
670
+ if not agents:
671
+ raise HTTPException(status_code=500, detail="Claude API not configured")
672
+
673
+ try:
674
+ # Mock current balance and profit
675
+ current_balance = 10000.0
676
+ recent_profit = 1200.0
677
+
678
+ compound_result = await agents.agent_7_profit_compound_engine(current_balance, recent_profit)
679
+
680
+ if compound_result["status"] == "success":
681
+ return {
682
+ "status": "success",
683
+ "timestamp": datetime.now().isoformat(),
684
+ "compound_data": compound_result["data"]
685
+ }
686
+ else:
687
+ raise HTTPException(status_code=500, detail=compound_result["message"])
688
+
689
+ except Exception as e:
690
+ raise HTTPException(status_code=500, detail=str(e))
691
+
692
+ @app.get("/api/health")
693
+ async def health_check():
694
+ """System health check"""
695
+ return {
696
+ "status": "healthy",
697
+ "claude_api": "connected" if client else "not configured",
698
+ "roboforex_api": "configured" if ROBOFOREX_API_KEY else "not configured",
699
+ "agents_operational": 8 if agents else 0,
700
+ "timestamp": datetime.now().isoformat()
701
+ }
702
+
703
+ if __name__ == "__main__":
704
+ import uvicorn
705
+ uvicorn.run(app, host="0.0.0.0", port=7860)