Jump to content

Component:Trade Execution

From PlusEV Wiki Page
Revision as of 11:17, 8 January 2026 by 152.57.133.55 (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Trade Execution Engine

[edit]

Purpose

[edit]

"How do we execute & manage trade to protect capital & maximize profit?"

This component is the executor. It takes signals from Layer 4 and:

  1. Converts signals to trades with realistic slippage
  2. Monitors open positions (stop, target, time)
  3. Manages stops dynamically (breakeven, trailing)
  4. Calculates complete P&L with all costs

Trading Market Principle

[edit]

"Let winners run, cut losers short. Protect profits once we have them."

  • Breakeven stop = protect capital once trade is working → move stop to entry at 25pt profit
  • Trailing stop = let winners run → trail stop behind price using ATR
  • Time exit = don't hold losing trades forever → 8 hour maximum
  • Slippage modeling = realistic execution → winners don't fill perfectly either

Trade Lifecycle

[edit]
        ┌───────────────────────────────────────┐
        │  Signal from Layer 4                  │
        │  (Direction, Entry, Stop, Target)     │
        └───────────────────────────────────────┘
                         │
                         ▼
        ┌───────────────────────────────────────┐
        │  ENTRY EXECUTION                      │
        │  • Add entry slippage (1-2 pts)       │
        │  • Calculate costs (commission + CTT) │
        │  • Create Trade object                │
        └───────────────────────────────────────┘
                         │
                         ▼
        ┌───────────────────────────────────────┐
        │  POSITION MANAGEMENT (per bar)        │
        │                                       │
        │  1. Update MFE/MAE tracking           │
        │  2. Check breakeven activation (25pt) │
        │  3. Update trailing stop (ATR-based)  │
        │  4. Check stop hit                    │
        │  5. Check target hit                  │
        │  6. Check time exit (8 hours)         │
        └───────────────────────────────────────┘
                         │
                         ▼
        ┌───────────────────────────────────────┐
        │  EXIT EXECUTION                       │
        │  • Add exit slippage (stop=2pt, TP=0.5pt)│
        │  • Calculate final P&L                │
        │  • Record exit reason                 │
        └───────────────────────────────────────┘

Two-Phase Stop Management

[edit]

Phase 1: Breakeven Stop

[edit]

Once trade is profitable by 25 points, move stop to entry price + buffer:

IF current_profit >= 25 points:

    LONG:  stop = entry_price + 2 (buffer)
    SHORT: stop = entry_price - 2 (buffer)

Purpose: Lock in a no-loss trade (or small profit with buffer).

Phase 2: Trailing Stop

[edit]

After profit exceeds activation threshold, trail stop behind price:

Trailing Distance = ATR × 2.0 (minimum 15 points)

LONG:
    IF profit >= 20 points:
        new_stop = current_high - trailing_distance
        IF new_stop > current_stop:
            current_stop = new_stop  // Only moves UP

SHORT:
    IF profit >= 20 points:
        new_stop = current_low + trailing_distance
        IF new_stop < current_stop:
            current_stop = new_stop  // Only moves DOWN

Purpose: Let winners run while protecting accumulated profit.


ATR Calculation

[edit]

ATR (Average True Range) measures volatility for adaptive trailing:

True Range = max(
    high - low,
    |high - previous_close|,
    |low - previous_close|
)

ATR = average(True Range over 14 bars)

Trailing Distance = ATR × 2.0

Effect:

  • High volatility → wider trailing stop (more room to breathe)
  • Low volatility → tighter trailing stop (protect more profit)

Slippage Model

[edit]

Realistic slippage based on market conditions:

Entry Slippage

[edit]
entry_slippage = base (1.0 pt)
               + position_impact (0.1 × lots, capped at 2.0)
               + volatility (0.5 pt)

Minimum: 0.5 points

Exit Slippage

[edit]
Exit Type Slippage Reason
Stop Loss 2.0 points Panic selling, worse fills
Take Profit 0.5 points Limit order, better fills
Time Exit 0.0 points Market order at close

MFE/MAE Tracking

[edit]

Tracks Maximum Favorable and Adverse Excursion for each trade:

Metric What It Measures Usage
MFE Best profit point reached during trade Entry timing quality
MAE Worst loss point during trade Stop placement optimization
LONG:
    MFE = max profit seen = (highest_high - entry) × 100 × lots
    MAE = max loss seen = (lowest_low - entry) × 100 × lots

SHORT:
    MFE = max profit seen = (entry - lowest_low) × 100 × lots
    MAE = max loss seen = (entry - highest_high) × 100 × lots

Exit Conditions

[edit]

Trades exit when any condition is met (checked in order):

Priority Condition Exit Price Reason Code
1 Stop hit stop_price - slippage (LONG) "stop"
2 Target hit target_price - slippage (LONG) "target"
3 Time limit (8 hours) current_close "timeout"

Configuration

[edit]
Parameter Value Description
base_slippage_points 1.0 Base entry slippage
market_impact_factor 0.1 Slippage per lot
max_market_impact_slippage 2.0 Cap on position slippage
stop_loss_slippage 2.0 Additional slippage on stops
take_profit_slippage 0.5 Reduced slippage on targets
max_holding_period_minutes 480 8 hours max holding
enable_trailing_stop True Enable trailing stop
trailing_stop_method "ATR_MULTIPLE" ATR-based or fixed
atr_period 14 ATR lookback period
atr_multiplier 2.0 Trailing = ATR × 2
enable_breakeven_stop True Enable breakeven
breakeven_activation 25.0 Points profit to activate
breakeven_buffer 2.0 Buffer above/below entry
max_concurrent_trades 3 Maximum open positions

Output

[edit]

Trade Object (after exit):

Field Type Description
entry_price float Actual entry (with slippage)
exit_price float Actual exit (with slippage)
exit_reason str "stop", "target", "timeout"
gross_pnl_inr float P&L before costs
net_pnl_inr float P&L after commission + CTT
brokerage_cost float Commission paid
tax_cost float CTT paid
max_favorable_excursion_inr float Best P&L during trade
max_adverse_excursion_inr float Worst P&L during trade
current_stop_price float Final stop (after trailing)

Dependencies

[edit]

Upstream:

Uses:

  • SignalGenerationTradeManagement.execute_signal() - For entry
  • SignalGenerationTradeManagement.close_trade() - For exit

Quick Reference

[edit]
Event Action
New signal received Execute with slippage, create trade
Profit reaches 25pt Move stop to breakeven (entry + 2pt)
Profit reaches 20pt Start trailing stop (ATR × 2)
Price hits stop Exit with 2pt slippage, reason="stop"
Price hits target Exit with 0.5pt slippage, reason="target"
8 hours elapsed Exit at market, reason="timeout"
Higher high (LONG) Trail stop up if trailing active
Lower low (SHORT) Trail stop down if trailing active