# Crypto Algo Trading Platform – Master Requirement & Implementation Guide v2.3

**Last Updated**: January 21, 2026  
**Status**: Production Ready  
**Version**: 2.3
**Implementation**: Complete with Multi-Strategy + Multi-Asset Trading

This document contains the complete requirements, implementation status, and operational guide for the crypto algorithmic trading platform using PHP (OOP) and React.  
All documentation is stored in the `/docs` folder.  
All test scripts are stored in the `/tests` folder and `/bin` folder for operational scripts.

---

## 📊 CURRENT IMPLEMENTATION STATUS (v2.3)

### ✅ FULLY IMPLEMENTED FEATURES

#### 1. Multi-Strategy Architecture (v2.3 - NEW)
- ✅ **Multiple trading strategies per platform**
  - Options selling strategy for Delta Exchange
  - Spot trading strategy for CoinDCX
  - Futures strategy (disabled, for future use)
- ✅ **Strategy-broker mapping system**
  - Database-driven strategy assignment
  - `broker_strategy_mapping` table
  - Dynamic strategy selection based on broker and asset
- ✅ **Strategy parameters management**
  - Configurable SuperTrend parameters per strategy
  - Strategy instances for different assets/timeframes
  - Active/inactive strategy toggling

#### 2. Multi-Asset Trading (v2.3 - NEW)
- ✅ **Trade multiple cryptocurrencies simultaneously**
  - BTC, ETH, SHIB, AVAX, SAND
- ✅ **Automatic asset detection**
  - Scans broker accounts for available holdings
  - Validates against minimum trading requirements
  - `AssetDetectionService` for dynamic discovery
- ✅ **Tradeable assets configuration**
  - `tradeable_assets` table
  - Broker-specific market name mapping
  - Minimum quantity and notional value settings
- ✅ **Symbol-to-market conversion**
  - BTCUSD → BTCINR (CoinDCX)
  - ETHUSD → ETHINR (CoinDCX)
  - Automatic mapping for all supported assets

#### 3. Core Trading Engine
- ✅ SuperTrend-based algorithmic trading (16, 1.5 for entry, 10, 3 for exit)
- ✅ Multi-timeframe support (90M entry, 30M/45M exit)
- ✅ Event-driven architecture with dispatchers
- ✅ Candle aggregation from tick data
- ✅ Indicator calculation engine (SuperTrend, ATR)
- ✅ Trade signal generation and execution
- ✅ Active trade monitoring with exit conditions

#### 4. Multi-Exchange Support
- ✅ **Delta Exchange** (TEST/TESTNET + LIVE environments)
- ✅ **CoinDCX** (LIVE environment)
- ✅ Broker-agnostic architecture via `BrokerInterface`
- ✅ Dynamic broker routing based on symbol
- ✅ Multiple brokers for same symbol support
- ✅ Account-based order routing

#### 5. Options Trading (Delta Exchange Only)
- ✅ Strike selection (nearest to SuperTrend value, equidistant handling)
- ✅ Expiry selection (0DTE/1DTE/2DTE with >= 300 USD premium)
- ✅ Premium tracking via WebSocket (Delta Options)
- ✅ 70% premium decay exit
- ✅ SuperTrend flip exit (30M/45M)
- ✅ 13-hour maximum duration exit

#### 6. Order Execution & Management
- ✅ Paper trading mode
- ✅ Live trading mode (configurable via `TRADING_ENABLED` and `PAPER_TRADING`)
- ✅ Order status polling
- ✅ Balance verification before orders
- ✅ Currency conversion (USD ↔ INR)
- ✅ Test account fund check bypass
- ✅ Crypto holdings verification for SELL orders
- ✅ Retry logic with exponential backoff
- ✅ Rate limiting (token bucket algorithm)

#### 7. Market Data Pipeline
- ✅ WebSocket connection to Delta Exchange (spot + options)
- ✅ Real-time tick ingestion
- ✅ Candle aggregation for multiple timeframes
- ✅ Candle persistence to database
- ✅ Indicator computation on candle close
- ✅ Environment-aware WebSocket (TESTNET/LIVE)

#### 8. Telegram Notifications
- ✅ **Trade signals** (sent to ALL subscribers)
  - Entry signals (SuperTrend flip on 90M)
  - Exit signals (70% premium decay, SuperTrend flip, 13-hour limit)
- ✅ **Order notifications** (sent to LINKED subscribers only)
  - Order executed confirmations
  - Order rejected notifications
  - Broker-specific filtering
- ✅ Bot commands: `/start`, `/status`, `/unsubscribe`
- ✅ Subscriber-to-broker account linking
- ✅ Interactive bot management

#### 9. Logging & Monitoring
- ✅ Centralized logging (`App\Support\Logger`)
- ✅ Indian Standard Time (IST) timestamps
- ✅ Sequential logging for strategy validation
- ✅ API request/response logging
- ✅ Error tracking with stack traces

#### 10. Database Schema
- ✅ `candles` - OHLCV data
- ✅ `indicator_values` - Technical indicators
- ✅ `orders` - Order history with strike/expiry/option_type
- ✅ `active_trades` - Currently open positions
- ✅ `brokers` - Exchange master data with API/WebSocket URLs (v2.2)
- ✅ `broker_accounts` - Account credentials (TEST/LIVE)
- ✅ `symbol_broker_mapping` - Multi-broker routing
- ✅ `telegram_subscribers` - Notification subscribers
- ✅ `telegram_subscriber_broker_mapping` - Many-to-many broker linking (v2.1)
- ✅ `strategies` - Trading strategy definitions with type (SPOT/OPTIONS/FUTURES) (v2.3)
- ✅ `strategy_instances` - Strategy configurations for specific assets/timeframes (v2.3)
- ✅ `strategy_parameters` - Strategy-specific parameters (v2.3)
- ✅ `broker_strategy_mapping` - Links brokers to strategies (v2.3)
- ✅ `tradeable_assets` - Asset configuration with minimums (v2.3)
- ✅ `assets` - Master list of supported assets (v2.3)

#### 11. Testing & Validation
- ✅ Smoke tests for market data pipeline
- ✅ Integration tests for order execution
- ✅ Multi-exchange order placement tests
- ✅ Live API testing scripts
- ✅ WebSocket connection tests
- ✅ End-to-end trading flow tests

---

## 🎯 BUSINESS & STRATEGY OVERVIEW

### Trading Strategy
- **Type**: Directional Options Selling
- **Underlying**: BTCUSD Perpetual Futures (for trend detection)
- **Execution**: BTCUSD Options (CE/PE)
- **Supported Assets**: BTC (currently), ETH and others (future phases)
- **Exchanges**: Delta Exchange, CoinDCX

### Market Access
- **Delta Exchange**: TEST (testnet.delta.exchange), LIVE (delta.exchange)
- **CoinDCX**: LIVE (coindcx.com)
- **Data Feed**: Delta WebSocket (spot + options premium)

---

## 📈 CORE STRATEGY LOGIC (SUPERTREND BASED)

### Entry Rules
- **Indicator**: SuperTrend (16, 1.5)
- **Timeframe**: 90 minutes
- **Trigger**: Only on SuperTrend flip candle CLOSE
- **Direction**:
  - Bullish Flip (UP) → SELL PUT
  - Bearish Flip (DOWN) → SELL CALL
- **Position Limit**: Only one active trade at a time

### Strike Selection
1. **Primary Rule**: Nearest strike to SuperTrend value
   - Example: SuperTrend = 93491 → Strike = 93400
   - Example: SuperTrend = 98978 → Strike = 99000

2. **Equidistant Handling**:
   - If two strikes are equidistant, choose further OTM:
     - Bullish (PUT selling) → Lower strike (more OTM PUT)
     - Bearish (CALL selling) → Higher strike (more OTM CALL)

### Expiry Selection
**Priority Order**: 0 DTE → 1 DTE → 2 DTE

**Logic**:
1. Check current day expiry (0 DTE)
2. If premium >= 300 USD → Execute trade
3. If premium < 300 USD → Check next expiry
4. Continue through 1 DTE, 2 DTE
5. If all expiries fail premium check → **Skip trade completely**

### Exit Rules (Priority Order)

#### 1. **70% Premium Decay** (HIGHEST PRIORITY)
- Exit when premium drops to 30% of entry premium
- **Instant execution** (tick-based, no candle close required)
- Example: Entry = 500 USD, Exit = 150 USD

#### 2. **SuperTrend Exit** (SECONDARY)
- Monitor 30M and 45M timeframes
- Apply SuperTrend (10, 3) on both
- Exit when candle CLOSES opposite to trade direction
- Either 30M OR 45M flip triggers exit

#### 3. **Time-Based Exit** (TERTIARY)
- Maximum trade duration: 13 hours from entry
- Force close regardless of P/L

#### 4. **Hold Condition**
- If none of the above, continue holding

---

## 🏗️ SYSTEM ARCHITECTURE

### Technology Stack
- **Frontend**: React JS (WebSocket-based real-time dashboard) - *Pending*
- **Backend**: PHP 7.4+ (OOP, SOLID principles)
- **Database**: MySQL/MariaDB
- **WebSocket**: Ratchet/Pawl for PHP
- **HTTP Client**: Guzzle for API calls
- **Environment**: vlucas/phpdotenv for configuration

### Design Principles
1. **Event-Driven Architecture**: All modules communicate via events
2. **Broker-Agnostic**: Unified interface for all exchanges
3. **Strategy Isolation**: Each strategy instance runs independently
4. **Repository Pattern**: Clean separation of data access
5. **DTO Pattern**: Structured data transfer between modules

### Module Structure

```
app/
├── Algorithm/              # Trading strategy logic
│   ├── Engine/
│   ├── Strategies/
│   ├── Events/
│   └── Repository/
├── MarketData/            # Market data ingestion & processing
│   ├── WebSocket/
│   ├── Aggregation/
│   ├── Persistence/
│   └── Bootstrap/
├── Indicator/             # Technical indicator calculation
│   ├── Calculators/
│   ├── Engine/
│   └── Repository/
├── Execution/             # Order execution & broker integration
│   ├── Brokers/
│   ├── Engine/
│   ├── Services/
│   ├── DTO/
│   └── Repository/
├── TradeMonitor/          # Active trade monitoring & exits
│   ├── Engine/
│   ├── Services/
│   └── Repository/
├── Notification/          # Telegram notifications
│   ├── Engine/
│   ├── Channels/
│   ├── Telegram/
│   └── Repository/
└── Support/               # Utilities
    ├── Logger.php
    ├── Env.php
    ├── Database.php
    ├── RateLimiter.php
    └── RetryHandler.php
```

---

## 💾 DATABASE SCHEMA

### Core Tables

#### `candles`
```sql
CREATE TABLE candles (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    symbol VARCHAR(20) NOT NULL,
    timeframe INT NOT NULL,
    candle_open_ts INT NOT NULL,
    candle_close_ts INT NOT NULL,
    open_price DECIMAL(20,8) NOT NULL,
    high_price DECIMAL(20,8) NOT NULL,
    low_price DECIMAL(20,8) NOT NULL,
    close_price DECIMAL(20,8) NOT NULL,
    volume DECIMAL(20,8) NOT NULL,
    is_closed TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_candle (symbol, timeframe, candle_open_ts),
    INDEX idx_symbol_tf_time (symbol, timeframe, candle_open_ts)
);
```

#### `indicator_values`
```sql
CREATE TABLE indicator_values (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    symbol VARCHAR(20) NOT NULL,
    timeframe INT NOT NULL,
    indicator_name VARCHAR(50) NOT NULL,
    candle_close_ts INT NOT NULL,
    indicator_values JSON NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_symbol_tf_indicator (symbol, timeframe, indicator_name)
);
```

#### `orders`
```sql
CREATE TABLE orders (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    trade_id VARCHAR(50) NULL,
    broker_order_id VARCHAR(100) NULL,
    symbol VARCHAR(20) NOT NULL,
    order_type ENUM('ENTRY', 'EXIT', 'SL', 'TP') NOT NULL,
    side ENUM('BUY', 'SELL') NOT NULL,
    price DECIMAL(20,8) NULL,
    quantity DECIMAL(20,8) NOT NULL,
    status ENUM('PENDING', 'PLACED', 'EXECUTED', 'REJECTED', 'CANCELLED') NOT NULL,
    strike DECIMAL(20,2) NULL,
    expiry DATE NULL,
    option_type ENUM('CALL', 'PUT') NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_trade_id (trade_id),
    INDEX idx_broker_order_id (broker_order_id),
    INDEX idx_status (status)
);
```

#### `active_trades`
```sql
CREATE TABLE active_trades (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    trade_id VARCHAR(50) UNIQUE NOT NULL,
    symbol VARCHAR(20) NOT NULL,
    timeframe INT NOT NULL,
    direction ENUM('BULLISH', 'BEARISH') NOT NULL,
    strike DECIMAL(20,2) NOT NULL,
    expiry DATE NOT NULL,
    option_type ENUM('CALL', 'PUT') NOT NULL,
    entry_premium DECIMAL(20,8) NOT NULL,
    current_premium DECIMAL(20,8) NOT NULL,
    entry_time TIMESTAMP NOT NULL,
    quantity DECIMAL(20,8) NOT NULL,
    mode ENUM('PAPER', 'LIVE') NOT NULL,
    broker_code VARCHAR(20) NULL,
    status ENUM('OPEN', 'CLOSED') DEFAULT 'OPEN',
    exit_reason VARCHAR(100) NULL,
    exit_premium DECIMAL(20,8) NULL,
    exit_time TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_symbol (symbol),
    INDEX idx_status (status),
    INDEX idx_trade_id (trade_id)
);
```

#### `brokers`
```sql
CREATE TABLE brokers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

#### `broker_accounts`
```sql
CREATE TABLE broker_accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    broker_id INT NOT NULL,
    environment ENUM('TEST', 'LIVE') NOT NULL,
    base_currency VARCHAR(10) NOT NULL,
    credentials JSON NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (broker_id) REFERENCES brokers(id)
);
```

#### `symbol_broker_mapping`
```sql
CREATE TABLE symbol_broker_mapping (
    id INT AUTO_INCREMENT PRIMARY KEY,
    symbol VARCHAR(20) NOT NULL,
    broker_account_id INT NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (broker_account_id) REFERENCES broker_accounts(id),
    INDEX idx_symbol (symbol)
);
```

#### `telegram_subscribers`
```sql
CREATE TABLE telegram_subscribers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    chat_id VARCHAR(255) UNIQUE NOT NULL,
    username VARCHAR(255) DEFAULT NULL,
    broker_account_id INT NULL,
    notification_preferences JSON NULL,
    is_active TINYINT(1) DEFAULT 1,
    subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (broker_account_id) REFERENCES broker_accounts(id) ON DELETE SET NULL,
    INDEX idx_chat_id (chat_id),
    INDEX idx_is_active (is_active),
    INDEX idx_broker_account (broker_account_id)
);
```

---

## ⚙️ CONFIGURATION (.env)

### Database Configuration
```env
DB_HOST=localhost
DB_PORT=3306
DB_NAME=crypto_algo
DB_USER=root
DB_PASS=
```

### Application Settings
```env
APP_TIMEZONE=Asia/Kolkata
LOG_LEVEL=DEBUG
```

### Trading Configuration
```env
TRADING_ENABLED=true
PAPER_TRADING=false
TRADING_SYMBOLS=BTCUSD
```

### Delta Exchange API
```env
DELTA_API_KEY=your_api_key_here
DELTA_API_SECRET=your_api_secret_here
```

### CoinDCX API
```env
COINDCX_API_KEY=your_api_key_here
COINDCX_API_SECRET=your_api_secret_here
```

### Telegram Bot
```env
TELEGRAM_BOT_TOKEN=your_bot_token_here
```

---

## 🚀 OPERATIONAL GUIDE

### Starting the System

#### Option 1: Start All Services with Visible Output (Recommended) ⭐

**For Windows (shows real-time logs)**:
```bash
bin\start-all-visible.bat
```

**Cross-platform (background mode)**:
```bash
php bin/start-all-services.php
```

**Why visible mode?**
- ✅ See real-time logs in each window
- ✅ Easy debugging
- ✅ Monitor all services at once
- ✅ Better for development/troubleshooting

**What it starts**:
- ✅ Market Data Runner (WebSocket, candles, indicators, algorithm)
- ✅ Trade Monitor Runner (exit conditions, premium tracking)
- ✅ Telegram Bot Runner (notifications, subscriber commands)
- ✅ Order Status Poller (order status updates)

**Features**:
- All services run in parallel
- Cross-platform (Windows, Linux, Mac)
- PID management for easy stopping
- Background execution

**Management commands**:
```bash
# Check status
php bin/check-services-status.php

# Stop all services
php bin/stop-all-services.php
```

#### Option 2: Start Individual Services with Visible Output

**Windows (visible logs)**:
```bash
bin\start-market-data-visible.bat
bin\start-telegram-bot-visible.bat
```

**Or use foreground PHP launcher**:
```bash
php bin/start-services-foreground.php
```

#### Option 3: Start Services Individually (Background Mode)

**1. Market Data Runner** (Ingests ticks, aggregates candles, calculates indicators)
```bash
php bin/market-data-runner.php
```

**2. Trade Monitor Runner** (Monitors active trades, applies exit rules)
```bash
php bin/trade-monitor-runner.php
```

**3. Telegram Bot Runner** (Handles subscriber commands)
```bash
php bin/telegram-bot-runner.php
```

**4. Order Status Poller** (Updates order statuses)
```bash
php bin/order-status-poller.php
```

### Testing Scripts

#### Test Live Order Placement
```bash
# Place test order on all brokers
php bin/place-live-order-test.php --symbol BTCUSD --side SELL --amount 1

# Test with balance check bypass (for testnet)
php bin/place-live-order-test.php --symbol BTCUSD --side SELL --amount 1 --test
```

#### Check Configuration
```bash
php bin/check-live-trading-config.php
```

#### Test Telegram Notifications
```bash
# Test trade signals (all subscribers)
php bin/send-test-telegram.php

# Test order notifications (linked subscribers only)
php bin/test-order-notification.php
```

#### Link Telegram to Broker
```bash
php bin/link-telegram-to-broker.php
```

### Monitoring

#### View Logs
```bash
tail -f storage/logs/market-data.log
```

#### Check Active Trades
```sql
SELECT * FROM active_trades WHERE status = 'OPEN';
```

#### Check Recent Orders
```sql
SELECT * FROM orders ORDER BY created_at DESC LIMIT 10;
```

---

## 📱 TELEGRAM NOTIFICATIONS

### Two-Tier Notification System

#### Tier 1: Trade Signals (ALL Subscribers)
- Entry signals (SuperTrend flip on 90M)
- Exit signals (70% premium decay, SuperTrend flip, 13-hour limit)
- Sent to all active subscribers

#### Tier 2: Order Notifications (LINKED Subscribers Only)
- Order executed confirmations
- Order rejected notifications
- Filtered by broker code (DELTA, COINDCX)

### Bot Commands

#### `/start`
Subscribe to notifications. You'll receive:
- Trade signals (all users)
- Order notifications (if linked to broker)

#### `/status`
Check your subscription and broker linkage status.
Shows all linked broker accounts (many-to-many support).

#### `/unsubscribe`
Stop all alerts.

### Many-to-Many Broker Linking ✨

**New Feature**: One subscriber can link to multiple brokers, and multiple subscribers can monitor the same broker.

#### Linking to Broker Accounts

1. Subscribe to bot: Send `/start` in Telegram
2. Run linking script:
   ```bash
   php bin/link-telegram-to-broker-v2.php
   ```
3. Choose action:
   - **Action 1**: Link subscriber to broker (repeat for multiple brokers)
   - **Action 2**: Unlink subscriber from specific broker
   - **Action 3**: View all current links
4. Verify: Send `/status` to bot

#### Use Cases

**Personal Multi-Broker Monitoring**:
- Link your Telegram to both Delta and CoinDCX
- Receive order notifications from both exchanges

**Team Collaboration**:
- Multiple team members link to same broker account
- All receive the same order notifications
- Great for team coordination

### Notification Examples

**Trade Signal** (all subscribers receive):
```
🟢 SELL PUT (Bullish)

Symbol: BTCUSD
TF: 90
Price: 95000.0
Reason: SuperTrend (16, 1.5) flipped on 90m candle close
Mode: PAPER
```

**Order Notification** (only linked subscribers receive):
```
✅ ORDER EXECUTED

🟢 BUY
Symbol: BTCUSD
Quantity: 0.001
Price: 95000.0
Order ID: ORD_DELTA_123456
Broker: DELTA
Mode: LIVE
```

---

## 🧪 TESTING & VALIDATION

### Completed Tests
- ✅ Market data smoke tests
- ✅ Candle persistence tests
- ✅ SuperTrend calculation tests
- ✅ Indicator persistence tests
- ✅ Order execution flow tests
- ✅ Multi-exchange integration tests
- ✅ Live API connectivity tests
- ✅ Balance and currency conversion tests
- ✅ Complete trading flow tests
- ✅ WebSocket connection tests
- ✅ Telegram notification tests

### Test Locations
- `/tests/Smoke/` - Basic functionality tests
- `/tests/Integration/` - End-to-end tests
- `/bin/` - Operational and manual test scripts

---

## 🔐 SECURITY CONSIDERATIONS

1. **API Keys**: Stored in database `credentials` JSON field (encrypted recommended)
2. **Environment Variables**: Never commit `.env` to version control
3. **Testnet First**: Always test with TEST/TESTNET environments before LIVE
4. **Balance Checks**: Enforced for LIVE accounts (bypassed for TEST accounts)
5. **Rate Limiting**: Token bucket algorithm prevents API throttling

---

## 📊 PERFORMANCE METRICS

### Latency Targets
- Tick to Candle Aggregation: < 100ms
- Indicator Calculation: < 200ms
- Signal Generation: < 50ms
- Order Placement: < 1000ms (network dependent)

### Throughput
- Tick Processing: 100+ ticks/second
- Candle Aggregation: Real-time for up to 10 symbols
- Indicator Calculation: Multiple timeframes per symbol
- Order Execution: Multiple brokers in parallel

---

## 🚧 KNOWN LIMITATIONS

1. **React Dashboard**: Not yet implemented (CLI monitoring only)
2. **Multi-Strategy**: Single strategy (SuperTrend) currently supported
3. **Assets**: BTC only (ETH and others pending)
4. **Exchanges**: Delta and CoinDCX only
5. **Options Premium Feed**: Delta only (real-time), CoinDCX uses mock

---

## 🗺️ FUTURE ROADMAP

### Phase 1 (Completed)
- ✅ Core trading engine
- ✅ SuperTrend strategy
- ✅ Delta Exchange integration
- ✅ Options trading support
- ✅ Telegram notifications

### Phase 2 (Completed)
- ✅ CoinDCX integration
- ✅ Multi-exchange support
- ✅ Order status polling
- ✅ Rate limiting
- ✅ Enhanced logging

### Phase 3 (Pending)
- ⏳ React dashboard
- ⏳ Multi-strategy support
- ⏳ Portfolio management
- ⏳ Advanced analytics
- ⏳ ETH and other crypto support

---

## 🚨 TROUBLESHOOTING (Quick Reference)

### All Errors Showing? Run This First:
```bash
php bin/fix-all-errors.php
```
**Diagnoses everything and provides specific fixes**

### Common Issues:

#### 1. WebSocket Connection Failing
**Error**: `Connection dropped`, `testnet-socket.delta.exchange unreachable`

**Quick Fix** (works NOW, no changes):
```bash
php bin/demo-trading-runner.php
```

**Permanent Fix**:
```bash
# Switch to LIVE environment
php bin/switch-to-live-delta.php

# Then add to .env:
DELTA_API_KEY=your_live_key
DELTA_API_SECRET=your_live_secret
```

#### 2. Services Show No Output
**Problem**: Windows open but blank

**Fix**:
```bash
bin\start-all-visible.bat
```

#### 3. No Trading Happening
**Diagnose**:
```bash
php bin/check-trading-status.php
```

**Demo** (works immediately):
```bash
php bin/demo-trading-runner.php
```

---

## 🔧 DIAGNOSTIC & DEMO TOOLS

### Quick Error Fix (All-in-One) ⭐
```bash
# Diagnose ALL issues and get fixes
php bin/fix-all-errors.php

# Checks:
# - WebSocket connectivity
# - Database tables
# - Broker credentials  
# - Data availability
# - Provides specific fixes for each issue
```

### Live Trading Diagnosis
```bash
# Check why no trading is happening
php bin/check-trading-status.php

# Shows:
# - Candle aggregation status
# - Indicator calculation status  
# - Order history
# - Active trades
# - Root cause analysis
```

### Switch Delta Environment
```bash
# If testnet WebSocket is down, switch to LIVE
php bin/switch-to-live-delta.php

# Note: Requires LIVE credentials in .env
```

### Client Demo Tool ⭐
```bash
# Demonstrate end-to-end trading flow immediately
php bin/demo-trading-runner.php

# Features:
# - Uses real market data
# - Calculates indicators on existing candles
# - Simulates SuperTrend flips
# - Places real/paper orders
# - Complete visual output
# - NO WAITING - works NOW
```

**Use Cases**:
- ✅ Client presentations (show trading NOW)
- ✅ Testing end-to-end flow
- ✅ Verifying algorithm logic
- ✅ Training demonstrations

---

---

## 🔄 ENVIRONMENT MANAGEMENT

### Unified Environment Switcher

**Single script to switch ALL brokers between LIVE and TEST environments.**

#### Quick Commands

```bash
# Interactive mode (menu-driven)
php bin/switch-environment.php

# Direct commands
php bin/switch-environment.php --env=live --force
php bin/switch-environment.php --env=test --force

# Check current status
php bin/switch-environment.php --status

# API mode (JSON for frontend)
php bin/switch-environment.php --status --json
php bin/switch-environment.php --env=live --force --json
```

#### Parameters

| Parameter | Description |
|-----------|-------------|
| `--env=live\|test` | Target environment |
| `--json` | Return JSON output |
| `--broker=CODE` | Switch specific broker only |
| `--force` | Skip confirmation |
| `--status` | Show current status |

#### Environment Comparison

| Feature | TEST | LIVE |
|---------|------|------|
| **Money** | Virtual | Real ⚠️ |
| **Risk** | None | High |
| **WebSocket** | May be down | Stable |
| **API** | Testnet | Production |
| **Best for** | Development | Production |

#### Frontend Integration (JavaScript Example)

```javascript
// Get current status
async function getEnvironmentStatus() {
  const response = await fetch(
    'http://localhost/bitcoin/bin/switch-environment.php?status=1&json=1'
  );
  return await response.json();
}

// Switch to LIVE
async function switchToLive() {
  const response = await fetch(
    'http://localhost/bitcoin/bin/switch-environment.php?env=live&force=1&json=1'
  );
  const data = await response.json();
  
  if (data.success) {
    console.log('✅ Switched to LIVE:', data.data.brokers);
  } else {
    console.error('❌ Error:', data.message);
  }
  return data;
}

// Switch to TEST
async function switchToTest() {
  const response = await fetch(
    'http://localhost/bitcoin/bin/switch-environment.php?env=test&force=1&json=1'
  );
  return await response.json();
}
```

#### JSON Response Format

**Success Response:**
```json
{
  "success": true,
  "message": "Successfully switched to LIVE environment",
  "data": {
    "environment": "LIVE",
    "brokers_affected": 2,
    "brokers": [
      {
        "code": "DELTA",
        "name": "Delta Exchange",
        "environment": "LIVE",
        "api_url": "https://api.delta.exchange",
        "ws_url": "wss://socket.delta.exchange"
      }
    ]
  },
  "timestamp": "2026-01-21 19:30:00"
}
```

**Error Response:**
```json
{
  "success": false,
  "message": "Invalid environment",
  "data": {},
  "timestamp": "2026-01-21 19:30:00"
}
```

#### After Switching

Always restart services after switching environments:
```bash
bin\start-all-visible.bat
```

#### WebSocket Requirements

- **LIVE**: WebSocket required for real-time trading (stable)
- **TEST**: WebSocket may be unstable (use demo mode as fallback)
- **Demo Mode**: `php bin/demo-trading-runner.php` (works without WebSocket)

---

## 📝 CHANGELOG

### v2.2 (January 21, 2026)
- ✅ **Unified Environment Switcher**: Single script for all brokers
- ✅ **API-Ready Configuration**: JSON output for frontend
- ✅ **Database-Driven URLs**: API/WebSocket URLs in database
- ✅ **Consolidated Documentation**: Merged guides into main document

### v2.1 (January 21, 2026)
- ✅ **Service Launcher**: Single command to start all services (`start-all-services.php`)
- ✅ **Many-to-Many Telegram Linking**: One subscriber can link to multiple brokers
- ✅ **Service Management**: Status checking and graceful shutdown scripts
- ✅ **Team Support**: Multiple subscribers can monitor same broker account
- ✅ **Cross-Platform**: Works on Windows, Linux, Mac
- ✅ **Production Ready**: PID management, background execution

### v2.0 (January 21, 2026)
- ✅ Added Telegram broker-specific order notifications
- ✅ Added subscriber-to-broker account linking
- ✅ Enhanced bot commands (/start, /status, /unsubscribe)
- ✅ Added event dispatching to OrderExecutionEngine
- ✅ Added brokerCode to OrderResultDto
- ✅ Fixed SQL queries for broker_accounts table structure

### v1.11 (January 20, 2026)
- ✅ Added CoinDCX exchange support
- ✅ Implemented multi-exchange order routing
- ✅ Added currency conversion (USD/INR)
- ✅ Implemented balance checks with account environment awareness

### v1.10 (January 15, 2026)
- ✅ Core trading engine implementation
- ✅ SuperTrend strategy with options trading
- ✅ Delta Exchange integration
- ✅ Telegram basic notifications

---

## 🆘 TROUBLESHOOTING

### Common Issues

#### 1. WebSocket Connection Fails
**Problem**: Cannot connect to Delta WebSocket  
**Solution**: Check broker_accounts environment, ensure correct URL (testnet vs live)

#### 2. Order Rejected - Insufficient Funds
**Problem**: Balance check failing for testnet  
**Solution**: Use `--test` flag to bypass balance checks for TEST accounts

#### 3. Telegram Notifications Not Working
**Problem**: Bot not sending messages  
**Solution**: Check TELEGRAM_BOT_TOKEN, ensure bot is started with `/start` command

#### 4. No Active Trades
**Problem**: Algorithm not generating signals  
**Solution**: Check logs for SuperTrend flip detection, ensure 90M candles are closing

---

## 📚 ADDITIONAL RESOURCES

### API Documentation
- Delta Exchange: https://docs.delta.exchange/
- CoinDCX: https://docs.coindcx.com/

### Libraries
- Guzzle HTTP: http://docs.guzzlephp.org/
- Ratchet WebSocket: http://socketo.me/
- PHP dotenv: https://github.com/vlucas/phpdotenv

### Support
- Check logs: `storage/logs/market-data.log`
- Database queries: See "Monitoring" section above
- Test scripts: `/bin/` folder

---

**Document Version**: 2.0  
**Platform Version**: Production Ready  
**Last Verified**: January 21, 2026

