Skip to content

Shawnchee/WInTheChat

 
 

Repository files navigation

WInTheChat - Intelligent Trading Analyst

"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.


🎯 The Problem

Retail traders face a "Triple Threat" disadvantage:

  1. Information Asymmetry: Breaking news is priced in before retail traders can react
  2. Cognitive Bias: Emotional decisions (FOMO, revenge trading) destroy carefully planned strategies
  3. Verification Gap: Distinguishing real market-moving news from noise is computationally expensive

💡 Our Solution

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

🏗️ System Architecture

High-Level Overview

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
Loading

The 5-Node AI Pipeline

Our LangGraph pipeline processes market events through 5 specialized nodes with a fact-checking retry loop:

  1. 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
  2. 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)
  3. 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
  4. 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
  5. 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

🎯 Key Features

1. Event-Driven Newsletter

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

2. AI Coaching Chat

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

3. Content Management System

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

4. Trading Terminal

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

5. Persistent Memory System

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

6. Auto-Generated Market Podcast

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

7. Interactive Visualizations

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

8. Intelligent Onboarding & Risk Profiling

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

🛠️ Technology Stack

Frontend

  • 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

Backend

  • 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

AI Layer

  • 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

Tool Server (FastMCP)

  • 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

Database & Storage

  • 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

External Services

  • 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

🚀 Getting Started

Prerequisites

  • 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)

Installation

  1. Clone the repository:

    git clone https://github.com/johnnytan5/WInTheChat.git
    cd WInTheChat
  2. Environment Setup:

    cp .env.example .env
    # Edit .env and add your API keys
  3. Install Dependencies:

    Backend:

    cd backend
    uv sync

    FastMCP Server:

    cd fastmcp_server
    uv sync

    Frontend:

    cd frontend
    npm install
  4. 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
  5. Launch Development Environment:

    Open 3 separate terminals:

    Terminal 1 - Backend:

    cd backend
    uv run uvicorn app.main:app --reload --port 8000

    Terminal 2 - FastMCP Server:

    uv run python -m fastmcp_server.server

    Terminal 3 - Frontend:

    cd frontend
    npm run dev
  6. Access the application:


📖 Usage Guide

Use the AI Coach

  1. Navigate to User Portal → Coach
  2. Ask questions like:
    • "What's the current price of AAPL?"
    • "Get news sentiment for NVDA"
    • "Should I buy TSLA given my trading patterns?"
  3. The AI will:
    • Search your trading history
    • Call relevant market data tools
    • Reference past conversations from Mem0
    • Provide personalized advice

Review and Approve Content

  1. Navigate to Manager Portal
  2. View generated content drafts
  3. Actions available:
    • Approve - Mark as ready for publishing
    • Decline - Reject the content
    • ✏️ Reprompt - Provide custom instructions to regenerate

🔒 Security & Reliability

Fact-Checking System

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

Error Resilience

  • 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

📊 API Endpoints

Core Endpoints

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


🧪 FastMCP Tools

Our tool server provides 10+ standardized tools:

Price Data Tools

  • get_price_data(ticker, timeframe) - Historical OHLC with anomaly detection
  • get_finnhub_quote(ticker) - Real-time stock quotes
  • get_alpha_stock_quote(ticker) - Alpha Vantage quotes
  • get_crypto_candles(symbol, resolution, days_back) - Crypto candlestick data

News Tools

  • search_market_moving_news(ticker, timeframe) - NewsData.io search
  • fetch_article_deep_dive(article_id) - Full article analysis
  • search_mediastack_news(keywords, ...) - Global news search
  • get_news_sentiment(tickers, ...) - Alpha Vantage sentiment

Analysis Tools

  • query_user_patterns(user_id) - Trading history and behavioral metrics
  • verify_correlation(price_event, news_event) - Deterministic correlation scoring

All tools include mock fallbacks for offline development and API rate limit resilience.


📁 Project Structure

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

🎨 UI Features

User Portal

  • 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

Manager Portal

  • 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

🧠 Advanced Capabilities

Memory System (Mem0 Integration)

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

Fact-Checking with Retry Loop

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 ⚠️

Image Generation

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

🔑 Environment Variables

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

📚 Documentation


🧪 Development Workflow

Run Individual Components

Backend only:

cd backend
uv run uvicorn app.main:app --reload --port 8000

FastMCP Server only:

cd fastmcp_server
uv run mcp dev server.py

Frontend only:

cd frontend
npm run dev

🎓 Key Differentiators

  1. 5-Node AI Pipeline - Sophisticated orchestration with conditional routing and retry loops
  2. Automated Fact-Checking - Dual-source verification (Finnhub + Tavily) with 2+ source requirement
  3. Persistent Memory - Cross-session context via Mem0 for truly personalized advice
  4. Event-Driven Architecture - Real-time newsletter generation from market anomalies
  5. Microservices Design - Isolated tool server with graceful degradation
  6. Content Approval Workflow - Enterprise-ready content management
  7. Real-Time Updates - WebSocket broadcasting for live UI updates
  8. Multi-Modal AI - Text generation + editorial image creation
  9. Behavioral Analytics - Personalized coaching based on individual trading patterns
  10. Production-Ready - Error handling, fallbacks, retry logic, human review paths

👥 Team

  • Shawn Chee
  • Tan Hao Wen
  • Somendran Sunder
  • Lim Zhe Yu
  • Lim Jia Le

Built For

Deriv AI Hackathon 2026

About

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 60.4%
  • Python 38.4%
  • Other 1.2%