Learn the components of a trading system
6.1.2· Stock-Market › Algorithmic & Quant Trading
Overview
Ek trading system ek complete, automated framework hota hai jo predefined rules ke basis par trades execute karta hai, bina kisi human intervention ke. Iske components ko samajhna bahut zaroori hai kyunki har piece ek specific failure mode handle karta hai algorithmic trading mein—data errors, execution delays, risk breaches, ya logic bugs.
YE components kyun matter karte hain: Manual trading scale par fail hoti hai emotion, speed limits, aur inconsistency ki wajah se. Ek systematic approach concerns ko alag karta hai: data → logic → execution → monitoring, jisse aap har ek piece ko independently test, optimize, aur debug kar sako.
Core Components
1. Data Management Layer
Data handling alag kyun rakhen?
- Market data dirty aati hai (missing ticks, spikes, delayed timestamps)
- Strategies ko multiple timeframes/assets synchronized chahiye hote hain
- Backtesting ke liye historical data identical format mein chahiye hota hai jaise live data mein hoti hai
HOW it works:
Raw Feed → Validation → Normalization → Storage → API
(check gaps) (align timestamps) (DB/cache) (serve strategy)
Raw: AAPL shows price jump from 1500 → $151 in 1 second
def clean_tick(current, previous, threshold=0.10): """Remove ticks > 10% move (likely error)""" if abs(current - previous)/previous > threshold: return previous # Hold last valid price return current
Why this step? Without cleaning, a strategy might:
- Trigger false breakout signal
- Calculate wrong volatility
- Execute at phantom price
**Key data types**:
1. **Tick data**: Har trade/quote (L1 data)
2. **OHLCV bars**: Aggregated candles (1min, 5min, daily)
3. **Order book**: Bid/ask depth (L2/L3 data)
4. **Reference data**: Symbols, contract specs, corporate actions
> [!mistake]
> **Galti**: Backtest aur live ke liye alag data sources use karna.
> **Kyun sahi lagta hai**: Vendor X ka historical data clean hai; broker Y ka live feed convenient hai.
> **Trap**: Vendor X splits/dividends ke liye retroactively adjust karta hai; broker Y nahi karta → backtest mein 50% return dikhta hai, live mein paisa jaata hai.
> **Fix**: Dono ke liye identical data pipeline use karo, ya explicitly adjustments reconcile karo.
---
### 2. Strategy Engine
> [!definition]
> ==Strategy engine== mein trading logic hoti hai: signal generation, parameter calculations, aur decision rules. Yeh answer karta hai: "Current state diye hue, kya mujhe enter/exit/hold karna chahiye?"
**Strategy code alag kyun rakhen?**
- **A/B testing** multiple strategies ko parallel mein enable karta hai
- Research (strategy dev) ko engineering (infrastructure) se alag karta hai
- Live systems ko touch kiye bina backtesting allow karta hai
**HOW a strategy operates** (example: Mean Reversion):
**Step 1: Signal calculate karo**
```python
# Moving average deviation strategy
price = data['close']
ma_20 = price.rolling(20).mean()
std_20 = price.rolling(20).std()
z_score = (price - ma_20) / std_20 # Deviation in standard deviations
# Signal: -1 (sell), 0 (neutral), +1 (buy)
signal = np.where(z_score < -2, 1, # Price 2σ below mean → buy
np.where(z_score > 2, -1, 0)) # Price 2σ above → sell
Yeh step kyun?
- z_score alag stocks/volatility regimes mein price deviation ko normalize karta hai
- -2/+2 thresholds frequency (kam signals) vs conviction (zyada strong deviations) ke beech balance banate hain
Step 2: Position sizing
# Kelly Criterion: optimal fraction = edge / odds
win_rate = 0.55 # Historical: 55% of mean-reversion trades profit
avg_win = 0.02 # Average return when right: +2%
avg_loss = 0.015 # Average loss when wrong: -1.5%
kelly_fraction = (win_rate * avg_win - (1 - win_rate) * avg_loss) / avg_win
# = (0.55*0.02 - 0.45*0.015) / 0.02= 0.2125
position_size = account_value * kelly_fraction * signalYeh step kyun?
- Fixed dollar amounts changing account size aur risk ko ignore karte hain
- Full Kelly aggressive hota hai; traders safety ke liye half-Kelly use karte hain
- Signal strength (z_score magnitude) position ko aur scale kar sakti hai
Problem: 5-min chart buy dikhata hai, lekin 1-hour downtrend mein hai → likely false signal
def multi_timeframe_signal(data5m, data_1h): # Short-term: mean reversion z_5m = calculate_zscore(data_5m, window=20) signal_5m = 1 if z_5m < -2 else 0
# Long-term: trend filter
ma_fast1h = data_1h['close'].rolling(20).mean()
ma_slow_1h = data_1h['close'].rolling(50).mean()
uptrend_1h = ma_fast_1h > ma_slow_1h
# Only take5m buy signals if1h trend agrees
return signal_5m if uptrend_1h else 0
Why? Downtrends ke andar ranging markets mein whipsaws kam karta hai
---
### 3. Risk Management Module
> [!definition]
> ==Risk management module== losses, position sizes, aur exposure par hard limits enforce karta hai **orders market tak pahunchne se pehle**. Yeh system ka circuit breaker hai.
**Risk controls mandatory kyun hain?**
- Strategy code mein ek bug seconds mein account drain kar sakta hai
- Flash crashes temporary mispricings create karte hain jo mass liquidations trigger karte hain
- Regulatory requirements (brokers risk limits demand karte hain)
**HOW risk checks work** (sequence mein execute hote hain):
> [!formula]
> **Pre-trade risk checks:**
1. **Position limit**:
$$\text{Proposed position} \leq \text{Max position per symbol}$$
Concentration risk rokta hai (e.g., ek stock mein max 10% portfolio).
2. **Portfolio delta**:
$$\Delta_{\text{portfolio}} = \sum_{i=1}^{n} \text{position}_i \times \frac{\partial P_i}{\partial S_i}$$
jahan $P_i$ = position value, $S_i$ = underlying price. Directional exposure limit karta hai.
3. **Value-at-Risk (VaR)**:
$$\text{VaR}_{95} = \mu_{\text{portfolio}} - 1.645 \times \sigma_{\text{portfolio}}$$
1 din mein 95% confidence ke saath max loss estimate karta hai. VaR limit se upar jaane wale trades reject karta hai.
4. **Drawdown check**:
$$\text{Current drawdown} = \frac{\text{Equity}_{\text{peak}} - \text{Equity}_{\text{current}}}{\text{Equity}_{\text{peak}}}$$
Agar $> \text{max allowed}$ (e.g., 15%), toh naye trades rok do.
**Post-trade monitoring**:
- **Stop-loss**: Auto-exit karo agar position X% lose kare (bachata hai "hope it recovers" wali soch se)
- **Time-based exit**: N periods se zyada held positions close karo (dead capital rokta hai)
> [!example]
> **Example: Risk module ek trade reject karta hai**
> ```python
> class RiskManager:
> def __init__(self, max_position_pct=0.10, max_drawdown=0.15):
> self.max_position_pct = max_position_pct
> self.max_drawdown = max_drawdown
> self.equity_peak = 1000
def check_trade(self, proposed_value, current_equity portfolio_value):
# Check 1: Position size
position_pct = abs(proposed_value) / portfolio_value
if position_pct > self.max_position_pct:
return False, f"Position {position_pct:.1%} exceeds {self.max_position_pct:.1%}"
# Check 2: Drawdown
drawdown = (self.equity_peak - current_equity) / self.equity_peak
if drawdown > self.max_drawdown:
return False, f"Drawdown {drawdown:.1%} exceeds limit"
return True, "Approved"
# Usage
rm = RiskManager()
approved, msg = rm.check_trade(
proposed_value=15000, # $15k ka stock khareedna chahte hain
current_equity=85000, # Account $100k peak se neeche
portfolio_value=100000
)
# Result: False, "Drawdown 15.0% exceeds limit" → trade blocked
Yeh step kyun? Pre-trade checks ke bina, strategy yeh kar sakti hai:
- $100k account mein $50k position calculate kare (overleveraged)
- Ignore kare ki account pehle se 20% down hai (drawdown rule violate)
- Order through karae, phir margin call face kare
4. Execution Engine
Execution alag kyun rakhen?
- Strategy kehti hai "10,000 shares kharido"; execution decide karta hai "kaise, kab, aur kahan"
- $1M market order price aapke against move karta hai (slippage)
- Alag venues (exchanges, dark pools) alag liquidity offer karte hain
HOW execution strategies work:
-
Market order: Current price par immediate fill
- Use case: Chhota size, urgent entry (e.g., breaking news)
- Cost: Spread pay karta hai + potential slippage
-
Limit order: Sirf specified price ya better par fill
- Use case: Bada size, patient entry
- Risk: Fill na ho (adverse selection—price door chali jaaye)
-
VWAP (Volume-Weighted Average Price): Historical volume distribution match karne ke liye order ko din bhar mein slice karo.
Kyun? Natural flow mein "hide" karke market impact minimize karta hai.
-
TWAP (Time-Weighted Average Price): Har N minutes mein equal slices execute karo.
Kyun? Simple, predictable, acha hai jab volume profile flat ho.
4 ghante mein 50,000 shares khareedne hain
Historical volume profile: hour 1 mein 30%, hour 2 mein 40%, hour 3 mein 20%, hour 4 mein 10%
total_shares = 50000 volume_profile = [0.30, 0.40, 0.20, 0.10]
order_slices = [int(total_shares * pct) for pct in volume_profile]
[15000, 20000, 10000, 5000]
Execution:
for hour, shares in enumerate(order_slices, 1): # Us ghante ke liye 12 orders mein aur split karo (har 5 min) shares_per_interval = shares // 12 for interval in range(12): place_limit_order(shares_per_interval, limit_price=get_mid_price()) wait(5 * 60) # 5 minutes
Yeh step kyun?
- Market rhythm match karta hai (low impact)
- "Large buyer here" signal karne se bachta hai jo frontrunners exploit karte hain
- Mid-price par limit orders spread capture karte hain (vs market orders jo spread pay karte hain)
**Slippage calculation**:
$$\text{Slippage} = \text{Average fill price} - \text{Decision price}$$
Agar aapne \$100 par buy decide kiya, lekin fills average \$100.20 rahi → 20¢ slippage × 50,000 shares = **\$10,000 hidden cost**.
---
### 5. Monitoring & Logging
> [!definition]
> ==Monitoring system== live performance, system health, aur anomalies ko real-time mein track karta hai. ==Logging== har decision, order, aur fill ko post-mortem analysis ke liye record karta hai.
**Yeh critical kyun hai?**
- Live trading mein koi "undo" nahi hota—failures seconds mein detect karne padenge
- Post-trade analysis ke liye exact reconstruction chahiye ki kya hua
- Regulatory audits complete order trails demand karte hain
**KYA monitor karna hai**:
1. **Performance metrics**:
- P&L (realized + unrealized)
- Sharpe ratio: $\frac{\text{Mean return}}{\text{Std dev of returns}}$ (risk-adjusted return)
- Win rate, avg win/loss, max drawdown
2. **System health**:
- Latency (data arrival se order submission tak)
- Fill rates (orders executed / orders placed)
- Data gaps (missed ticks)
3. **Anomaly detection**:
- Sudden volatility spike (circuit breaker trigger)
- Order rejections (margin, halts)
- Position drift (actual vs intended)
> [!example]
> **Example: Real-time alert system**
> ```python
> class Monitor:
> def __init__(self):
> self.alerts = []
def check_system(self, state):
# Alert 1: High latency
if state['latency_ms'] > 100:
self.alert(f"HIGH LATENCY: {state['latency_ms']}ms (threshold: 100ms)")
# Alert 2: Unexpected position
expected_pos = state['strategyposition']
actual_pos = state['broker_position']
if abs(expected_pos - actual_pos) > 10:
self.alert(f"POSITION DRIFT: Expected {expected_pos}, actual {actual_pos}")
# Alert 3: Drawdown breach
if state['drawdown'] > 0.15:
self.alert(f"DRAWDOWN LIMIT: {state['drawdown']:.1%}")
return "HALT_TRADING"
def alert(self, message):
# Email, Slack, SMS par bhejo
print(f"[ALERT] {message}")
self.alerts.append((datetime.now(), message))
# Yeh checks kyun?
# - High latency → stale data → galat signals
# - Position drift → partial fills, ya execution bug
# - Drawdown breach → gadhhe mein aur khudaai mat karo
Log structure (har order ka):
timestamp, symbol, signal, order_id, order_type, quantity, limit_price, fill_qty, slippage, reason
Is se aisa sawaal poochha ja sakta hai: "Maine XYZ 10:23 par kyun kharida?" → Log check karo → Signal z_score = -2.3 tha, limit $100, filled $100.15.
System Architecture
Critical timing constraint:
jahan = wo time jiske baad aapka signal public knowledge ban jaata hai. HFT ke liye yeh microseconds hota hai; daily strategies ke liye minutes acceptable hain.
Practical Considerations
Backtesting vs Live: The Gap
Yeh kyun hota hai:
- Look-ahead bias: Future data use karna (e.g., 9:30 AM par daily close)
- Survivorship bias: Sirf listed stocks par backtest (bankruptcies ignore karna)
- Overfitting: Strategy historical noise ke liye tune ki gayi, real patterns ke liye nahi
- Transaction costs: Backtest slippage, fees, spread ignore karta hai
Fix checklist:
- Backtest sirf point-in-time data use kare
- Realistic slippage model include kare (e.g., 0.05% per trade)
- Out-of-sample period par test kare (dev ke dauran test data mat chhuao)
- Bid-ask spread assume kare (backtest mein kabhi mid-price par trade mat karo)
- Failed orders account kare (10% limits fill nahi hote)
Latency Budgets
Alag strategy speeds ke liye:
| Strategy Type | Data Freq | Max Latency | Infra Needs |
|---|---|---|---|
| Daily swing | EOD bars | Minutes | Cloud server theek hai |
| Intraday mean-rev | 1-min bars | 1-5 seconds | Co-located server |
| High-frequency | Tick-by-tick | <1 millisecond | FPGA, direct exchange feed |
Latency kyun matter karta hai: Ek mean-reversion strategy mein, agar aapka signal $100 par trigger hota hai lekin delay ki wajah se $100.10 par execute hota hai, toh aap pehle se 0.1% lose kar chuke—potentially aapka poora edge.
Recall
Ek 12-saal ke baache ko samjhao:
Socho tum ek lemonade stand chala rahe ho, lekin tum decide karne ki jagah tune ek robot banaya jo automatically karta hai.
Data Management = Robot ki aankhein aur kaan. Yeh mausam dekh ta hai (garmi = zyada sales), paas se guzarne wale customers count karta hai, aur kal ki sales yaad rakhta hai.
Strategy Engine = Robot ka dimaag. Iske rules hain jaise: "Agar temperature > 30°C AUR Saturday hai AUR hmare paas lemons hain, toh 50 cups banao."
Risk Management = Safety rules. "Kabhi bhi apna aadhe se zyada paisa lemons par mat lagao" aur "Agar 3 din se lagatar paisa gaya, toh break lo."
Execution = Robot ke haath. Yeh ek baar mein saare 50 cups nahi rakhta—10-10 cups rakhta hai taaki thande aur fresh rahein.
Monitoring = Logbook. Yeh likhta hai: "10AM: 10 cups banaye. 10:15 AM: 7 cups bech diye. Temperature 32°C ho gaya. Agli batch 12 cups kar di."
Agar ek part kharab ho jaaye (maan lo thermometer kaam karna band kar de), poora robot crash nahi hota—bas ek backup rule pe aa jaata hai jaise "Saturday ka average amount banao."
- Data: Fuel
- Strategy: Dimaag
- Risk: Brakes
- Execution: Haath
- Monitoring: Aankhein
Connections
- 6.1.01-Introduction-to-Algorithmic-Trading - Hamen systematic trading kyun chahiye
- 6.1.03-Backtesting-Strategies - Live deployment se pehle strategies test karna
- 6.1.05-Order-Typesand-Execution - Execution layer mein deep dive
- 6.2.01-Market-Microstructure - Exchanges orders kaise process karte hain
- 6.3.01-Risk-Management-in-Algo-Trading - Advanced risk controls
#flashcards/stock-market
Ek trading system ke 5 core components kya hain? :: 1) Data Management Layer 2) Strategy Engine 3) Risk Management Module 4) Execution Engine 5) Monitoring & Logging