# 🚀 Institutional Flow Trading Platform

A professional-grade institutional trading platform that combines real-time options flow analysis, multi-timeframe price context, alert stream correlation, institutional footprint detection, and automated scoring & badge system.

## Features

- **Real-time Options Flow Analysis** - Live streaming of options trades with institutional detection
- **Multi-Signal Scanner** - Automated scanning for high-probability trading opportunities
- **Daily Post-Mortem Analysis** - Performance tracking and analysis
- **Institutional Footprint Detection** - Tape alignment and cluster detection
- **Automated Scoring System** - Rocket Score (🚀) calculation for opportunity ranking
- **Badge System** - Visual indicators for trade characteristics (🟢🔴💎⭐💰⚡🚀)
- **Live WebSocket Updates** - Real-time data streaming
- **Interactive Charts** - TradingView-style price charts using Lightweight Charts

## Tech Stack

### Backend
- **Node.js** + **Express.js** - RESTful API server
- **PostgreSQL** (via **Supabase**) - Database
- **WebSocket** - Real-time data streaming
- **Express-WS** - WebSocket support for Express

### Frontend
- **React.js** - UI framework
- **Vite** - Build tool and dev server
- **TailwindCSS** - Utility-first CSS framework
- **Zustand** - State management
- **React Query** - Data fetching and caching
- **Lightweight Charts** - TradingView-style charts
- **shadcn/ui** - UI component library (styled components)

## Project Structure

```
/institutional_trader
├── /backend
│   ├── /src
│   │   ├── /routes          # API route handlers
│   │   ├── /queries         # Database query modules
│   │   ├── /services        # Business logic (badges, scoring, alignment)
│   │   ├── db.js            # Supabase connection
│   │   └── server.js        # Express server
│   ├── package.json
│   └── .env.example
├── /frontend
│   ├── /src
│   │   ├── /components      # React components
│   │   │   ├── /dashboard   # Main dashboard panels
│   │   │   ├── /charts      # Chart components
│   │   │   ├── /tables      # Table components
│   │   │   └── /ui          # UI components
│   │   ├── /hooks           # Custom React hooks
│   │   ├── /store           # Zustand store
│   │   ├── App.jsx
│   │   └── main.jsx
│   ├── package.json
│   ├── vite.config.js
│   └── tailwind.config.js
└── README.md
```

## Setup Instructions

### Prerequisites

- **Node.js** 18+ and npm
- **Supabase account** and project
- Git

### 1. Clone the Repository

```bash
git clone <repository-url>
cd institutional_trader
```

### 2. Backend Setup

```bash
cd backend
npm install
```

Create a `.env` file in the `backend` directory:

```env
# Supabase Configuration
SUPABASE_URL=your_supabase_project_url
SUPABASE_KEY=your_supabase_anon_key
SUPABASE_SERVICE_KEY=your_supabase_service_key

# Server Configuration
PORT=3001
NODE_ENV=development

# CORS Configuration
CORS_ORIGIN=http://localhost:5173
```

### 3. Database Setup (Supabase)

You'll need to create the following tables in your Supabase database:

#### `options_flow` table
```sql
CREATE TABLE options_flow (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  symbol VARCHAR(10) NOT NULL,
  type VARCHAR(4) NOT NULL, -- 'CALL' or 'PUT'
  strike DECIMAL(10, 2) NOT NULL,
  expiration TIMESTAMP WITH TIME ZONE,
  total_premium DECIMAL(15, 2),
  volume INTEGER,
  sentiment DECIMAL(3, 2), -- 0.00 to 1.00
  volume_ratio DECIMAL(10, 2),
  execution_time INTEGER, -- seconds
  rocket_score INTEGER, -- 0-100
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX idx_options_flow_symbol ON options_flow(symbol);
CREATE INDEX idx_options_flow_created_at ON options_flow(created_at DESC);
CREATE INDEX idx_options_flow_type ON options_flow(type);
```

#### `daily_analysis` table
```sql
CREATE TABLE daily_analysis (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  symbol VARCHAR(10) NOT NULL,
  analysis_date DATE NOT NULL,
  final_score INTEGER, -- 0-100
  price_change_percent DECIMAL(5, 2),
  flow_count INTEGER,
  total_premium DECIMAL(15, 2),
  call_put_ratio DECIMAL(5, 2),
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  UNIQUE(symbol, analysis_date)
);

CREATE INDEX idx_daily_analysis_date ON daily_analysis(analysis_date DESC);
CREATE INDEX idx_daily_analysis_symbol ON daily_analysis(symbol);
```

### 4. Frontend Setup

```bash
cd frontend
npm install
```

### 5. Start Development Servers

#### Terminal 1 - Backend
```bash
cd backend
npm run dev
```

The backend will start on `http://localhost:3001`

#### Terminal 2 - Frontend
```bash
cd frontend
npm run dev
```

The frontend will start on `http://localhost:5173`

## API Endpoints

### Options Flow
- `GET /api/options-flow` - Get recent options flow data
- `GET /api/options-flow/stats/:symbol` - Get flow statistics for a symbol
- `GET /api/options-flow/:id` - Get specific flow entry
- `POST /api/options-flow/search` - Search flows by criteria

### Daily Analysis
- `GET /api/daily-analysis` - Get recent daily analyses
- `GET /api/daily-analysis/:date` - Get analysis for specific date
- `GET /api/daily-analysis/:date/top` - Get top performers for date
- `GET /api/daily-analysis/symbol/:symbol` - Get symbol performance over time

### Scanner
- `POST /api/scanner/multi-signal` - Multi-signal scan
- `POST /api/scanner/clusters` - Institutional cluster detection
- `POST /api/scanner/alert-correlation` - Alert correlation analysis
- `GET /api/scanner/opportunities` - Quick top opportunities scan

### WebSocket
- `ws://localhost:3001/ws` - Real-time data streaming

## Badge System

The platform uses emoji badges to quickly identify trade characteristics:

- 🟢 **Bullish Flow** - Call options with bullish sentiment
- 🔴 **Bearish Flow** - Put options with bearish sentiment
- 💎 **Premium Trade** - High premium trades (>$100k)
- ⭐ **Unusual Activity** - Volume > 10x average
- 💰 **High Volume** - Volume > 1000 contracts
- ⚡ **Fast Execution** - Execution time < 5 seconds
- 🚀 **High Momentum** - Momentum score > 80

## Rocket Score

The Rocket Score (0-100) combines multiple signals:

- **Badge Score** (0-25 points) - Based on badge count
- **Tape Alignment** (0-30 points) - Price action alignment with flow
- **Premium Score** (0-20 points) - Trade size significance
- **Volume Score** (0-15 points) - Unusual volume detection
- **Sentiment Score** (0-10 points) - Directional conviction

**Score Tiers:**
- 90-100: 🚀🚀🚀 ELITE
- 75-89: 🚀🚀 HIGH
- 60-74: 🚀 MEDIUM
- 40-59: ⚡ LOW
- 0-39: MINIMAL

## Development

### Backend Scripts
- `npm run dev` - Start development server with auto-reload
- `npm start` - Start production server

### Frontend Scripts
- `npm run dev` - Start development server
- `npm run build` - Build for production
- `npm run preview` - Preview production build

## Environment Variables

### Backend (.env)
- `SUPABASE_URL` - Your Supabase project URL
- `SUPABASE_KEY` - Supabase anon key
- `SUPABASE_SERVICE_KEY` - Supabase service role key (for admin operations)
- `PORT` - Server port (default: 3001)
- `NODE_ENV` - Environment (development/production)
- `CORS_ORIGIN` - Allowed CORS origin

## Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

MIT License

## Support

For issues and questions, please open an issue on GitHub.

---

**Built with ❤️ for institutional traders**
