# Trading Engine & Order Lifecycle

This document explains the order matching engine, supported segments (Equity, F&O, Crypto), contests, and the background cache warming systems.

---

## 1. Core Trading Segments

The engine processes orders across three distinct financial segments, each with unique routing and matching properties:

| Segment | Database Representation | Execution Style | Live Data Source |
|---|---|---|---|
| **Equity** | Segment ID/Symbol | Immediate / Limit matching | Kite Connect API (Zerodha) |
| **NFO (F&O)** | Derivative Symbols | Contracts matching | Kite Connect API (Zerodha) |
| **Crypto** | USDT pairs (e.g. BTCUSDT) | Immediate execution | Binance API |

---

## 2. Order Lifecycle and State Transitions

```mermaid
stateDiagram-v2
    [*] --> PENDING : Order Placed (Limit/Market)
    PENDING --> EXECUTED : Price matches LTP (Limit Order)
    PENDING --> CANCELLED : Cancelled by User
    PENDING --> EXPIRED : Market closes / Validity expires
    EXECUTED --> OPEN_POSITION : Position Created
    OPEN_POSITION --> CLOSED_POSITION : Position Exited
```

### Route Operations

* **Add Order:** `/api/add-order` & `/api/contest-order`
  * Checks margin validation (ensures user has sufficient `balance`).
  * If `TRADING_GRPC_ENABLED=true` is enabled, the Node API proxies this request over gRPC to the `grpc-engine` (Port 50051), which executes under MySQL transactions with explicit locks.
  * If order is `market`, it executes immediately at the current Last Traded Price (LTP).
  * If order is `limit`, it is saved as `PENDING` until price matches.
* **Modify Order:** `/api/modify-order`
  * Updates the price or quantity parameters of a pending order.
* **Cancel Order:** `/api/cancel-order`
  * If `TRADING_GRPC_ENABLED=true` is enabled, proxies the request to `grpc-engine` over gRPC.
  * Checks permissions, cancels the pending order in a database transaction, deletes cache entries, and pushes a cache-refresh event to the Redis stream `stream:trading-terminal-refresh`.
* **Combined Margin:** `/api/combined-margin-order`
  * If `TRADING_GRPC_ENABLED=true` is enabled, delegates the margin calculations to the gRPC service to offload the event loop from the main API processes.
* **Exit Position:** `/api/exit-position`
  * Closes an open position at the market price, calculating realized Profit/Loss (P&L) and releasing margin back to the user's balance.

---

## 3. Contest Management & Join Logic

Users participate in virtual paper-trading contests to win real or virtual rewards.

```mermaid
sequenceDiagram
    participant User as User Mobile Client
    participant API as Node.js API
    participant DB as MySQL DB
    
    User->>API: POST /api/join-contest (contestId, apptoken)
    API->>DB: Check if contest exists and registration is open
    alt Not enough balance or contest full
        API-->>User: Return failure error response
    else Valid registration
        API->>DB: Deduct entry fee from user account balance
        API->>DB: Insert record in contest_join
        API->>DB: Increment contest_joined count in users table
        API-->>User: Return success response
    end
```

---

## 4. Background Workers & Cache Warming

Due to the heavy database query load of compiling user portfolios, open positions, closed positions, and pending orders for the UI, the engine utilizes Redis caching heavily.

### Cache Key Format
* Trading Terminal Summary: `cache:trading-terminal:${uid}:${segment}` (e.g. `cache:trading-terminal:67337:all`)

### Worker Processes (`ecosystem.config.js`)

1. **Terminal Cache Preloader (`terminal_cache_preloader.js`)**
   * **Cron Schedule:** Every hour.
   * **Operation:**
     1. Queries the `user_activity` table for users active today (`active_date = CURDATE()`).
     2. Sequentially pre-warms the trading terminal summaries in Redis for active users by calling the trading terminal logic in the background.
     3. Pre-warms the `apptoken:uid:${apptoken}` session cache mappings.
