Ta4j Wiki

Documentation, examples and further information of the ta4j project

View the Wiki On GitHub

This project is maintained by ta4j Organization

Stop Loss and Stop Gain Rules

ta4j now provides a full stop-rule toolkit that covers fixed %, fixed amount, trailing variants, and volatility/ATR-adaptive variants for both loss and gain exits.

Use this page as the operational guide for:

Rule families

Fixed percentage (classic)

These use percentage distance from entry (or favorable move for trailing variants).

Best when:

Fixed amount (flat-dollar / flat-price-distance)

These use an absolute price distance (for example: $10 from reference).

Best when:

Volatility-driven

These use a dynamic threshold based on volatility indicators (typically ATR multiplied by a coefficient).

Best when:

Quick selection guide

How to wire exits

ClosePriceIndicator close = new ClosePriceIndicator(series);
ATRIndicator atr = new ATRIndicator(series, 14);

Rule riskExit = new AverageTrueRangeTrailingStopLossRule(close, atr, 2.0)
        .or(new AverageTrueRangeTrailingStopGainRule(close, atr, 3.0))
        .or(new StopLossRule(close, series.numFactory().numOf(1.5))); // hard fail-safe

Rule signalExit = new CrossedDownIndicatorRule(fast, slow);
Rule exitRule = signalExit.or(riskExit);

Strategy strategy = new BaseStrategy(entryRule, exitRule);

Notes:

Using stop-price models for risk analytics

Several rules implement:

This lets you query stop prices directly (for example in risk budgeting or custom position sizing flows) without duplicating threshold math.

Live trading usage patterns

1) Match your reference price to execution reality

2) Decide bar-close vs intrabar evaluation

Pick one model explicitly and keep it consistent between research and production.

3) Protect against gaps and slippage

4) Avoid stop churn

5) Keep a stop hierarchy

Do not rely on a single mechanism.

Parameter tuning tips

Practical tuning workflow:

  1. Optimize for robustness first, not max return.
  2. Validate on multiple volatility regimes.
  3. Compare with realistic fees/slippage.
  4. Stress test gap days and high-spread windows.

Common mistakes

Live deployment checklist

See also: