### Run ta4j Quickstart Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Examples-Expected-Outputs.md Execute the Quickstart example to see staged walkthrough sections and a trade metrics summary. In GUI mode, a chart window will open. ```bash mvn -pl ta4j-examples exec:java -Dexec.mainClass=ta4jexamples.Quickstart ``` -------------------------------- ### Run ta4j TradingRecordParityBacktest Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Examples-Expected-Outputs.md Execute the TradingRecordParityBacktest example to compare execution models and verify record-parity checks. ```bash mvn -pl ta4j-examples exec:java -Dexec.mainClass=ta4jexamples.backtesting.TradingRecordParityBacktest ``` -------------------------------- ### Quick Start: Elliott Wave Facade Analysis Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Indicators.md This Java snippet demonstrates how to quickly get started with ta4j's Elliott Wave facade to analyze scenarios, check for consensus, and retrieve alternative wave counts. ```java // Create facade ElliottWaveFacade facade = ElliottWaveFacade.fractal(series, 5, ElliottDegree.INTERMEDIATE); int index = series.getEndIndex(); // Get base case interpretation with confidence Optional baseCase = facade.primaryScenario(index); if (baseCase.isPresent()) { ElliottScenario bc = baseCase.get(); System.out.println("Phase: " + p.currentPhase()); System.out.println("Confidence: " + String.format("%.1f%%", p.confidence().asPercentage())); System.out.println("Invalidation: " + p.invalidationPrice()); System.out.println("Target: " + p.primaryTarget()); } // Check for consensus if (facade.hasScenarioConsensus(index)) { System.out.println("Strong consensus: " + facade.scenarioConsensus(index)); } // Get alternatives List alts = facade.alternativeScenarios(index); System.out.println("Alternative counts: " + alts.size()); ``` -------------------------------- ### Run ta4j Examples Tests Source: https://github.com/ta4j/ta4j-wiki/blob/master/Getting-started.md Executes tests for the ta4j examples module. This helps verify your environment setup. ```bash mvn -pl ta4j-examples test ``` -------------------------------- ### Run Elliott Wave Analysis Examples (Bash) Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Indicators.md These bash commands demonstrate how to run pre-configured Elliott Wave analysis examples using the ta4j-examples module. They cover analyzing different assets like Bitcoin, Ethereum, and S&P 500 with default or custom settings. ```bash # Analyze ossified Bitcoin with default settings java ta4jexamples.analysis.elliottwave.ElliottWavePresetDemo ossified btc # Analyze ossified Ethereum java ta4jexamples.analysis.elliottwave.ElliottWavePresetDemo ossified eth # Analyze ossified S&P 500 java ta4jexamples.analysis.elliottwave.ElliottWavePresetDemo ossified sp500 # Custom live-style analysis with command-line arguments java ta4jexamples.analysis.elliottwave.ElliottWavePresetDemo live Coinbase BTC-USD PT1D 1825 PRIMARY ``` -------------------------------- ### Example Usage: Coinbase Backtest Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Illustrates backtesting with data fetched from Coinbase. This is useful for understanding cryptocurrency data integration and strategy execution. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; import org.ta4j.core.BaseStrategy; import org.ta4j.core.BaseBarSeries; import java.time.LocalDate; import java.time.Duration; public class CoinbaseBacktest { public static void main(String[] args) { // 1. Building a bar series from Coinbase BarSeries series = new BaseBarSeries(); // For example, we will use the "2018-01-01" to "2018-01-31" interval // For more details, see the "Data Sources" page series.addBars(CoinbaseData.getBars(series, "BTC-USD", "1DAY", LocalDate.of(2018, 1, 1), LocalDate.of(2018, 1, 31))); // 2. Strategy design with TA-Lib // Close price indicator ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // SMA indicators SMAIndicator shortSma = new SMAIndicator(closePrice, 5); SMAIndicator longSma = new SMAIndicator(closePrice, 10); // Strategy rules // Buy rule: close price crosses above the long SMA Strategy buyStrategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Backtesting the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(buyStrategy); System.out.println("Number of trades for the strategy: " + tradingRecord.getTradeCount()); // 4. Analysis of the strategy results // TODO } } class CoinbaseData { public static java.util.List getBars(BarSeries barSeries, String symbol, String interval, LocalDate start, LocalDate end) { // This is a placeholder for actual data fetching logic. // In a real application, you would use a library like "ta4j-core"'s Coinbase data provider // or another financial data API to fetch historical OHLCV data. // For demonstration purposes, we'll return an empty list. System.out.println("Fetching data for " + symbol + " interval " + interval + " from " + start + " to " + end); return java.util.Collections.emptyList(); } } ``` -------------------------------- ### Example Usage: Yahoo Finance Backtest Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Demonstrates how to perform a backtest using data from Yahoo Finance. This example is useful for understanding data ingestion and backtesting execution. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; import org.ta4j.core.BaseStrategy; import org.ta4j.core.BaseBarSeries; import java.time.LocalDate; import java.time.Duration; public class YahooFinanceBacktest { public static void main(String[] args) { // 1. Building a bar series from Yahoo Finance BarSeries series = new BaseBarSeries(); // For example, we will use the "2018-01-01" to "2018-01-31" interval // For more details, see the "Data Sources" page series.addBars(YahooFinanceData.getBars(series, "AAPL", LocalDate.of(2018, 1, 1), LocalDate.of(2018, 1, 31))); // 2. Strategy design with TA-Lib // Close price indicator ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // SMA indicators SMAIndicator shortSma = new SMAIndicator(closePrice, 5); SMAIndicator longSma = new SMAIndicator(closePrice, 10); // Strategy rules // Buy rule: close price crosses above the long SMA Strategy buyStrategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Backtesting the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(buyStrategy); System.out.println("Number of trades for the strategy: " + tradingRecord.getTradeCount()); // 4. Analysis of the strategy results // TODO } } class YahooFinanceData { public static java.util.List getBars(BarSeries barSeries, String symbol, LocalDate start, LocalDate end) { // This is a placeholder for actual data fetching logic. // In a real application, you would use a library like "ta4j-core"'s YahooFinance data provider // or another financial data API to fetch historical OHLCV data. // For demonstration purposes, we'll return an empty list. System.out.println("Fetching data for " + symbol + " from " + start + " to " + end); return java.util.Collections.emptyList(); } } ``` -------------------------------- ### Example Elliott Wave Strategy Rules Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Indicators.md Demonstrates wiring built-in Elliott Wave scenario rules for entry and exit conditions. Requires an ElliottWaveFacade and relevant indicators. ```java Num fibTolerance = series.numFactory().numOf(0.25); ElliottWaveFacade facade = ElliottWaveFacade.fractal( series, 5, ElliottDegree.INTERMEDIATE, Optional.of(fibTolerance), Optional.empty()); ElliottScenarioIndicator scenarios = facade.scenarios(); ClosePriceIndicator close = new ClosePriceIndicator(series); Rule entryRule = new ElliottScenarioValidRule(scenarios, close) .and(new ElliottScenarioConfidenceRule(scenarios, 0.6)) .and(new ElliottImpulsePhaseRule(scenarios, ElliottPhase.WAVE3)) .and(new ElliottScenarioDirectionRule(scenarios, true)) .and(new ElliottTrendBiasRule(scenarios, true, 0.5)); Rule exitRule = new ElliottScenarioInvalidationRule(scenarios, close) .or(new ElliottScenarioTargetReachedRule(scenarios, close, true)) .or(new ElliottScenarioTimeStopRule(scenarios, 2.0)); ``` -------------------------------- ### Run TrendLineAndSwingPointAnalysis Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Trendlines-and-Swing-Points.md Executes the ta4j example for TrendLineAndSwingPointAnalysis using Maven. This is useful for performing regression-style headroom checks and rendering charts. ```bash mvn -pl ta4j-examples -Dexec.mainClass=ta4jexamples.analysis.TrendLineAndSwingPointAnalysis exec:java ``` -------------------------------- ### Trade Fill Recording Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Demonstrates how to record trade fills, separating signal decisions from fill recording. This is essential for realistic backtesting and live trading. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseBarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; import org.ta4j.core.Trade; public class TradeFillRecordingExample { public static void main(String[] args) { // 1. Building a bar series BarSeries series = new BaseBarSeries(); series.addBar(10, 12, 9, 11, 100); series.addBar(11, 13, 10, 12, 120); series.addBar(12, 14, 11, 13, 110); series.addBar(13, 15, 12, 14, 130); series.addBar(14, 16, 13, 15, 140); series.addBar(15, 17, 14, 16, 150); // 2. Strategy design ClosePriceIndicator closePrice = new ClosePriceIndicator(series); SMAIndicator shortSma = new SMAIndicator(closePrice, 2); SMAIndicator longSma = new SMAIndicator(closePrice, 4); Strategy strategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Backtesting the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(strategy); // 4. Recording trade fills // In a real scenario, you would iterate through the tradingRecord and record fills // based on broker confirmations or simulated execution logic. System.out.println("Number of trades: " + tradingRecord.getTradeCount()); for (Trade trade : tradingRecord.getTrades()) { System.out.println("Trade: " + trade.getEntry().getIndex() + " to " + trade.getExit().getIndex()); // Here you would add logic to record the fill details (price, quantity, timestamp, etc.) } } } ``` -------------------------------- ### Direct Push Override Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/completed-features/RELEASE_PROCESS_PRD.md Demonstrates how to bypass the standard Pull Request creation process and publish a release directly. This is intended for emergency use cases. ```bash RELEASE_DIRECT_PUSH=true ``` -------------------------------- ### Initialize Single-Threaded Market and Trading State Source: https://github.com/ta4j/ta4j-wiki/blob/master/Live-trading.md Use this for single-threaded setups to initialize a BaseBarSeries and a BaseTradingRecord. Ensure the strategy's starting type and execution match policy are correctly set. ```java BarSeries series = new BaseBarSeriesBuilder() .withName("eth-usd-live") .build(); BaseTradingRecord tradingRecord = new BaseTradingRecord( strategy.getStartingType(), ExecutionMatchPolicy.FIFO, RecordedTradeCostModel.INSTANCE, new ZeroCostModel(), null, null); ``` -------------------------------- ### Backtest Performance Tuning Harness Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Provides a harness for tuning backtest performance. This is useful for optimizing the execution speed of backtesting processes. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseBarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; public class BacktestPerformanceTuningHarness { public static void main(String[] args) { // 1. Building a bar series BarSeries series = new BaseBarSeries(); // Add a large amount of sample data for performance testing for (int i = 0; i < 10000; i++) { series.addBar(i, i + 2, i, i + 1, 100); } // 2. Strategy design ClosePriceIndicator closePrice = new ClosePriceIndicator(series); SMAIndicator shortSma = new SMAIndicator(closePrice, 5); SMAIndicator longSma = new SMAIndicator(closePrice, 10); Strategy strategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Backtesting the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); long startTime = System.nanoTime(); TradingRecord tradingRecord = seriesManager.run(strategy); long endTime = System.nanoTime(); // 4. Performance measurement System.out.println("Backtest completed in " + (endTime - startTime) / 1_000_000 + " ms"); System.out.println("Number of trades: " + tradingRecord.getTradeCount()); } } ``` -------------------------------- ### Example Entry Logic (Accumulation Continuation) Source: https://github.com/ta4j/ta4j-wiki/blob/master/VWAP-Support-Resistance-and-Wyckoff.md Implement entry logic for a long position during accumulation phases, checking for agreement between high-level and low-level Wyckoff indicators, price position relative to VWAP and support, and Z-score thresholds. ```java int i = series.getEndIndex(); Num price = close.getValue(i); WyckoffPhase phase = wyckoff.getValue(i); // low-level indicator path WyckoffPhase cyclePhase = wyckoffFacade.phase(i); // high-level facade path Num cycleRangeLow = wyckoffFacade.tradingRangeLow(i); boolean inAccumulationAdvance = phase.cycleType() == WyckoffCycleType.ACCUMULATION && (phase.phaseType() == WyckoffPhaseType.PHASE_D || phase.phaseType() == WyckoffPhaseType.PHASE_E) && phase.confidence() >= 0.75; boolean cycleAgrees = cyclePhase.cycleType() == WyckoffCycleType.ACCUMULATION; boolean aboveValue = price.isGreaterThan(vwap.getValue(i)); boolean notOverextended = zScore.getValue(i).isLessThan(num.numOf("2.0")); boolean nearSupport = price.minus(support.getValue(i)).abs().isLessThanOrEqual(num.numOf("0.5")); boolean nearCycleRangeLow = price.minus(cycleRangeLow).abs().isLessThanOrEqual(num.numOf("0.5")); if (inAccumulationAdvance && cycleAgrees && aboveValue && notOverextended && nearSupport && nearCycleRangeLow) { // candidate long condition } ``` -------------------------------- ### Start with the Elliott Wave Facade Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Quickstart.md Use this snippet for indicator-style access within rules or chart overlays. It initializes the facade with optional Fibonacci tolerance for phase and scenario analysis. ```java BarSeries series = ...; int index = series.getEndIndex(); // Optional: loosen/tighten Fibonacci validation for both phase() and scenarios() Num fibTolerance = series.numFactory().numOf(0.25); ElliottWaveFacade facade = ElliottWaveFacade.fractal( series, 5, ElliottDegree.INTERMEDIATE, Optional.of(fibTolerance), Optional.empty()); ElliottPhase phase = facade.phase().getValue(index); ElliottScenarioSet scenarios = facade.scenarios().getValue(index); Num invalidation = facade.invalidationLevel().getValue(index); ``` -------------------------------- ### Install ta4j Core Module Source: https://github.com/ta4j/ta4j-wiki/blob/master/Getting-started.md Installs the ta4j-core module locally. Use this if you need the latest master APIs not yet available on Maven Central. ```bash mvn -pl ta4j-core -am install ``` -------------------------------- ### Simple Moving Average Range Backtest Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Performs a backtest using a Simple Moving Average (SMA) crossover strategy. This example focuses on range-based trading conditions. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; import org.ta4j.core.BaseBarSeries; public class SimpleMovingAverageRangeBacktest { public static void main(String[] args) { // 1. Building a bar series BarSeries series = new BaseBarSeries(); // Add some sample data (replace with actual data loading) series.addBar(10, 12, 9, 11, 100); series.addBar(11, 13, 10, 12, 120); series.addBar(12, 14, 11, 13, 110); series.addBar(13, 15, 12, 14, 130); series.addBar(14, 16, 13, 15, 140); series.addBar(15, 17, 14, 16, 150); // 2. Strategy design ClosePriceIndicator closePrice = new ClosePriceIndicator(series); SMAIndicator shortSma = new SMAIndicator(closePrice, 2); SMAIndicator longSma = new SMAIndicator(closePrice, 4); Strategy strategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Backtesting the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(strategy); // 4. Analysis of the strategy results System.out.println("Number of trades: " + tradingRecord.getTradeCount()); // Further analysis can be performed here. } } ``` -------------------------------- ### Net Momentum Strategy Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Implements a Net Momentum strategy. This strategy combines multiple indicators to determine entry and exit points. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; public class NetMomentumStrategy { public static Strategy buildStrategy(BarSeries series) { // We need to define the trading session timeframe int shortSmaTimeFrame = 5; int longSmaTimeFrame = 10; // Close price indicator ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // SMA indicators SMAIndicator shortSma = new SMAIndicator(closePrice, shortSmaTimeFrame); SMAIndicator longSma = new SMAIndicator(closePrice, longSmaTimeFrame); // Strategy rules // Buy rule: short SMA crosses above long SMA Strategy strategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // Set unstable bars for the strategy strategy.setUnstableBars(longSmaTimeFrame); return strategy; } } ``` -------------------------------- ### Risk Gating Rules Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Stop-Loss-and-Stop-Gain-Rules.md Demonstrates the usage of various risk gating rules including RiskRewardRatioRule, OverOrEqualIndicatorRule, UnderOrEqualIndicatorRule, and OrWithThresholdRule to build a complex entry rule. ```java Rule rrGate = new RiskRewardRatioRule(close, stopPrice, targetPrice, true, 2.0); Rule inclusiveState = new OverOrEqualIndicatorRule(rsi, 50); Rule inclusiveOversold = new UnderOrEqualIndicatorRule(rsi, 30); Rule delayedConfirm = new OrWithThresholdRule(macdCrossUp, breakoutRule, 3); Rule entryRule = rrGate.and(inclusiveState).and(inclusiveOversold.negation()).and(delayedConfirm); ``` -------------------------------- ### Build and Add a Bar to a Live Series Source: https://github.com/ta4j/ta4j-wiki/blob/master/Bar-series-and-bars.md Initializes a new BaseBarSeries and adds the first bar with specified time, price, and volume data. Useful for starting a live data feed. ```java BarSeries liveSeries = new BaseBarSeriesBuilder() .withName("eth_usd_live") .build(); Bar latest = liveSeries.barBuilder() .timePeriod(Duration.ofMinutes(1)) .endTime(Instant.now()) .openPrice(100.0) .highPrice(101.0) .lowPrice(99.5) .closePrice(100.7) .volume(42) .build(); liveSeries.addBar(latest); ``` -------------------------------- ### Configuring a Short-Only Strategy Source: https://github.com/ta4j/ta4j-wiki/blob/master/Trading-strategies.md Create a strategy that exclusively takes short positions by specifying Trade.TradeType.SELL as the starting trade type for the BaseStrategy. ```java Strategy shortOnly = new BaseStrategy("Short breakdown", shortEntryRule, shortExitRule, Trade.TradeType.SELL); ``` -------------------------------- ### Concurrent Usage Example for ConcurrentBarSeries Source: https://github.com/ta4j/ta4j-wiki/blob/master/Bar-series-and-bars.md Demonstrates how multiple threads can safely interact with a ConcurrentBarSeries for simultaneous trade ingestion, strategy evaluation, and indicator calculation. ```java // Thread 1: Ingest trades from WebSocket executorService.submit(() -> { while (running) { Trade trade = websocket.receiveTrade(); concurrentSeries.ingestTrade(trade.getTime(), trade.getVolume(), trade.getPrice()); } }); // Thread 2: Evaluate strategy executorService.submit(() -> { while (running) { int endIndex = concurrentSeries.getEndIndex(); if (strategy.shouldEnter(endIndex, tradingRecord)) { // Execute trade... } } }); // Thread 3: Calculate indicators executorService.submit(() -> { while (running) { int endIndex = concurrentSeries.getEndIndex(); Num rsiValue = rsiIndicator.getValue(endIndex); // Use indicator value... } }); ``` -------------------------------- ### RSI2 Strategy Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Implements the RSI(2) trading strategy. This is a common strategy for demonstrating rule composition and indicator usage. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.indicators.RSIIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; public class RSI2Strategy { public static Strategy buildStrategy(BarSeries series) { // We need to define the trading session timeframe // For example, for a daily series, we can use 14 days int timeFrame = 14; // Close price indicator ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // RSI indicator RSIIndicator rsi = new RSIIndicator(closePrice, timeFrame); // Strategy rules // Buy rule: RSI crosses above 30 Strategy strategy = new BaseStrategy(new OverIndicatorRule(rsi, 30), new UnderIndicatorRule(rsi, 70)); // Set unstable bars for the strategy // This is important for indicators that need a certain amount of data to be calculated correctly strategy.setUnstableBars(timeFrame); return strategy; } } ``` -------------------------------- ### Trading Bot on Moving Bar Series Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Illustrates a trading bot operating on a moving bar series. This is relevant for live trading scenarios where new data arrives continuously. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseBarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; public class TradingBotOnMovingBarSeries { public static void main(String[] args) { // 1. Building a moving bar series BarSeries series = new BaseBarSeries(); // Simulate new bars arriving over time for (int i = 0; i < 100; i++) { series.addBar(i, i + 2, i, i + 1, 100); // In a real bot, you would add logic here to process the new bar // and potentially make trading decisions. processNewBar(series); } } private static void processNewBar(BarSeries series) { // 2. Strategy design (example: SMA crossover) ClosePriceIndicator closePrice = new ClosePriceIndicator(series); SMAIndicator shortSma = new SMAIndicator(closePrice, 5); SMAIndicator longSma = new SMAIndicator(closePrice, 10); Strategy strategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Running the strategy on the current series state TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(strategy); // 4. Bot logic: making trading decisions based on the trading record if (!tradingRecord.getTrades().isEmpty()) { Trade lastTrade = tradingRecord.getLastTrade(); if (lastTrade.isBuy() && !series.isTradingEnabled()) { System.out.println("BUY signal at bar " + lastTrade.getEntry().getIndex()); // Execute buy order series.setTradingEnabled(true); } else if (lastTrade.isSell() && series.isTradingEnabled()) { System.out.println("SELL signal at bar " + lastTrade.getExit().getIndex()); // Execute sell order series.setTradingEnabled(false); } } } } ``` -------------------------------- ### Example Coinbase JSON Format Source: https://github.com/ta4j/ta4j-wiki/blob/master/Data-Sources.md An example of the JSON structure expected for Coinbase API response format, containing an array of candle data with start time, low, high, open, close, and volume. ```json { "candles": [ { "start": "2023-01-01T00:00:00Z", "low": "149.50", "high": "152.50", "open": "150.00", "close": "151.25", "volume": "1000000" }, { "start": "2023-01-02T00:00:00Z", "low": "150.75", "high": "153.00", "open": "151.25", "close": "152.00", "volume": "1200000" } ] } ``` -------------------------------- ### Yahoo Finance Data Source with Caching Source: https://github.com/ta4j/ta4j-wiki/blob/master/architecture/proposed/TODO-bar-series-datasource-refactoring.md Example of composing a YahooFinanceHttpBarSeriesDataSource using a CachedHttpDataRetrievalClient. Ensure caching is enabled by setting the boolean parameter to true. This setup is useful when dealing with frequently accessed financial data where performance is critical. ```java HttpDataRetrievalClient httpClient = new HttpDataRetrievalClient(httpClientWrapper); CachedHttpDataRetrievalClient cachedClient = new CachedHttpDataRetrievalClient( httpClient, Paths.get("temp/responses"), true // caching enabled ); YahooFinanceJsonMapper mapper = new YahooFinanceJsonMapper(); // Compose data source YahooFinanceHttpBarSeriesDataSource yahoo = new YahooFinanceHttpBarSeriesDataSource( cachedClient, mapper ); // Use as before BarSeries series = yahoo.loadSeries("AAPL", Duration.ofDays(1), start, end); ``` -------------------------------- ### RSI Indicator Test Class Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/XLS-Testing.md Example of a JUnit test class for the RSI indicator, extending the generic IndicatorTest class. ```java public class RSIIndicatorTest extends IndicatorTest, Decimal> { private ExternalIndicatorTest xls; public RSIIndicatorTest() { super((data, params) -> new RSIIndicator(data, (int) params[0])); xls = new XLSIndicatorTest(this.getClass(), "RSI.xls", 10); } } ``` -------------------------------- ### Instance Load for Unit Testing with Mock Client Source: https://github.com/ta4j/ta4j-wiki/blob/master/Data-Sources.md Demonstrates creating an instance for loading data using a mocked HTTP client. This is essential for unit testing data loading logic without making actual network requests. ```java // For unit testing with mock HTTP client HttpClientWrapper mockClient = mock(HttpClientWrapper.class); YahooFinanceHttpBarSeriesDataSource loader = new YahooFinanceHttpBarSeriesDataSource(mockClient); BarSeries series = loader.loadSeriesInstance("AAPL", YahooFinanceInterval.DAY_1, start, end); ``` -------------------------------- ### Java CriterionTest Class Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/XLS-Testing.md An example of a criterion test class extending CriterionTest for XLS-based criterion unit tests. It initializes an ExternalCriterionTest object for data extraction and calculation. ```java public class LinearTransactionCostCriterionTest extends CriterionTest { private ExternalCriterionTest xls; public LinearTransactionCostCriterionTest() throws Exception { super((params) -> new LinearTransactionCostCriterion((double) params[0], (double) params[1], (double) params[2])); xls = new XLSCriterionTest(this.getClass(), "LTC.xls", 16, 6); } } ``` -------------------------------- ### Run ta4j TradeFillRecordingExample Source: https://github.com/ta4j/ta4j-wiki/blob/master/Examples-Expected-Outputs.md Execute the TradeFillRecordingExample to observe streamed fill ingestion, grouped order ingestion, and lot-matching outcomes for different ExecutionMatchPolicy values. ```bash mvn -pl ta4j-examples exec:java -Dexec.mainClass=ta4jexamples.backtesting.TradeFillRecordingExample ``` -------------------------------- ### Example Bitstamp Trades CSV Format Source: https://github.com/ta4j/ta4j-wiki/blob/master/Data-Sources.md An example of the CSV format for Bitstamp trades data, including a header row and columns for timestamp (Unix seconds), price, and volume. ```csv timestamp,price,volume 1385337600,150.00,1.5 1385337610,150.25,2.0 1385337620,150.50,1.0 1385337630,150.75,3.5 ``` -------------------------------- ### Create and Use Trading Rules Source: https://github.com/ta4j/ta4j-wiki/blob/master/Trading-strategies.md Demonstrates how to create basic entry and exit rules using indicators and combine them into a trading strategy. Pass the TradingRecord to rules that depend on open positions or previous signals. ```java BarSeries series = new BaseBarSeriesBuilder().withName("sample").build(); ClosePriceIndicator closePrice = new ClosePriceIndicator(series); Num resistanceLevel = series.numFactory().numOf(120); Num supportLevel = series.numFactory().numOf(100); Rule breakout = new CrossedUpIndicatorRule(closePrice, resistanceLevel); Rule pullback = new CrossedDownIndicatorRule(closePrice, supportLevel); if (breakout.isSatisfied(index, tradingRecord)) { // do something with the signal } ``` -------------------------------- ### Automatic Axis Assignment Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Charting.md This example demonstrates how ChartBuilder automatically assigns indicators to primary and secondary Y-axes. The RSI (0-100) is placed on the secondary axis, while the SMA (price range) is placed on the primary axis, alongside the series price data. ```java RSIIndicator rsi = new RSIIndicator(closePrice, 14); SMAIndicator sma = new SMAIndicator(closePrice, 50); chartWorkflow.builder() .withSeries(series) // Primary axis: price range .withIndicatorOverlay(sma) // Primary axis: same range as price .withIndicatorOverlay(rsi) // Secondary axis: 0-100 range .display(); ``` -------------------------------- ### Build Elliott Wave Analyzer with Custom Components Source: https://github.com/ta4j/ta4j-wiki/blob/master/architecture/proposed/ew-enhancements-part-2/TODO-ta4j-elliottwave-enhancements-part-2.md Demonstrates how to construct an ElliottWaveAnalyzer by specifying custom detectors, compression profiles, scenario generators, and confidence models. This allows for fine-grained control over the analysis process. ```java ElliottWaveAnalyzer analyzer = ElliottWaveAnalyzer.builder() .swingDetector(SwingDetectors.composite( SwingDetectors.fractal(5), SwingDetectors.adaptiveZigZag(adaptiveCfg) )) .swingCompression(CompressionProfiles.primaryDegree()) .scenarioGenerator(ScenarioGenerators.defaultEnabled()) .confidenceModel(ConfidenceProfiles.defaultByScenarioType()) .build(); ElliottAnalysisResult result = analyzer.analyze(series); ElliottScenario base = result.scenarios().base(); ``` -------------------------------- ### Add ta4j-examples Dependency Source: https://github.com/ta4j/ta4j-wiki/blob/master/Charting.md Include the ta4j-examples module as a dependency to use charting functionalities in your project. ```xml org.ta4j ta4j-examples ${USE_LATEST_VERSION} ``` -------------------------------- ### Get JFreeChart Object Source: https://github.com/ta4j/ta4j-wiki/blob/master/Charting.md Obtain the JFreeChart object from the builder for further customization or display. Requires series and tradingRecordOverlay. ```java JFreeChart chart = chartWorkflow.builder() .withSeries(series) .withTradingRecordOverlay(tradingRecord) .toChart(); // Further customize the chart if needed chart.setTitle("Custom Title"); chartWorkflow.displayChart(chart); ``` -------------------------------- ### Trade Cost Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Calculates the cost associated with trades, including commissions and slippage. This is important for realistic performance analysis. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseBarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.TimeSeriesManager; import org.ta4j.core.TradingRecord; import org.ta4j.core.indicators.SMAIndicator; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; import org.ta4j.core.analysis.criteria.TotalProfitCriterion; import org.ta4j.core.analysis.criteria.AverageProfitCriterion; import org.ta4j.core.analysis.criteria.AverageEdgeCriterion; import org.ta4j.core.analysis.criteria.AverageTransactionCostCriterion; public class TradeCost { public static void main(String[] args) { // 1. Building a bar series BarSeries series = new BaseBarSeries(); series.addBar(10, 12, 9, 11, 100); series.addBar(11, 13, 10, 12, 120); series.addBar(12, 14, 11, 13, 110); series.addBar(13, 15, 12, 14, 130); series.addBar(14, 16, 13, 15, 140); series.addBar(15, 17, 14, 16, 150); // 2. Strategy design ClosePriceIndicator closePrice = new ClosePriceIndicator(series); SMAIndicator shortSma = new SMAIndicator(closePrice, 2); SMAIndicator longSma = new SMAIndicator(closePrice, 4); Strategy strategy = new BaseStrategy(new OverIndicatorRule(shortSma, longSma), new UnderIndicatorRule(shortSma, longSma)); // 3. Backtesting the strategy TimeSeriesManager seriesManager = new TimeSeriesManager(series); TradingRecord tradingRecord = seriesManager.run(strategy); // 4. Analyzing trade costs // Assuming a commission of 0.1% per trade double commission = 0.001; System.out.println("Average Transaction Cost: " + new AverageTransactionCostCriterion(commission).calculate(series, tradingRecord)); // Other criteria can also be used to analyze performance considering costs. } } ``` -------------------------------- ### Combine Price and Volume Indicators Source: https://github.com/ta4j/ta4j-wiki/blob/master/Technical-indicators.md Combine price-driven and volume-driven indicators to reduce false positives. This example uses MACD and VWMA. ```java new AndIndicatorRule(new OverIndicatorRule(macdv, zero), new OverIndicatorRule(vwma, close)) ``` -------------------------------- ### Execute Walk-Forward Backtest with Default Configuration Source: https://github.com/ta4j/ta4j-wiki/blob/master/Backtesting.md Use this snippet to perform a walk-forward backtest with default configuration settings. It requires a series and a strategy object. ```java WalkForwardConfig config = WalkForwardConfig.defaultConfig(series); BacktestExecutor.BacktestAndWalkForwardResult result = new BacktestExecutor(series) .executeWithWalkForward(strategy, config); BacktestExecutionResult standardRun = result.backtest(); StrategyWalkForwardExecutionResult walkForward = result.walkForward(); ``` -------------------------------- ### Proposed ta4j-examples Modernization Source: https://github.com/ta4j/ta4j-wiki/blob/master/architecture/proposed/ew-enhancements-part-2/TODO-ta4j-elliottwave-enhancements-part-2.md Details the planned updates and new examples for the ta4j-examples module, focusing on Elliott Wave analysis demonstrations. ```plaintext - Update existing `ElliottWaveAnalysis` example to print **confidence breakdown** including time alternation data. - Add `ElliottWaveAdaptiveSwingAnalysis` example demonstrating: - ATR-adaptive zigzag threshold - composite confirmation (fractal + zigzag) - Add `ElliottWavePatternProfileDemo` showing pattern-specific profiles and their effect on ranking. ``` -------------------------------- ### ElliottWaveIndicatorSuiteDemo Command-Line Usage Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Indicators.md Demonstrates command-line execution of the ElliottWaveIndicatorSuiteDemo. It shows how to load default datasets or specify custom data sources, tickers, bar durations, and epochs. ```bash # Load the default ossified BTC-USD dataset java ta4jexamples.analysis.elliottwave.ElliottWaveIndicatorSuiteDemo # Load from an external data source java ta4jexamples.analysis.elliottwave.ElliottWaveIndicatorSuiteDemo [dataSource] [ticker] [barDuration] [startEpoch] [endEpoch] java ta4jexamples.analysis.elliottwave.ElliottWaveIndicatorSuiteDemo [dataSource] [ticker] [barDuration] [degree] [startEpoch] [endEpoch] ``` -------------------------------- ### ATR Indicator Test Class Extension Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/XLS-Testing.md Demonstrates how to modify the IndicatorTest extension for indicators that use BarSeries data, such as ATR. ```java public class ATRIndicatorTest extends IndicatorTest ``` -------------------------------- ### Swing Adaptivity Implementation Checklist Source: https://github.com/ta4j/ta4j-wiki/blob/master/architecture/proposed/ew-enhancements-part-2/TODO-ta4j-elliottwave-enhancements-part-2.md Tracks the implementation status of various components related to swing adaptivity in Elliott Wave analysis. ```plaintext - [x] Add `SwingDetector` interface + adapters around existing `RecentSwingIndicator` style detectors. - [x] Implement `AdaptiveZigZagSwingDetector` (config: ATR period, min/max threshold, smoothing). - [x] Implement `CompositeSwingDetector` (policy: AND/OR; reconcile pivot disagreements). - [x] Implement `MinMagnitudeSwingFilter` (relative-to-largest-swing or ATR-based). - [x] Add unit tests with synthetic volatility regime shifts. ``` -------------------------------- ### Wiring Exit Rules with Stop-Loss and Stop-Gain Source: https://github.com/ta4j/ta4j-wiki/blob/master/Stop-Loss-and-Stop-Gain-Rules.md This example demonstrates how to combine different stop-loss and stop-gain rules with a signal-based exit rule to create a comprehensive exit strategy. It includes an ATR-based trailing stop loss, an ATR-based trailing stop gain, and a fixed amount stop loss as a fail-safe. The strategy is then constructed using these exit rules. ```java 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); ``` -------------------------------- ### Quick One-off Load (Static Method) Source: https://github.com/ta4j/ta4j-wiki/blob/master/Data-Sources.md Demonstrates a quick, one-off data load using a static method. This method does not utilize caching and is suitable for simple scripts. ```java // Quick one-off load - no caching BarSeries series = YahooFinanceHttpBarSeriesDataSource.loadSeries("AAPL", 365); ``` -------------------------------- ### ADX Strategy Example Source: https://github.com/ta4j/ta4j-wiki/blob/master/Canonical-User-Journey.md Implements the Average Directional Movement Index (ADX) trading strategy. This strategy is useful for identifying trend strength. ```java import org.ta4j.core.BarSeries; import org.ta4j.core.BaseStrategy; import org.ta4j.core.Strategy; import org.ta4j.core.indicators.helpers.ClosePriceIndicator; import org.ta4j.core.indicators.ADXIndicator; import org.ta4j.core.rules.OverIndicatorRule; import org.ta4j.core.rules.UnderIndicatorRule; public class ADXStrategy { public static Strategy buildStrategy(BarSeries series) { // We need to define the trading session timeframe // For example, for a daily series, we can use 14 days int timeFrame = 14; // Close price indicator ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // ADX indicator ADXIndicator adx = new ADXIndicator(series, timeFrame); // Strategy rules // Buy rule: ADX crosses above 25 (indicating a strong trend) Strategy strategy = new BaseStrategy(new OverIndicatorRule(adx, 25), new UnderIndicatorRule(adx, 25)); // Set unstable bars for the strategy // This is important for indicators that need a certain amount of data to be calculated correctly strategy.setUnstableBars(timeFrame); return strategy; } } ``` -------------------------------- ### Run a Backtest with BarSeriesManager Source: https://github.com/ta4j/ta4j-wiki/blob/master/Getting-started.md Initialize a `BarSeriesManager` with your bar series and run the strategy to obtain trading records. This provides a basic backtesting execution. ```java BarSeriesManager manager = new BarSeriesManager(series); TradingRecord record = manager.run(strategy); System.out.printf("Closed positions: %d%n", record.getPositionCount()); System.out.printf("Current position open? %s%n", record.getCurrentPosition().isOpened()); ``` -------------------------------- ### Get Elliott Trend Bias Value Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Indicators.md Retrieve the ElliottTrendBias value for a specific index to check for bullish, bearish, or neutral trends and consensus. ```java ElliottTrendBias bias = trendBias.getValue(index); if (bias.isBullish() && bias.consensus()) { // High-confidence scenarios agree on bullish direction } ``` -------------------------------- ### Using ElliottWaveFacade for Comprehensive Analysis Source: https://github.com/ta4j/ta4j-wiki/blob/master/Elliott-Wave-Indicators.md Demonstrates how to create and use ElliottWaveFacade for deterministic analysis, wave counting, scenario-based analysis, price projections, and consensus. Requires a BarSeries and specifies swing detection parameters. ```java BarSeries series = // your bar series (minimum ~60 bars recommended) // Create a complete Elliott Wave analysis facade ElliottWaveFacade facade = ElliottWaveFacade.fractal(series, 5, ElliottDegree.INTERMEDIATE); int index = series.getEndIndex(); // Deterministic analysis ElliottPhase phase = facade.phase().getValue(index); ElliottRatio ratio = facade.ratio().getValue(index); ElliottChannel channel = facade.channel().getValue(index); boolean confluent = facade.confluence().isConfluent(index); // Wave counting int waveCount = facade.waveCount().getValue(index); // All swings int filteredCount = facade.filteredWaveCount().getValue(index); // Filtered (if compressor configured) // Scenario-based analysis Optional baseCase = facade.primaryScenario(index); List alternatives = facade.alternativeScenarios(index); String summary = facade.scenarioSummary(index); // Human-readable summary // Price projections and invalidation Num projection = facade.projection().getValue(index); Num invalidationPrice = facade.invalidationLevel().getValue(index); // Consensus and confidence boolean hasConsensus = facade.hasScenarioConsensus(index); ElliottPhase consensusPhase = facade.scenarioConsensus(index); Num confidence = facade.confidenceForPhase(index, ElliottPhase.WAVE3); ```