Use this file to discover all available pages before exploring further.
Rules are the boolean building blocks of a ta4j strategy. Each rule implements the Rule interface and returns true or false when evaluated at a given bar index.
Every Rule exposes four fluent combinators that each return a new Rule:
Rule a = new CrossedUpIndicatorRule(fastEma, slowEma);Rule b = new OverIndicatorRule(rsi, 50);Rule both = a.and(b); // AND — both must be satisfiedRule either = a.or(b); // OR — at least one must be satisfiedRule oneNotOther = a.xor(b); // XOR — exactly one must be satisfiedRule notA = a.negation(); // NOT — inverts the rule
ChainRule requires an initial rule followed by one or more ChainLink steps. Each step must be satisfied within a configurable number of bars after the previous one fires.
import org.ta4j.core.rules.ChainRule;import org.ta4j.core.rules.helper.ChainLink;// Entry fires only when a crossover is followed by RSI > 50 within 3 barsRule entry = new ChainRule( new CrossedUpIndicatorRule(fastEma, slowEma), new ChainLink(new OverIndicatorRule(rsi, 50), 3));
The following example assembles a complete entry/exit strategy from multiple rule types:
import org.ta4j.core.*;import org.ta4j.core.indicators.*;import org.ta4j.core.indicators.helpers.ClosePriceIndicator;import org.ta4j.core.rules.*;import org.ta4j.core.backtest.BarSeriesManager;BarSeries series = /* your data source */;ClosePriceIndicator close = new ClosePriceIndicator(series);EMAIndicator ema12 = new EMAIndicator(close, 12);EMAIndicator ema26 = new EMAIndicator(close, 26);RSIIndicator rsi = new RSIIndicator(close, 14);// Entry: EMA golden cross AND RSI confirms momentum, but only on MondaysRule entry = new CrossedUpIndicatorRule(ema12, ema26) .and(new OverIndicatorRule(rsi, 50)) .and(new DayOfWeekRule(DayOfWeek.MONDAY));// Exit: reverse crossover, OR take profit at +5%, OR cut loss at -2%Rule exit = new CrossedDownIndicatorRule(ema12, ema26) .or(new StopGainRule(close, 5.0)) .or(new StopLossRule(close, 2.0));Strategy strategy = new BaseStrategy("EMA + RSI", entry, exit);TradingRecord record = new BarSeriesManager(series).run(strategy);
Combine WaitForRule or OpenedPositionMinimumBarCountRule with an exit rule to enforce a minimum hold period before exits are considered.