Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ta4j/ta4j/llms.txt

Use this file to discover all available pages before exploring further.

Stop rules exit an open position when the price moves by a defined amount against (stop-loss) or in favor of (stop-gain) the trade. All stop rules implement Rule and use the tradingRecord to read the entry price of the current position.
All stop rules evaluate against the current open position’s entry price. They return false when no position is open.

Fixed stop rules

Exits when the current price drops (for long) or rises (for short) by more than lossPercentage from the entry price.Constructor signatures:
new StopLossRule(Indicator<Num> priceIndicator, Number lossPercentage)
new StopLossRule(Indicator<Num> priceIndicator, Num lossPercentage)
Parameters:
ParameterDescription
priceIndicatorThe price series to compare — typically ClosePriceIndicator
lossPercentageMaximum acceptable loss as a percentage (e.g., 2.0 for 2%)
ClosePriceIndicator close = new ClosePriceIndicator(series);
Rule stopLoss = new StopLossRule(close, 2.0);   // exit if price falls 2% from entry
Exits when the current price rises (for long) or falls (for short) by more than gainPercentage from the entry price.Constructor signatures:
new StopGainRule(Indicator<Num> priceIndicator, Number gainPercentage)
new StopGainRule(Indicator<Num> priceIndicator, Num gainPercentage)
Parameters:
ParameterDescription
priceIndicatorThe price series to compare
gainPercentageTarget gain as a percentage (e.g., 5.0 for 5%)
Rule stopGain = new StopGainRule(close, 5.0);   // exit when price gains 5% from entry
Exits when the price moves against the position by a fixed absolute amount (not a percentage).
// Exit if price falls $50 from the entry price
new FixedAmountStopLossRule(close, series.numFactory().numOf(50))
Exits when the price moves in favor of the position by a fixed absolute amount.
// Exit when price gains $100 from the entry price
new FixedAmountStopGainRule(close, series.numFactory().numOf(100))
A trailing stop that tracks the highest (long) or lowest (short) price seen since entry and exits if the price retraces by lossPercentage from that peak.Constructor signatures:
// Uses all bars since entry
new TrailingStopLossRule(Indicator<Num> indicator, Num lossPercentage)

// Limits lookback to the last barCount bars
new TrailingStopLossRule(Indicator<Num> indicator, Num lossPercentage, int barCount)
Parameters:
ParameterDescription
indicatorTypically ClosePriceIndicator
lossPercentageRetracement percentage from the peak/trough
barCount(Optional) Maximum lookback window; defaults to all bars since entry
// Trail stop: exit if price falls 3% from the highest close since entry
Rule trailingStop = new TrailingStopLossRule(close, series.numFactory().numOf(3));
Trailing stop based on a fixed absolute distance from the highest (long) or lowest (short) price since entry.
new TrailingFixedAmountStopLossRule(close, series.numFactory().numOf(50))
Exits when the price retraces by a fixed absolute amount from the most favorable price reached since entry.
new TrailingFixedAmountStopGainRule(close, series.numFactory().numOf(25))
Exits when the price retraces by retracementPercentage from the most favorable price reached since entry — locking in profits as the position moves in your favor.
// Exit when price pulls back 2% from its peak gain
new TrailingStopGainRule(close, series.numFactory().numOf(2))

ATR-based stop rules

These rules scale the stop distance dynamically using the Average True Range (ATR), adapting to current market volatility.
Sets the stop distance as atrCoefficient × ATR(atrBarCount) below the entry price.Constructor signatures:
// Uses close price as reference
new AverageTrueRangeStopLossRule(BarSeries series, int atrBarCount, Number atrCoefficient)

// Custom reference price
new AverageTrueRangeStopLossRule(BarSeries series, Indicator<Num> referencePrice,
                                  int atrBarCount, Number atrCoefficient)

// Bring your own ATR indicator
new AverageTrueRangeStopLossRule(Indicator<Num> referencePrice,
                                  ATRIndicator atrIndicator, Number atrCoefficient)
Parameters:
ParameterDescription
seriesThe bar series
atrBarCountPeriod for ATR calculation (e.g., 14)
atrCoefficientMultiplier applied to the ATR value (e.g., 2.0)
// Stop at 2× ATR(14) below entry
Rule atrStop = new AverageTrueRangeStopLossRule(series, 14, 2.0);
Takes profit when the price moves atrCoefficient × ATR(atrBarCount) in favor of the position from the entry price.
new AverageTrueRangeStopGainRule(series, 14, 3.0)
A trailing ATR stop: tracks the most favorable price seen since entry and triggers when the price retraces by atrCoefficient × ATR.
new AverageTrueRangeTrailingStopLossRule(series, 14, 2.0)
Trailing profit target based on ATR: exits when the price retraces by atrCoefficient × ATR from the peak favorable price.
new AverageTrueRangeTrailingStopGainRule(series, 14, 2.5)

Volatility stop rules

These rules accept any Indicator<Num> as the volatility measure (ATR, standard deviation, etc.), giving you full flexibility over the volatility model.
Stop distance = volatilityIndicator × coefficient. Fires when the price moves more than this distance against the position.Constructor signatures:
// Uses close price as reference, explicit coefficient
new VolatilityStopLossRule(BarSeries series, Indicator<Num> volatilityIndicator, Number coefficient)

// Uses close price as reference, unit coefficient
new VolatilityStopLossRule(BarSeries series, Indicator<Num> volatilityIndicator)

// Custom reference price
new VolatilityStopLossRule(Indicator<Num> referencePrice,
                            Indicator<Num> volatilityIndicator, Number coefficient)
StandardDeviationIndicator stdDev = new StandardDeviationIndicator(close, 20);
Rule volStop = new VolatilityStopLossRule(series, stdDev, 2.0);
Takes profit when the price moves volatilityIndicator × coefficient in favor of the position.
new VolatilityStopGainRule(series, stdDev, 3.0)
Trailing volatility stop: trails the most favorable price and exits when the price retraces by volatility × coefficient.
new VolatilityTrailingStopLossRule(series, stdDev, 2.0)
Trailing profit target based on a volatility indicator.
new VolatilityTrailingStopGainRule(series, stdDev, 2.5)

Price model rules

These interfaces let stop levels be computed externally and queried programmatically, separate from rule evaluation.
Interface implemented by StopLossRule and TrailingStopLossRule. Provides stopPrice(BarSeries, Position) to retrieve the current stop level without needing a full bar index evaluation.
StopLossRule rule = new StopLossRule(close, 2.0);
Num stopLevel = rule.stopPrice(series, currentPosition);
Interface implemented by StopGainRule. Provides stopPrice(BarSeries, Position) to retrieve the profit target level.
StopGainRule rule = new StopGainRule(close, 5.0);
Num targetLevel = rule.stopPrice(series, currentPosition);

Risk-reward rule

Satisfied when the ratio of potential reward to risk meets a minimum threshold. Used as an entry filter — you only enter a trade if the risk/reward setup is favorable.Constructor signature:
new RiskRewardRatioRule(
    Indicator<Num> priceIndicator,
    Indicator<Num> stopIndicator,
    Indicator<Num> targetIndicator,
    boolean bullish,
    Number minRiskReward
)
Parameters:
ParameterDescription
priceIndicatorCurrent reference price
stopIndicatorIndicator providing the stop level
targetIndicatorIndicator providing the profit target level
bullishtrue for long setups, false for short
minRiskRewardMinimum reward/risk ratio required (e.g., 2.0 for 2:1)
// Only enter if the reward:risk ratio is at least 2:1
Rule rrFilter = new RiskRewardRatioRule(close, stopIndicator, targetIndicator, true, 2.0);
Rule entry = new CrossedUpIndicatorRule(ema12, ema26).and(rrFilter);

Compound stop rule example

Combine stop rules with .or() to exit on the first condition that fires:
import org.ta4j.core.*;
import org.ta4j.core.indicators.helpers.ClosePriceIndicator;
import org.ta4j.core.rules.*;

BarSeries series = /* your data source */;
ClosePriceIndicator close = new ClosePriceIndicator(series);

// Entry: EMA crossover
Rule entry = new CrossedUpIndicatorRule(new EMAIndicator(close, 12), new EMAIndicator(close, 26));

// Exit: any of the following conditions fires first
Rule exit = new StopLossRule(close, 2.0)             // hard stop at -2%
        .or(new TrailingStopLossRule(                 // OR trailing stop at -3% from peak
                close, series.numFactory().numOf(3)))
        .or(new StopGainRule(close, 8.0))             // OR take profit at +8%
        .or(new AverageTrueRangeStopLossRule(         // OR 2× ATR stop
                series, 14, 2.0));

Strategy strategy = new BaseStrategy("Multi-Stop Strategy", entry, exit);
When combining a trailing stop with a fixed stop, the fixed stop acts as an absolute floor while the trailing stop moves up with the price. Make sure the fixed stop percentage is larger than the trailing percentage, or the fixed stop will always trigger first and the trailing stop will never activate.