Skip to content

03 Modules Risk Management

Łukasz Rafał Czarnacki edited this page Mar 9, 2026 · 1 revision

Risk Management

Source package: src/trade_lab/risk_management

TradeLab separates risk policies from strategy generation. Strategies attach risk objects as plain attributes, and BacktestEngine consumes them when positions are opened and updated.

Source files

  • base.py
  • take_profit.py
  • stop_loss.py
  • trailing_stop.py

Base contracts

  • BaseTakeProfit.compute(entry_price, direction, signal_strength, bar) -> float | None
  • BaseStopLoss.compute(entry_price, direction, signal_strength, bar) -> float | None
  • BaseTrailingStop.compute_initial(...) -> float | None
  • BaseTrailingStop.update(current_stop, direction, signal_strength, bar) -> float

Trailing stops also share step_points, which prevents tiny stop updates unless the new stop improves by at least that amount.

Built-in take-profit policies

  • FixedTP(base_points): fixed offset from entry
  • SignalStrengthTP(base_points): offset scales with abs(signal_strength)

Built-in stop-loss policies

  • FixedSL(base_points): fixed offset from entry
  • SignalStrengthSL(base_points): offset scales with abs(signal_strength)
  • MovingAverageSL(column): uses an existing DataFrame column on the current bar
  • ParabolicSARSL(...): uses bar["sar"] if available, otherwise seeds a SAR-like level from the current bar

Built-in trailing stops

  • FixedTS(base_points, step_points=10.0)
  • SignalStrengthTS(base_points, step_points=10.0)
  • MovingAverageTS(column, step_points=10.0)
  • ParabolicSARTS(af_start=0.02, af_step=0.02, af_max=0.2, step_points=10.0)

Engine behavior

  • TP, SL, and TS exits are evaluated before threshold-based signal exits.
  • For a long trade, the effective stop is the tighter of stop-loss and trailing-stop.
  • For a short trade, the effective stop is the tighter upper bound.
  • trade_log.exit_reason records tp, sl, ts, or signal.

Typical usage

from trade_lab.risk_management import FixedSL, FixedTP, SignalStrengthTS

strategy.take_profit = FixedTP(base_points=8.0)
strategy.stop_loss = FixedSL(base_points=5.0)
strategy.trailing_stop = SignalStrengthTS(base_points=6.0, step_points=1.0)

MQL5 export notes

  • Directly exportable: FixedTP, SignalStrengthTP, FixedSL, SignalStrengthSL, FixedTS, SignalStrengthTS
  • Warning-only/manual mapping: MovingAverageSL, MovingAverageTS, ParabolicSARSL, ParabolicSARTS

See MQL5 Export.

Clone this wiki locally