tradei
v2026.2.25
Published
TRADEI - AI Trading & Research Platform
Downloads
1,253
Maintainers
Readme
TRADEI
TRADEI is an autonomous AI trading & research platform that thinks, plans, and learns as it works. It performs financial analysis using task planning, self-reflection, and real-time market data — a terminal-based AI agent built specifically for financial research and trading.
Table of Contents
- Overview
- Use Cases
- Web UI
- Hosted Mode
- Scanner & Alerts
- Strategy Leaderboard
- Installation
- Prerequisites
- How to Run
- How to Evaluate
- How to Debug
- API Key Rotation
- Token Management
- WhatsApp Integration
- Contributing
- Credits
- License
Overview
TRADEI takes complex financial questions and turns them into clear, step-by-step research plans. It runs those tasks using live market data, checks its own work, and refines the results until it has a confident, data-backed answer.
Key Capabilities:
- Intelligent Task Planning: Automatically decomposes complex queries into structured research steps
- Autonomous Execution: Selects and executes the right tools to gather financial data
- Self-Validation: Checks its own work and iterates until tasks are complete
- Real-Time Financial Data: Access to income statements, balance sheets, and cash flow statements
- Multi-Provider LLM Support: Works with OpenAI, Anthropic, Google, xAI, OpenRouter, Ollama, and more
- Statistical Analysis: Cointegration testing (Engle-Granger, Johansen) and time series forecasting (ARIMA)
- Pairs Trading: Identify cointegrated stock pairs and backtest spread mean-reversion strategies
- Token Management: Budget enforcement, cost tracking, smart model routing, and response caching to minimize API spend
- API Key Rotation: Automatic fallback key chain — when a key hits credit limits, seamlessly switches to the next
- OpenRouter Auto-Detection: Models with
org/modelformat are automatically routed to OpenRouter — no manual prefix needed - Safety Features: Built-in loop detection and step limits to prevent runaway execution
- Hosted API Mode: Server-side API key management — users just connect, no BYOK friction
- Built-in Web UI (PWA): Clean, warm-themed chat interface with sidebar settings, feature launcher, and session management — installable as a PWA, no separate build step
- Stock Scanner: Scan Nifty 50 (or custom tickers) by RSI, MACD, SMA, volume, and price conditions
- Price & Indicator Alerts: File-based alert system with periodic evaluation and multi-channel notifications (console + WhatsApp)
- Strategy Leaderboard: Benchmark all strategies across tickers and rank by CAGR, Sharpe, win rate, or drawdown
- Broker Partnership API: Partnership program infrastructure with registration, webhooks, and status tracking
Use Cases
Fundamental Analysis
"Compare RELIANCE and TCS revenue growth over the last 5 years and tell me which is a better value"
TRADEI fetches income statements, calculates growth rates, compares P/E ratios, and delivers a data-backed comparison.
Portfolio Research
"Analyze the top 5 Nifty IT stocks — summarize their financials and recent momentum"
Automatically plans multi-step research across tickers, gathers data in parallel, and presents consolidated findings.
F&O Strategy Analysis
"Show me the NIFTY options chain for this week's expiry — highlight strikes with unusual OI buildup"
Pulls options chain data, analyzes open interest patterns, and identifies key support/resistance levels for expiry day trading.
Market Screening
"Find NSE stocks with RSI below 30, positive earnings growth, and market cap above ₹10,000 Cr"
Runs strategy-based screens using 25+ built-in trading strategies including CANSLIM, SEPA, Darvas Box, pairs trading, and more.
Expiry Day Trading
"What's the PCR for BANKNIFTY this Thursday? Run an ORB strategy with VIX regime filter"
Combines Put-Call Ratio, Opening Range Breakout, and India VIX data for weekly expiry day setups.
Pairs Trading & Cointegration
"Are HDFCBANK and ICICIBANK cointegrated? Backtest a pairs trade with 2σ entry"
Tests stock pairs for statistical cointegration using Engle-Granger and Johansen methods, computes spread half-life, and backtests spread mean-reversion strategies with configurable z-score thresholds.
Price Forecasting
"Forecast NIFTY closing prices for the next 5 trading sessions"
Uses ARIMA time series analysis with automatic order selection, seasonal decomposition, and confidence intervals — built for expiry-day VIX and price trend forecasting.
FII/DII Flow Tracking
"Show me FII and DII cash market activity for the last 10 sessions — are FIIs net buyers or sellers?"
Tracks institutional flow data from NSE, analyzes trends, and correlates with market direction.
Token & Cost Management
"How much have I spent today? Show me my weekly usage breakdown"
TRADEI tracks every API call with provider-specific pricing, enforces daily token budgets per tier, caches repeated queries, compresses large tool results, and routes simple questions to cheaper models — so you spend only what's needed.
Real-Time Alerts via WhatsApp
Send a message to yourself on WhatsApp and get AI-powered research responses on the go.
Web UI
TRADEI includes a built-in web UI served directly by the API server — no separate frontend build step required. The interface uses a clean, warm aesthetic inspired by Claude with Fig Tree + SF Pro typography and a cream/terracotta color palette.
# Start the API server — web UI is served automatically
bun run api
# Open in browser
open http://localhost:3001Chat:
- Real-time SSE streaming of agent responses
- Markdown rendering with syntax-highlighted code blocks and copy button
- Tool call display with collapsible input/result details
- Quick action cards for common trading queries
- Typing indicator and auto-scroll
Sidebar — 3 tabs:
- Chats — Session management with create, switch, and delete
- Features — Quick-launch cards for Stock Scanner, Price Alerts, Leaderboard, Portfolio, and Available Tools
- Settings — Provider/model selectors, stream responses toggle, auto-scroll toggle, show tool calls toggle, compact messages toggle, clear all sessions
Other:
- Installable as a PWA (Progressive Web App) with offline caching
- Mobile-responsive design with collapsible sidebar
- Online/offline status indicator
- All settings persist in localStorage
Hosted Mode
Hosted mode lets you run TRADEI as a managed service — users connect without needing their own LLM API keys.
# Set hosted mode environment variables
export TRADEI_HOSTED_MODE=true
export TRADEI_HOSTED_OPENAI_KEY=sk-your-key
export TRADEI_HOSTED_ANTHROPIC_KEY=sk-your-key # optional
export TRADEI_API_KEYS=user-key-1,user-key-2 # optional, for auth
# Start API server
bun run apiWhen TRADEI_API_KEYS is set, requests require a Bearer token in the Authorization header. When unset, all requests are allowed (dev mode).
Scanner & Alerts
Stock Scanner — Scan Nifty 50 (or custom tickers) against technical indicator conditions:
"Scan Nifty 50 for RSI below 30 and MACD bullish crossover"
Supported conditions: RSI above/below, price above/below, volume spike, MACD bullish/bearish, above/below SMA, price change %.
Alerts — Create persistent alerts that trigger on indicator conditions:
"Alert me when RELIANCE RSI drops below 30 on WhatsApp"
Alerts are stored in .dexter/alerts.json and evaluated periodically. Notifications via console or WhatsApp.
CLI Commands:
/scan Scan stocks by technical indicators
/alerts Manage price/indicator alertsStrategy Leaderboard
Benchmark all 25+ built-in strategies across configurable tickers and rank by performance metrics.
"Show strategy leaderboard sorted by Sharpe ratio"
"Run fresh benchmark for all strategies"
Sort by CAGR, Sharpe ratio, win rate, or max drawdown. Results are cached to .dexter/benchmarks/latest.json.
CLI Commands:
/leaderboard Show cached strategy rankings
/benchmark Run fresh benchmarksAPI Endpoints:
GET /api/leaderboard — View cached leaderboard
POST /api/leaderboard/run — Run fresh benchmarks
GET /api/partner/info — Broker partnership program info
POST /api/partner/register — Register as a partnerInstallation
npm / npx (Node.js 20+)
# Run directly
npx tradei
# Or install globally
npm install -g tradei
tradeiBun / bunx
# Run directly
bunx tradei
# Or install globally
bun install -g tradei
tradeiStandalone binary (zero dependencies)
curl -fsSL https://raw.githubusercontent.com/PJharwal/tradei/main/scripts/install.sh | sh
tradeiFrom source
git clone https://github.com/PJharwal/tradei.git
cd tradei
bun install
bun startPrerequisites
- OpenAI API key (get here)
- Financial Datasets API key (get here)
- Exa API key (get here) - optional, for web search
Set up your environment variables:
cp env.example .env
# Edit .env and add your API keys
# OPENAI_API_KEY=your-openai-api-key
# ANTHROPIC_API_KEY=your-anthropic-api-key (optional)
# GOOGLE_API_KEY=your-google-api-key (optional)
# XAI_API_KEY=your-xai-api-key (optional)
# OPENROUTER_API_KEY=your-openrouter-api-key (optional)
# OPENROUTER_API_KEY_FALLBACK=your-fallback-key (optional, for key rotation)
# FINANCIAL_DATASETS_API_KEY=your-financial-datasets-api-key
# EXASEARCH_API_KEY=your-exa-api-key (optional)
# TAVILY_API_KEY=your-tavily-api-key (optional)
# Hosted mode (optional — for running as a managed service)
# TRADEI_HOSTED_MODE=true
# TRADEI_HOSTED_OPENAI_KEY=your-hosted-openai-key
# TRADEI_API_KEYS=comma-separated-user-api-keysHow to Run
Run TRADEI in interactive mode:
bun startOr with watch mode for development:
bun devHow to Evaluate
TRADEI includes an evaluation suite that tests the agent against a dataset of financial questions. Evals use LangSmith for tracking and an LLM-as-judge approach for scoring correctness.
Run on all questions:
bun run src/evals/run.tsRun on a random sample of data:
bun run src/evals/run.ts --sample 10The eval runner displays a real-time UI showing progress, current question, and running accuracy statistics.
How to Debug
TRADEI logs all tool calls to a scratchpad file for debugging and history tracking. Each query creates a new JSONL file in .tradei/scratchpad/.
Scratchpad location:
.tradei/scratchpad/
├── 2026-01-30-111400_9a8f10723f79.jsonl
├── 2026-01-30-143022_a1b2c3d4e5f6.jsonl
└── ...Each file contains newline-delimited JSON entries tracking:
- init: The original query
- tool_result: Each tool call with arguments and raw result
- thinking: Agent reasoning steps
API Key Rotation
TRADEI automatically rotates API keys when a key hits credit exhaustion (402 errors) or persistent rate limits. Configure fallback keys in your .env:
# Primary key
OPENROUTER_API_KEY=sk-or-v1-primary-key
# Fallback keys — used automatically when the primary is exhausted
OPENROUTER_API_KEY_FALLBACK=sk-or-v1-fallback-key
OPENROUTER_API_KEY_FALLBACK_2=sk-or-v1-another-key
# Supports up to FALLBACK_5This works with any provider's API key (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.). When a key is exhausted, TRADEI:
- Marks the current key as exhausted
- Switches to the next available fallback key
- Resets all model rate limits so every model is available with the fresh key
- Retries the request transparently
OpenRouter Auto-Detection: Models using the org/model-name format (e.g. minimax/minimax-m2.5-20260211) are automatically detected and routed to OpenRouter — no openrouter: prefix needed.
Token Management
TRADEI includes a built-in token management system to keep API costs under control.
Features:
- Budget Enforcement: Per-query and daily token budgets with automatic early termination when limits are reached
- Cost Estimation: Real-time cost tracking with provider-specific pricing (OpenAI, Anthropic, Google, xAI)
- Persistent Usage Tracking: Daily, weekly, and monthly usage history stored locally
- Smart Model Routing: Automatically routes simple queries to cheaper models (opt-in via
autoRouteModelconfig) - Response Caching: File-based cache with per-tool TTLs — market data (5 min), search (15 min), forecasts (1 hr), backtests (24 hr)
- Result Compression: Large tool results are compressed before being sent to the LLM, saving context tokens
- Tier-Based Limits: Free (50k tokens/day), Pro (500k/day), Hosted (1M/day), Premium (2M/day), Team (unlimited)
CLI Commands:
/cost Show estimated cost for the current session
/usage View daily, weekly, and monthly token usage stats
/cache Show cache statistics
/cache clear Clear the response cacheWhatsApp Integration
Chat with TRADEI through WhatsApp by linking your phone to the gateway. Messages you send to yourself are processed by TRADEI and responses are sent back to the same chat.
Quick start:
# Link your WhatsApp account (scan QR code)
bun run gateway:login
# Start the gateway
bun run gatewayThen open WhatsApp, go to your own chat (message yourself), and ask TRADEI a question.
Contributing
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
Important: Please keep your pull requests small and focused.
Credits
Built on the foundation of Dexter by @virattt — an autonomous financial research agent.
License
This project is licensed under the MIT License.
