# 📖 System Technical Guide

This document provides a consolidated technical overview of the trading engine's internal logic, signal processing, and execution safety.

## 1. Event Flow & Foundation
The system operates on a strictly linear flow:
`Tick` -> `Candle Aggregator` -> `Indicator Engine` -> `Algorithm Engine` -> `Order Execution` -> `Notification`.

- **Single Threaded**: Ensuring that signals are processed in the exact order they arrive per process.
- **Idempotency**: Signal generation is gated by the `AlgorithmStateRepository`, which prevents duplicate signals for the same timeframe/trend state.
- **Locking**: Uses deterministic `PID` locks and database `ACTIVE` flags to ensure only one trade per symbol is open at any time.

## 2. Market Data & Options Handling
- **Reconstruction**: Candles are built from raw ticks to ensure real-time indicator accuracy.
- **Contract Resolution**: The `OptionStrikeResolverService` maps SuperTrend values to available strikes using a cached `option_products` master table.
- **Premium Threshold**: All entries require a minimum of **300 USD** premium. If not met, the engine skips the signal.

## 3. Exit Strategy Logic
The `TradeMonitorEngine` evaluates exit conditions in the following priority:
1. **Take Profit (70% Decay)**: If the option premium drops to 30% of its entry value, the trade exits immediately.
2. **Trailing Stop Loss**: Active only on **Expiry Day**. If the premium rises 15% from its lowest seen point, the trade exits.
3. **SuperTrend Flip**: If the 30M or 45M SuperTrend flips direction against the trade, an exit signal is triggered.
4. **Time-Based Exit**: Hard exit after **13 hours** of trade duration.

## 4. Reconciliation & Recovery
- **Boot Sync**: On startup, the `StartupReconciliationService` fetches open positions from Delta Exchange and reconciles them with the `active_trades` table.
- **State Persistence**: Current candle progress is saved to the database on every tick, allowing the system to resume accurately after a crash or restart.

## 5. Multi-Exchange Multicast
The `OrderExecutionEngine` allows for **Multicast Execution**. A single signal (e.g. `BUY BTCUSD`) can be automatically routed to multiple active accounts (e.g. CoinDCX, Delta Testnet, and Delta Live) simultaneously.
