Skip to content

jsong552/CogniTrade

Repository files navigation

CogniTrade

A QHacks 2026 Project

CogniTrade Logo

AI-Powered Trading Psychology Platform

Identify, understand, and overcome psychological trading biases with machine learning

React TypeScript Python Flask


🎯 Overview

CogniTrade is a comprehensive trading psychology platform that combines paper trading simulation with AI-powered behavioral analysis. It uses machine learning models to detect common psychological biases in your trading patterns, helping you become a more disciplined and profitable trader.

Why CogniTrade?

Most traders don't fail because of bad strategiesβ€”they fail because of psychological biases. CogniTrade helps you:

  • πŸ“Š Track your trades with a realistic paper trading simulation
  • 🧠 Detect psychological biases using ML models trained on trading behavior
  • πŸ’¬ Get AI-powered insights from an expert trading coach
  • πŸ“ˆ Improve your discipline with educational content and quizzes

✨ Features

πŸ“Š Paper Trading Simulator

Full-featured paper trading with real market data powered by the Alpaca Markets API:

  • Market & Limit Orders β€” Execute buy/sell orders with market or limit pricing
  • Stop-Loss & Take-Profit β€” Set automatic exit levels for risk management
  • Watchlist Management β€” Track your favorite stocks with live price updates
  • Position Tracking β€” Monitor P&L, average cost basis, and portfolio allocation
  • Order History β€” Complete log of all trades with timestamps and notes
  • Voice Memos β€” Record voice notes for trades using speech-to-text (Gradium API)
  • Interactive Charts β€” Real-time candlestick charts with multiple timeframes
  • Persistent Data β€” All data saved to localStorage for consistency across sessions

🧠 AI Behavioral Analysis

Upload your trade logs (or use your in-app trades) for comprehensive psychological analysis:

Machine Learning Models

Model Detection Target Algorithm
Overtrading Detector Excessive trading frequency XGBoost Classifier
Revenge Trading Detector Post-loss aggressive trading Custom ML Pipeline
Loss Aversion Detector Holding losers / cutting winners Pattern Analysis
Journal Bias Detector NLP analysis of trade journals RoBERTa Multi-Label

Five Psychological Biases Tracked

  1. FOMO β€” Chasing trades out of fear of missing out
  2. Loss Aversion β€” Cutting winners early, holding losers too long
  3. Revenge Trading β€” Trading emotionally after losses to "win it back"
  4. Overtrading β€” Taking excessive low-quality trades
  5. Gambler's Fallacy β€” Believing in false patterns and "due" wins

πŸ€– AI Trading Coach (Expert Agent)

An intelligent assistant powered by LangGraph + Backboard AI that:

  • Analyzes your complete trading history with SQL queries
  • Provides personalized feedback on your trading patterns
  • Answers follow-up questions about specific trades
  • Offers actionable advice for improving discipline
  • Streams responses with real-time progress updates

πŸ“š Educational Content

  • Behavior Summary β€” Quick-reference guide to the five trading biases
  • Pre-Trade Checklist β€” Questions to ask before every trade
  • Interactive Quiz β€” Test your bias recognition with real training examples
  • Daily Intentions β€” Mindset prompts for disciplined trading

πŸ—οΈ Architecture

CogniTrade/
β”œβ”€β”€ src/                     # React Frontend (Vite + TypeScript)
β”‚   β”œβ”€β”€ pages/               # Route pages
β”‚   β”‚   β”œβ”€β”€ Index.tsx        # Dashboard with portfolio overview
β”‚   β”‚   β”œβ”€β”€ TradePage.tsx    # Trading interface with charts
β”‚   β”‚   β”œβ”€β”€ SearchPage.tsx   # Stock search and watchlist
β”‚   β”‚   β”œβ”€β”€ AnalysisPage.tsx # ML bias analysis + AI chat
β”‚   β”‚   β”œβ”€β”€ SummaryPage.tsx  # Educational content + quiz
β”‚   β”‚   β”œβ”€β”€ SettingsPage.tsx # Account settings
β”‚   β”‚   └── LogsPage.tsx     # Trade history logs
β”‚   β”œβ”€β”€ components/          # Reusable UI components
β”‚   β”‚   β”œβ”€β”€ AlpacaMarketChart.tsx  # Interactive stock charts
β”‚   β”‚   β”œβ”€β”€ TradePanel.tsx         # Buy/sell order form
β”‚   β”‚   β”œβ”€β”€ AgentChat.tsx          # AI expert chat interface
β”‚   β”‚   β”œβ”€β”€ LogUpload.tsx          # Trade log upload + analysis
β”‚   β”‚   β”œβ”€β”€ BehaviorAnalysis.tsx   # Bias score cards
β”‚   β”‚   └── ui/                    # Radix UI primitives
β”‚   └── lib/
β”‚       └── tradingStore.ts  # Zustand state management
β”‚
β”œβ”€β”€ backend/                 # Python Flask Backend
β”‚   β”œβ”€β”€ app.py               # Flask API routes
β”‚   β”œβ”€β”€ agent.py             # LangGraph AI agent with DuckDB
β”‚   β”œβ”€β”€ models/              # ML model inference
β”‚   β”‚   β”œβ”€β”€ overtrading_model/
β”‚   β”‚   β”œβ”€β”€ revenge_trading_model/
β”‚   β”‚   └── loss_aversion_trading_model/
β”‚   β”œβ”€β”€ journal_model_training_script/
β”‚   β”‚   └── train_bias_detector.py  # RoBERTa training
β”‚   └── requirements.txt
β”‚
└── public/
    └── cognitrade_logo2.png

πŸš€ Getting Started

Prerequisites

  • Node.js 18+ and npm
  • Python 3.10+
  • API Keys (see below)

1. Clone the Repository

git clone https://github.com/yourusername/CogniTrade.git
cd CogniTrade

2. Configure Environment Variables

Copy the example environment file and add your API keys:

cp .env.example .env

Edit .env with your credentials:

# Alpaca Markets (for real-time stock data)
VITE_ALPACA_API_KEY=your_alpaca_key
VITE_ALPACA_SECRET_KEY=your_alpaca_secret
VITE_ALPACA_BASE_URL=https://paper-api.alpaca.markets

# Backend API URL (default for local dev)
VITE_API_URL=http://localhost:5001

# Gradium (for voice transcription)
GRADIUM_API_KEY=your_gradium_key
GRADIUM_REGION=us

# Backboard AI (for the AI trading expert)
BACKBOARD_API_KEY=your_backboard_key

# OpenAI (backup for AI features)
OPENAI_API_KEY=your_openai_key

3. Install Frontend Dependencies

npm install

4. Install Backend Dependencies

cd backend
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
cd ..

5. Start the Development Servers

Terminal 1 β€” Frontend:

npm run dev

Terminal 2 β€” Backend:

cd backend
source venv/bin/activate
python app.py

The app will be available at http://localhost:5173 or http://localhost:8080


πŸ“‘ API Endpoints

Backend API (Flask)

Endpoint Method Description
/ GET Health check
/health GET Service status
/transcribe POST Single-shot audio transcription
/transcribe/stream WebSocket Real-time streaming transcription
/analyze_journal POST Analyze journal text for biases (RoBERTa)
/analyze_trades POST Analyze trade CSV for all three biases
/agent/analyze POST Full AI analysis with ML + expert report (SSE)
/agent/chat POST Follow-up chat with the AI expert (SSE)

CSV Upload Format

For the /analyze_trades and /agent/analyze endpoints, upload a CSV with these columns:

Column Type Description
timestamp datetime Trade execution time
asset string Stock symbol (e.g., AAPL)
side string "buy" or "sell"
quantity number Number of shares
entry_price number Entry price per share
exit_price number Exit price per share
profit_loss number P&L for the trade
balance number Account balance after trade

πŸ”§ Tech Stack

Frontend

Technology Purpose
React 19 UI framework
TypeScript Type safety
Vite Build tool & dev server
TailwindCSS Utility-first styling
Radix UI Accessible component primitives
Zustand State management
Motion Animations
Recharts Data visualization
Lightweight Charts Stock candlestick charts
React Query Server state management

Backend

Technology Purpose
Flask Web framework
Flask-CORS Cross-origin requests
Flask-Sock WebSocket support
Pandas Data manipulation
scikit-learn ML utilities
XGBoost Overtrading model
PyTorch Deep learning runtime
Transformers RoBERTa bias detector
LangGraph AI agent orchestration
Backboard SDK AI thread management
DuckDB In-memory SQL for trade analysis

πŸ§ͺ Model Training

Overtrading Model

The overtrading detector uses XGBoost trained on windowed trading features:

  • Trade frequency per window
  • Average position size deviation
  • Time between trades
  • Win/loss streaks

Journal Bias Detector

The RoBERTa-based NLP model is trained on labeled trading journal entries:

cd backend/journal_model_training_script
python train_bias_detector.py

Training data is in backend/rational_training/train.json.


πŸ“Έ Screenshots

Dashboard Trading Analysis
Portfolio overview with P&L Real-time charts + order form ML bias scores + AI chat

πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


πŸ™ Acknowledgments


Trade smarter, not harder.

Made with ❀️ for disciplined traders everywhere.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors