"Precision in every trade. Intelligence in every decision."
An institutional-grade AI trading assistant that combines real-time market analysis, behavioral coaching, and automated fact-checking to help retail traders make informed decisions.
Retail traders face a "Triple Threat" disadvantage:
- Information Asymmetry: Breaking news is priced in before retail traders can react
- Cognitive Bias: Emotional decisions (FOMO, revenge trading) destroy carefully planned strategies
- Verification Gap: Distinguishing real market-moving news from noise is computationally expensive
An AI-Powered Event-Driven System that:
- Detects statistical price anomalies in real-time
- Correlates news events with price movements
- Fact-checks all claims against multiple independent sources
- Provides personalized behavioral coaching based on your trading patterns
- Generates verified, ready-to-share market analysis content
- Remembers past conversations for contextual, personalized advice
flowchart TB
subgraph Frontend["Frontend — User Portal"]
Trade[Trade]
ChatUI[Chat]
Newsletter[Newsletter]
SocialContent[Social Content]
end
subgraph Backend[API Gateway - FastAPI]
REST[REST Endpoints & Routers]
WS[WebSocket Manager<br/>Real-time Events]
BG[Background Tasks]
ChatModule[Chat Module]
end
subgraph AI[LangGraph AI Pipeline]
NodeA[Node A: Anomaly Detection]
NodeB[Node B: News Correlation]
NodeC[Node C: Behavioral Coaching]
NodeD[Node D: Content Generator]
NodeE[Node E: Fact Checker]
NodeA --> NodeB --> NodeC --> NodeD --> NodeE
NodeE -.->|retry if failed| NodeD
end
subgraph Tools[FastMCP Tool Server]
MarketData[Market Data Tools<br/>Finnhub, Alpha Vantage, yfinance]
NewsTools[News Tools<br/>NewsData.io, MediaStack]
UserData[User Pattern Analysis]
ProfileUpdate[Profile Update]
MemoryUpdate[Memory Update]
end
subgraph Data[Supabase Database]
Tables[8 Tables:<br/>users, trades, metrics,<br/>events, newsletters, drafts]
end
subgraph External[External AI Services]
Gemini[Gemini 2.0 Flash]
GeminiImage[Gemini 3 Pro Image]
Mem0[Mem0 Memory Platform]
Tavily[Tavily Search]
end
Frontend <-->|REST + WebSocket| Backend
WS -->|Real-time Events| BG
BG --> AI
REST --> Data
ChatModule -->|MCP Protocol| Tools
AI <-->|MCP Protocol| Tools
AI --> Gemini
AI --> Mem0
NodeE --> Tavily
Backend --> GeminiImage
Tools --> Data
Our LangGraph pipeline processes market events through 5 specialized nodes with a fact-checking retry loop:
-
Node A: Anomaly Detection
- Fetches historical price data (5-day window)
- Computes Z-scores to detect statistical anomalies (threshold: |Z| > 2.0)
- Routes: If anomaly → continue, else → END
-
Node B: News Correlation
- Searches market-moving news (7-day window)
- Scores correlation using 3-layer algorithm (temporal, relevance, magnitude)
- Uses Gemini to generate AI justification (newsletter summary)
-
Node C: Behavioral Coaching
- Queries user's trading history and behavioral metrics
- Searches Mem0 for past coaching history
- Generates personalized risk assessment and coaching advice
- Stores coaching to Mem0 for future reference
-
Node D: Content Generator
- Fetches deep article analysis
- Generates social media posts in 3 personas (Buffett, Trump, Burry)
- Creates both X/Twitter (≤280 chars) and LinkedIn (2-3 paragraphs) versions
- Incorporates correction prompts if retrying after fact-check failure
-
Node E: Fact Checker 🔒
- Claim Extraction: Uses Gemini to extract verifiable claims (prices, percentages, news events)
- Price Verification: Validates against Finnhub real-time quotes (±1% tolerance)
- News Verification: Validates against Tavily Search (requires 2+ independent sources)
- Retry Logic: If claims fail, generates correction prompt and loops back to Node D (max 3 attempts)
- Human Review: After 3 failed attempts, flags content for manual review
Real-time personalized newsletters delivered when market anomalies are detected:
- Market Event Detection: Monitors for price drops, spikes, and volume surges
- Automated Analysis: Runs full LangGraph pipeline for each event
- Personalized Content: Each user receives the same market analysis with personalized coaching based on their trading patterns
- Real-Time Delivery: WebSocket updates push new newsletters instantly
- Fact-Checked: All content verified before delivery with validation status badges
Contextual coaching conversations with persistent memory:
- Live Market Tools: Ask about stock prices, news sentiment, crypto data
- Behavioral Context: AI references your trading history and patterns
- Cross-Session Memory: Mem0 integration remembers past conversations
- Tool Transparency: See exactly which tools the AI calls and their results
- Newsletter Integration: Click "Chat with AI" from any newsletter event to dive deeper
Enterprise-grade workflow for social media content:
- Multi-Platform: Generate for X/Twitter and LinkedIn
- Multi-Persona: Choose Buffett (value), Trump (bullish hype), or Burry (contrarian) styles
- Approval Workflow: Review, approve, decline, or reprompt generated content
- Fact-Checked: All content passes through 2-source verification
- Image Generation: Create editorial illustrations with 4 visual styles
Execute trades with behavioral awareness:
- Real-Time Pricing: Live quotes with price charts
- Emotional Tagging: Automatic detection of revenge trades, panic sells, FOMO buys
- Trade History: Track performance with P&L and emotional patterns
- Balance Management: Simulated portfolio with $10,000 starting balance
Cross-session intelligence via Mem0:
- Chat Memory: AI remembers past coaching conversations
- Pattern Learning: System learns from repeated behavioral warnings
- Semantic Search: Retrieve relevant past conversations automatically
- Memory Management: View, search, and delete stored memories
Start your day with a personalized audio briefing:
- Daily Script Generation: Uses Gemini to synthesize overnight market news into a concise script
- Neural TTS: High-quality voice generation using Gemini audio capabilities
- Personalized Feed: Content tailored to your watchlist and portfolio
- On-Demand Playback: Stream via the dashboard or download for your commute
Understanding complex AI reasoning:
- React Flow Integration: Visualizes the AI's thought process as an interactive node graph
- Chat Summaries: Automatically condenses long conversations into visual flowcharts
- Traceability: See how the AI connected data points to reach its conclusion
ML-powered user classification:
- XGBoost Classifier: Custom-trained model (
trading_suitability_model_v2.pkl) determines risk tier- Suitability Assessment: Classifies users as Conservative, Balanced, or Aggressive
- 16-Point Analysis: Factors include net worth ratio, trading intensity, experience, and horizon
- Regulatory Compliance: Ensures users are matched with appropriate products
- Next.js 15 - React framework with App Router
- TypeScript - Type-safe development
- Tailwind CSS v4 - Utility-first styling
- WebSocket Client - Real-time updates
- React Markdown - Rich text rendering
- FastAPI - High-performance Python web framework
- Python 3.13 - Latest Python with asyncio
- Pydantic v2 - Data validation and settings
- WebSocket - Real-time event broadcasting
- Background Tasks - Async processing
- LangGraph - Stateful AI agent orchestration
- Google Gemini 2.0 Flash - Text generation and reasoning
- Google Gemini 3 Pro Image - Editorial illustration generation
- Tavily Python SDK - News verification (2+ source rule)
- FastMCP - Tool server protocol
- 10+ Market Tools:
- Price data: yfinance, Finnhub, Alpha Vantage
- News: NewsData.io, MediaStack, Alpha Vantage
- User patterns: Supabase queries
- Correlation scoring: Deterministic algorithm
- Mock Fallback System - Resilient when APIs fail
- Supabase - PostgreSQL database
- 8 Tables: users, trade_history, behavioral_metrics, content_drafts, market_events, user_newsletters, and more
- JSONB Fields - Flexible metadata storage
- GIN Indexes - Optimized queries
- Mem0 Platform - Persistent memory storage
- Finnhub - Real-time stock & crypto data
- Alpha Vantage - Market data & news sentiment
- NewsData.io - Global news articles
- MediaStack - News search with filtering
- Tavily Search - AI-native news verification
- yfinance - Historical price data
- Python 3.11+ (Python 3.13 recommended)
- Node.js 18+
- uv (Python package manager)
- Supabase Account
- API Keys:
- Google Gemini API Key (required)
- Finnhub API Key (recommended)
- Alpha Vantage API Key (optional)
- NewsData.io API Key (optional)
- MediaStack API Key (optional)
- Tavily API Key (for fact-checking)
- Mem0 API Key (for persistent memory)
-
Clone the repository:
git clone https://github.com/johnnytan5/WInTheChat.git cd WInTheChat -
Environment Setup:
cp .env.example .env # Edit .env and add your API keys -
Install Dependencies:
Backend:
cd backend uv syncFastMCP Server:
cd fastmcp_server uv syncFrontend:
cd frontend npm install -
Database Setup:
# Run schema.sql in your Supabase SQL editor # Located at: docs/schema.sql # Seed demo data (optional) cd backend uv run python scripts/seed_data.py
-
Launch Development Environment:
Open 3 separate terminals:
Terminal 1 - Backend:
cd backend uv run uvicorn app.main:app --reload --port 8000Terminal 2 - FastMCP Server:
uv run python -m fastmcp_server.server
Terminal 3 - Frontend:
cd frontend npm run dev -
Access the application:
- Frontend: http://localhost:3000
- Backend API Docs: http://localhost:8000/docs
- FastMCP Server: http://localhost:9000/mcp
- Navigate to User Portal → Coach
- Ask questions like:
- "What's the current price of AAPL?"
- "Get news sentiment for NVDA"
- "Should I buy TSLA given my trading patterns?"
- The AI will:
- Search your trading history
- Call relevant market data tools
- Reference past conversations from Mem0
- Provide personalized advice
- Navigate to Manager Portal
- View generated content drafts
- Actions available:
- ✅ Approve - Mark as ready for publishing
- ❌ Decline - Reject the content
- ✏️ Reprompt - Provide custom instructions to regenerate
All generated content passes through our 2-source verification:
- Price Claims: Verified against Finnhub real-time quotes (±1% tolerance)
- News Claims: Verified against Tavily Search (minimum 2 independent sources)
- Retry Mechanism: Up to 3 attempts with specific correction prompts
- Human Review: Unverifiable content flagged for manual review
- Mock Fallbacks: Every tool has realistic mock data when APIs fail
- Graceful Degradation: System continues operating even if some services are down
- Error Broadcasting: WebSocket events notify frontend of failures
- Async Processing: Long-running operations don't block the API
| Endpoint | Method | Purpose |
|---|---|---|
/api/auth/login |
POST | User authentication |
/api/auth/register |
POST | Create new account |
/api/analyze/trigger |
POST | Trigger LangGraph analysis |
/api/events/trigger |
POST | Trigger event-driven newsletter |
/api/users/{id}/newsletter |
GET | Get personalized newsletter |
/api/chat |
POST | AI coaching chat |
/api/trades |
GET/POST | View/execute trades |
/api/content/drafts |
GET | List content drafts |
/api/content/drafts/{id} |
PATCH | Approve/decline/reprompt |
/api/memory/{user_id} |
GET | List user memories |
/api/image/generate |
POST | Generate editorial images |
/ws/events |
WebSocket | Real-time pipeline events |
Full API documentation: http://localhost:8000/docs
Our tool server provides 10+ standardized tools:
get_price_data(ticker, timeframe)- Historical OHLC with anomaly detectionget_finnhub_quote(ticker)- Real-time stock quotesget_alpha_stock_quote(ticker)- Alpha Vantage quotesget_crypto_candles(symbol, resolution, days_back)- Crypto candlestick data
search_market_moving_news(ticker, timeframe)- NewsData.io searchfetch_article_deep_dive(article_id)- Full article analysissearch_mediastack_news(keywords, ...)- Global news searchget_news_sentiment(tickers, ...)- Alpha Vantage sentiment
query_user_patterns(user_id)- Trading history and behavioral metricsverify_correlation(price_event, news_event)- Deterministic correlation scoring
All tools include mock fallbacks for offline development and API rate limit resilience.
WInTheChat/
├── frontend/ # Next.js 15 application
│ ├── src/
│ │ ├── app/ # App router pages
│ │ │ ├── portal/user/ # User portal (terminal, chat, newsletter)
│ │ │ └── portal/manager/ # Manager portal
│ │ ├── components/ # React components
│ │ ├── lib/ # API client, types, utilities
│ │ └── hooks/ # Custom hooks (WebSocket, analysis)
│ └── package.json
│
├── backend/ # FastAPI backend
│ ├── app/
│ │ ├── routers/ # API endpoints (10+ routers)
│ │ ├── services/ # Business logic (LangGraph runner, LLM, memory)
│ │ ├── ws/ # WebSocket manager
│ │ └── main.py # FastAPI application
│ ├── scripts/ # seed_data.py
│ └── pyproject.toml
│
├── langgraph_agent/ # LangGraph AI pipeline
│ └── graph/
│ ├── nodes/ # 5 pipeline nodes
│ ├── prompts/ # LLM prompts (personas, fact-check, coaching)
│ ├── state.py # AnalysisState TypedDict
│ ├── builder.py # Graph construction
│ ├── llm.py # Gemini client
│ └── mcp_client.py # FastMCP client
│
├── fastmcp_server/ # Tool server (MCP protocol)
│ ├── tools/ # 10+ market data tools
│ ├── utils/ # Z-score, Supabase client
│ └── server.py # FastMCP server
│
├── docs/ # Documentation
│ ├── schema.sql # Database schema
│ ├── system-design.md # Architecture
│
├── .env.example # Environment variables template
└── README.md # This file
- Trading Terminal: Execute trades with real-time pricing and emotional tagging
- AI Coach Chat: Conversational interface with tool calling and memory
- Event Newsletter: 3-section cards (Price Action, News Correlation, Coaching) with fact-check badges and hover tooltips
- Newsletter Modal: Full content view with "Chat with AI" integration
- Event Feed: Real-time WebSocket updates showing pipeline progress
- Content Cards: Review generated social media posts
- Approval Workflow: Approve, decline, or reprompt with custom instructions
- Multi-Persona View: Filter by Buffett, Trump, or Burry style
The system maintains persistent memory across sessions:
- Chat Endpoint: Searches past conversations before responding, stores exchanges after
- Behavioral Coaching: References past coaching warnings (e.g., "We warned you about revenge trading 3 times this week")
- Semantic Search: Finds relevant memories automatically
- Memory API: CRUD operations for user memory management
Unique 3-attempt verification system:
Generate Content → Extract Claims → Verify Claims
↓
All Passed? → YES → Deliver to users ✅
↓ NO
retry < 3? → YES → Generate correction_prompt → Regenerate ↻
↓ NO
Flag for human review ⚠️
Create professional editorial illustrations:
- 4 Visual Styles: Modern Flat Vector, 3D Isometric Glass, Editorial Collage, Abstract Data Flow
- Prompt Engineering: Style injection for premium Bloomberg/NYT aesthetic
- Base64 Output: Direct embedding in social media posts
- Powered by: Gemini 3 Pro Image model
Required variables in .env:
# LLM (Required)
GEMINI_API_KEY=your_gemini_api_key
# Database (Required)
SUPABASE_URL=your_supabase_project_url
SUPABASE_KEY=your_supabase_anon_key
# Market Data (Recommended)
FINNHUB_API_KEY=your_finnhub_api_key
ALPHAADVANTAGE_API_KEY=your_alpha_vantage_key
# News (Optional - has fallbacks)
NEWSDATA_API_KEY=your_newsdata_api_key
MEDIASTACK_API_KEY=your_mediastack_api_key
# Fact-Checking (Recommended)
TAVILY_API_KEY=your_tavily_api_key
# Memory (Optional)
MEM0_API_KEY=your_mem0_api_key
# Internal Services (Default)
MCP_SERVER_URL=http://localhost:9000
BACKEND_PORT=8000- System Design - Detailed architecture explanation
- Schema - Database schema with relationships
- MCP Tools - Tool server documentation
- Pitch Deck Components - Architecture analysis
- Event Trigger Guide - How to use the event system
- How to Run - Detailed setup instructions
Backend only:
cd backend
uv run uvicorn app.main:app --reload --port 8000FastMCP Server only:
cd fastmcp_server
uv run mcp dev server.pyFrontend only:
cd frontend
npm run dev- 5-Node AI Pipeline - Sophisticated orchestration with conditional routing and retry loops
- Automated Fact-Checking - Dual-source verification (Finnhub + Tavily) with 2+ source requirement
- Persistent Memory - Cross-session context via Mem0 for truly personalized advice
- Event-Driven Architecture - Real-time newsletter generation from market anomalies
- Microservices Design - Isolated tool server with graceful degradation
- Content Approval Workflow - Enterprise-ready content management
- Real-Time Updates - WebSocket broadcasting for live UI updates
- Multi-Modal AI - Text generation + editorial image creation
- Behavioral Analytics - Personalized coaching based on individual trading patterns
- Production-Ready - Error handling, fallbacks, retry logic, human review paths
- Shawn Chee
- Tan Hao Wen
- Somendran Sunder
- Lim Zhe Yu
- Lim Jia Le
Deriv AI Hackathon 2026