Skip to content
This repository has been archived by the owner on May 12, 2019. It is now read-only.

Getting started

Marc de Verdelhan edited this page Sep 7, 2017 · 17 revisions

Ta4j is an open source Java library for technical analysis. It provides the basic components for creation, evaluation and execution of trading strategies.

About technical analysis:

Getting started with ta4j

In this quick example we will backtest a trading strategy over a price time series.

At the beginning we just need a time series.

// Getting a time series (from any provider: CSV, web service, etc.)
TimeSeries series = ...;

See the dedicated article to learn about time series and to know how you can construct one.

Using indicators

We can calculate indicator over this time series, in order to forecast the direction of prices through the study of past market data.

// Getting the close price of the ticks
Decimal firstClosePrice = series.getTick(0).getClosePrice();
System.out.println("First close price: " + firstClosePrice.toDouble());
// Or within an indicator:
ClosePriceIndicator closePrice = new ClosePriceIndicator(series);
// Here is the same close price:
System.out.println(firstClosePrice.isEqual(closePrice.getValue(0))); // equal to firstClosePrice

// Getting the simple moving average (SMA) of the close price over the last 5 ticks
SMAIndicator shortSma = new SMAIndicator(closePrice, 5);
// Here is the 5-ticks-SMA value at the 42nd index
System.out.println("5-ticks-SMA value at the 42nd index: " + shortSma.getValue(42).toDouble());

// Getting a longer SMA (e.g. over the 30 last ticks)
SMAIndicator longSma = new SMAIndicator(closePrice, 30);

Ta4j includes more than 100 technical indicators.

Building a trading strategy

Then we have to build our trading strategy. It is made of two trading rules: one for entry, the other for exit.

// Buying rules
// We want to buy:
//  - if the 5-ticks SMA crosses over 30-ticks SMA
//  - or if the price goes below a defined price (e.g $800.00)
Rule buyingRule = new CrossedUpIndicatorRule(shortSma, longSma)
        .or(new CrossedDownIndicatorRule(closePrice, Decimal.valueOf("800")));

// Selling rules
// We want to sell:
//  - if the 5-ticks SMA crosses under 30-ticks SMA
//  - or if if the price looses more than 3%
//  - or if the price earns more than 2%
Rule sellingRule = new CrossedDownIndicatorRule(shortSma, longSma)
        .or(new StopLossRule(closePrice, Decimal.valueOf("3")))
        .or(new StopGainRule(closePrice, Decimal.valueOf("2")));

Ta4j comes with a set of basic trading rules which can be combined using boolean operators.

Backtesting/running our juicy strategy

The backtest step is pretty simple:

// Running our juicy trading strategy...
TradingRecord tradingRecord = series.run(new Strategy(buyingRule, sellingRule));
System.out.println("Number of trades for our strategy: " + tradingRecord.getTradeCount());
Analyzing our results

Here is how we can analyze the results of our backtest:

// Getting the cash flow of the resulting trades
CashFlow cashFlow = new CashFlow(series, tradingRecord);

// Getting the profitable trades ratio
AnalysisCriterion profitTradesRatio = new AverageProfitableTradesCriterion();
System.out.println("Profitable trades ratio: " + profitTradesRatio.calculate(series, tradingRecord));
// Getting the reward-risk ratio
AnalysisCriterion rewardRiskRatio = new RewardRiskRatioCriterion();
System.out.println("Reward-risk ratio: " + rewardRiskRatio.calculate(series, tradingRecord));

// Total profit of our strategy
// vs total profit of a buy-and-hold strategy
AnalysisCriterion vsBuyAndHold = new VersusBuyAndHoldCriterion(new TotalProfitCriterion());
System.out.println("Our profit vs buy-and-hold profit: " + vsBuyAndHold.calculate(series, tradingRecord));

Trading strategies can be easily compared according to a set of analysis criteria.

Going further

Ta4j can also be used for live trading with more complicated strategies. Check out the rest of the documentation and the examples.