Add the Java binding over the C ABI hub (Panama/FFM) (#233)

Adds a Java binding (`bindings/java`) over the C ABI hub — the fourth language stecker after C#, Go and R, reaching the hub through the Java Foreign Function & Memory API (Panama, `java.lang.foreign`, final in Java 22) rather than JNI or jextract.

## What's here
- **`bindings/java`** — a Maven module (`org.wickra:wickra`) exposing all 514 indicators as idiomatic `AutoCloseable` classes. The downcall handles (`internal/NativeMethods.java`), the per-indicator wrappers and the output records are generated from `bindings/c/include/wickra.h` (same eight-archetype taxonomy as the C#/Go/R generators: scalar/batch, multi-output, bars, profile, values-profile, array-input). The opaque handle is a `MemorySegment` freed by a registered `java.lang.ref.Cleaner` action; multi-output returns a `record` (`null` at warmup), bars a `record[]`, profiles a record with a trailing `double[]`. The hand-written `WickraNative` resolves the native library (a bundled per-platform copy, or a `target/release` fallback for local development) and validates it against a sentinel symbol. repr(C) struct offsets are computed in the generator so the FFM reads land on the exact bytes.
- **`examples/java`** — the full example suite mirroring C/C#/Go/R: streaming, backtest, multi_timeframe, parallel_assets (parallel streams), three strategies, and `FetchBtcusdt`/`LiveBinance`.
- **CI** — a `java` job builds the C ABI library, sets up JDK 22 (Temurin, with a CDN-flake retry), runs the archetype test suite and the seven offline examples on Linux, macOS and Windows.
- **Release** — a gated `java-publish` job (skipped until the `JAVA_PUBLISH_ENABLED` repository variable is set) stages the native libraries from the `wickra-c-<triple>.tar.gz` assets into the binding's resources and deploys to Maven Central with GPG signing. Independent of the GitHub-release job, like the NuGet job.
- **Docs** — Java added to the README languages table, project layout, building/testing and comparison table, CONTRIBUTING, ARCHITECTURE, the examples index, the issue/PR templates, the About-description template, and the other binding READMEs.

## Requirements
Java 22+ (the FFM API is final since Java 22). The binding requires `--enable-native-access=ALL-UNNAMED` at runtime; the test and example runners pass it automatically.

No Rust crate or `Cargo.toml` change — the Java binding is standalone and additive. The generated `*.java` are committed (like the node `index.js`/`index.d.ts`); the generator stays private.
This commit is contained in:
kingchenc
2026-06-09 20:30:29 +02:00
committed by GitHub
parent 8659b42bef
commit 167f7b3ffe
664 changed files with 44991 additions and 26 deletions
+5
View File
@@ -0,0 +1,5 @@
# Maven build output
target/
# Data fetched at runtime by fetch_btcusdt
data/
+35
View File
@@ -0,0 +1,35 @@
# Wickra examples — Java
Runnable examples for the [Wickra Java binding](../../bindings/java). Each
example is a small `main` class that uses the `org.wickra:wickra` artifact and
resolves the native library automatically (from `target/release` during local
development, or the bundled per-platform library when packaged).
Build the native library and install the binding to your local Maven repo
first, then run any example with the `exec` plugin:
```bash
cargo build -p wickra-c --release
mvn -f bindings/java install -DskipTests
mvn -f examples/java compile
mvn -f examples/java exec:exec -Dexec.mainClass=org.wickra.examples.Streaming
```
(The `exec:exec` goal forks a JVM with `--enable-native-access=ALL-UNNAMED`, the
flag the FFM API needs.)
| Example | What it does | Main class |
| --- | --- | --- |
| `streaming` | Feed a synthetic price series through SMA / EMA / RSI / MACD tick by tick. | `org.wickra.examples.Streaming` |
| `backtest` | Compute a basket of indicators over an OHLCV series and print a summary. | `org.wickra.examples.Backtest` |
| `multi_timeframe` | Resample a 1-minute series into 5m / 15m and print an indicator per timeframe. | `org.wickra.examples.MultiTimeframe` |
| `parallel_assets` | SMA(20) batch over a panel of assets, serial vs parallel streams, with speedup. | `org.wickra.examples.ParallelAssets` |
| `strategy_rsi_mean_reversion` | RSI(14) mean-reversion with a PnL / Sharpe / max-DD summary. | `org.wickra.examples.StrategyRsiMeanReversion` |
| `strategy_macd_adx` | MACD crossover entries gated by ADX(14) > 20. | `org.wickra.examples.StrategyMacdAdx` |
| `strategy_bollinger_squeeze` | Bollinger-squeeze breakout with an ATR(14) trailing stop. | `org.wickra.examples.StrategyBollingerSqueeze` |
| `fetch_btcusdt` | Download real BTCUSDT klines from the Binance REST API into a CSV. | `org.wickra.examples.FetchBtcusdt` |
| `live_binance` | Stream live Binance klines through EMA(20) over a WebSocket. | `org.wickra.examples.LiveBinance` |
`fetch_btcusdt` and `live_binance` require network access; the rest run offline
on deterministic synthetic data. Shared helpers (synthetic data, CSV loader,
equity summary) live in `MarketData` and `Equity`.
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wickra.examples</groupId>
<artifactId>wickra-examples</artifactId>
<version>0.7.8</version>
<packaging>jar</packaging>
<name>Wickra Java examples</name>
<description>Runnable examples for the Wickra Java binding.</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>22</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>org.wickra</groupId>
<artifactId>wickra</artifactId>
<version>0.7.8</version>
</dependency>
<!-- Only the network examples (fetch_btcusdt) parse JSON. -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<!--
Run an example in a forked JVM with native access granted:
mvn exec:exec -Dexec.mainClass=org.wickra.examples.Streaming
-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<executable>${java.home}/bin/java</executable>
<arguments>
<argument>--enable-native-access=ALL-UNNAMED</argument>
<argument>-classpath</argument>
<classpath/>
<argument>${exec.mainClass}</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,43 @@
package org.wickra.examples;
import org.wickra.Atr;
import org.wickra.Ema;
import org.wickra.Rsi;
import org.wickra.Sma;
import org.wickra.examples.MarketData.Bar;
/**
* Compute a basket of indicators over an OHLCV series and print a summary.
* Pass a CSV path (timestamp,open,high,low,close,volume) or run on synthetic data.
*/
public final class Backtest {
public static void main(String[] args) throws Exception {
String source = args.length > 0 ? args[0] : "synthetic";
Bar[] bars = args.length > 0 ? MarketData.loadOhlcvCsv(args[0]) : MarketData.syntheticCandles(1000);
System.out.printf("Backtest over %d bars (%s):%n", bars.length, source);
try (Sma sma = new Sma(20);
Ema ema = new Ema(50);
Rsi rsi = new Rsi(14);
Atr atr = new Atr(14)) {
double lastSma = 0, lastEma = 0, lastRsi = 0, lastAtr = 0;
int oversold = 0;
for (Bar b : bars) {
lastSma = sma.update(b.close());
lastEma = ema.update(b.close());
lastRsi = rsi.update(b.close());
lastAtr = atr.update(b.open(), b.high(), b.low(), b.close(), b.volume(), b.timestamp());
if (Double.isFinite(lastRsi) && lastRsi < 30.0) {
oversold++;
}
}
System.out.printf(" SMA(20) last = %.4f%n", lastSma);
System.out.printf(" EMA(50) last = %.4f%n", lastEma);
System.out.printf(" RSI(14) last = %.4f (%d oversold bars)%n", lastRsi, oversold);
System.out.printf(" ATR(14) last = %.4f%n", lastAtr);
}
}
}
@@ -0,0 +1,63 @@
package org.wickra.examples;
import java.util.List;
/**
* Minimal long-only backtest helper: turn a stream of per-bar fractional returns
* into a PnL / Sharpe / max-drawdown summary. The strategy examples produce the
* returns; this aggregates them.
*/
public final class Equity {
private Equity() {
}
/** Summary statistics for a long-only equity curve. */
public record Result(double totalReturnPct, double sharpe, double maxDrawdownPct, int trades, double finalEquity) {
}
/**
* @param periodReturns per-bar fractional returns (0.01 == +1%)
* @param trades number of position entries
*/
public static Result summarize(List<Double> periodReturns, int trades) {
return summarize(periodReturns, trades, 252.0);
}
public static Result summarize(List<Double> periodReturns, int trades, double periodsPerYear) {
double equity = 1.0;
double peak = 1.0;
double maxDrawdown = 0.0;
for (double r : periodReturns) {
equity *= 1.0 + r;
peak = Math.max(peak, equity);
if (peak > 0) {
maxDrawdown = Math.max(maxDrawdown, (peak - equity) / peak);
}
}
double mean = 0.0;
for (double r : periodReturns) {
mean += r;
}
mean = periodReturns.isEmpty() ? 0.0 : mean / periodReturns.size();
double variance = 0.0;
if (periodReturns.size() > 1) {
for (double r : periodReturns) {
variance += (r - mean) * (r - mean);
}
variance /= periodReturns.size() - 1;
}
double stdDev = Math.sqrt(variance);
double sharpe = stdDev > 1e-12 ? mean / stdDev * Math.sqrt(periodsPerYear) : 0.0;
return new Result((equity - 1.0) * 100.0, sharpe, maxDrawdown * 100.0, trades, equity);
}
/** Prints a one-line summary. */
public static void print(String name, Result r) {
System.out.printf(
"%-26s return=%8.2f%% sharpe=%6.2f maxDD=%6.2f%% trades=%d%n",
name, r.totalReturnPct(), r.sharpe(), r.maxDrawdownPct(), r.trades());
}
}
@@ -0,0 +1,48 @@
package org.wickra.examples;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedWriter;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Download real BTCUSDT hourly klines from the Binance REST API into a CSV that the
* other examples can consume. Requires network access (build-only in CI).
*/
public final class FetchBtcusdt {
public static void main(String[] args) throws Exception {
String url = "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=500";
System.out.println("Fetching " + url);
HttpClient http = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode klines = new ObjectMapper().readTree(response.body());
Path dir = Path.of("data");
Files.createDirectories(dir);
Path path = dir.resolve("btcusdt_1h.csv");
int count = 0;
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write("timestamp,open,high,low,close,volume");
writer.newLine();
for (JsonNode kline : klines) {
// Binance kline array: [openTime, open, high, low, close, volume, ...]
writer.write(kline.get(0).asLong() + "," + kline.get(1).asText() + ","
+ kline.get(2).asText() + "," + kline.get(3).asText() + ","
+ kline.get(4).asText() + "," + kline.get(5).asText());
writer.newLine();
count++;
}
}
System.out.printf("Wrote %d klines to %s%n", count, path.toAbsolutePath());
}
}
@@ -0,0 +1,73 @@
package org.wickra.examples;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.wickra.Ema;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Stream live BTCUSDT 1-minute klines from Binance and feed each close through EMA(20).
* Requires network access (build-only in CI). Runs for up to 60 seconds.
*/
public final class LiveBinance {
public static void main(String[] args) throws Exception {
URI uri = URI.create("wss://stream.binance.com:9443/ws/btcusdt@kline_1m");
System.out.println("Connecting to " + uri + " (up to 60s)...");
ObjectMapper mapper = new ObjectMapper();
CountDownLatch done = new CountDownLatch(1);
try (Ema ema = new Ema(20)) {
WebSocket.Listener listener = new WebSocket.Listener() {
private final StringBuilder buffer = new StringBuilder();
@Override
public void onOpen(WebSocket webSocket) {
webSocket.request(1);
}
@Override
public java.util.concurrent.CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
buffer.append(data);
if (last) {
try {
JsonNode root = mapper.readTree(buffer.toString());
JsonNode k = root.get("k");
if (k != null) {
double close = Double.parseDouble(k.get("c").asText());
double value = ema.update(close);
System.out.printf("close=%.2f EMA(20)=%.2f%n", close, value);
}
} catch (Exception e) {
System.err.println("parse error: " + e.getMessage());
}
buffer.setLength(0);
}
webSocket.request(1);
return null;
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.err.println("websocket error: " + error.getMessage());
done.countDown();
}
};
WebSocket ws = HttpClient.newHttpClient()
.newWebSocketBuilder()
.buildAsync(uri, listener)
.join();
if (!done.await(60, TimeUnit.SECONDS)) {
System.out.println("Done (time limit reached).");
}
ws.sendClose(WebSocket.NORMAL_CLOSURE, "done");
}
}
}
@@ -0,0 +1,91 @@
package org.wickra.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Deterministic synthetic market data plus a small OHLCV CSV loader, shared by
* the offline examples so they run without network access.
*/
public final class MarketData {
private MarketData() {
}
/** One OHLCV bar with a millisecond timestamp. */
public record Bar(double open, double high, double low, double close, double volume, long timestamp) {
}
/** A reproducible price path (trend + two cycles), no randomness. */
public static double[] syntheticPrices(int count) {
return syntheticPrices(count, 100.0);
}
public static double[] syntheticPrices(int count, double start) {
double[] prices = new double[count];
for (int i = 0; i < count; i++) {
prices[i] = start + 12.0 * Math.sin(i * 0.05) + 5.0 * Math.sin(i * 0.013) + i * 0.01;
}
return prices;
}
/** A reproducible OHLCV series derived from {@link #syntheticPrices(int)}. */
public static Bar[] syntheticCandles(int count) {
return syntheticCandles(count, 0L, 3_600_000L);
}
public static Bar[] syntheticCandles(int count, long startTimestamp, long stepMs) {
double[] prices = syntheticPrices(count + 1);
Bar[] bars = new Bar[count];
for (int i = 0; i < count; i++) {
double open = prices[i];
double close = prices[i + 1];
double high = Math.max(open, close) + 0.5 + Math.abs(Math.sin(i * 0.7));
double low = Math.min(open, close) - 0.5 - Math.abs(Math.cos(i * 0.7));
double volume = 1_000.0 + 500.0 * (1.0 + Math.sin(i * 0.1));
bars[i] = new Bar(open, high, low, close, volume, startTimestamp + (long) i * stepMs);
}
return bars;
}
/**
* Loads an OHLCV CSV. Accepts rows of {@code timestamp,open,high,low,close,volume}
* or {@code open,high,low,close,volume}; a non-numeric first row is treated as a header.
*/
public static Bar[] loadOhlcvCsv(String path) throws IOException {
List<Bar> bars = new ArrayList<>();
for (String rawLine : Files.readAllLines(Path.of(path))) {
String line = rawLine.trim();
if (line.isEmpty()) {
continue;
}
String[] cols = line.split(",");
if (!isNumeric(cols[0])) {
continue; // header row
}
if (cols.length >= 6) {
bars.add(new Bar(
Double.parseDouble(cols[1]), Double.parseDouble(cols[2]),
Double.parseDouble(cols[3]), Double.parseDouble(cols[4]),
Double.parseDouble(cols[5]), Long.parseLong(cols[0])));
} else {
bars.add(new Bar(
Double.parseDouble(cols[0]), Double.parseDouble(cols[1]),
Double.parseDouble(cols[2]), Double.parseDouble(cols[3]),
Double.parseDouble(cols[4]), bars.size()));
}
}
return bars.toArray(new Bar[0]);
}
private static boolean isNumeric(String s) {
try {
Double.parseDouble(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
@@ -0,0 +1,46 @@
package org.wickra.examples;
import org.wickra.Ema;
import org.wickra.examples.MarketData.Bar;
import java.util.ArrayList;
import java.util.List;
/** Resample a 1-minute series into higher timeframes and run an indicator per timeframe. */
public final class MultiTimeframe {
public static void main(String[] args) {
Bar[] oneMinute = MarketData.syntheticCandles(1200, 0L, 60_000L);
System.out.println("EMA(20) of close across timeframes (resampled from 1-minute bars):");
for (int factor : new int[] {1, 5, 15}) {
Bar[] bars = resample(oneMinute, factor);
try (Ema ema = new Ema(20)) {
double last = 0;
for (Bar b : bars) {
last = ema.update(b.close());
}
System.out.printf(" %2dm: %5d bars EMA(20) last = %.4f%n", factor, bars.length, last);
}
}
}
private static Bar[] resample(Bar[] source, int factor) {
if (factor <= 1) {
return source;
}
List<Bar> output = new ArrayList<>();
for (int i = 0; i < source.length; i += factor) {
int end = Math.min(i + factor, source.length);
double high = Double.MIN_VALUE;
double low = Double.MAX_VALUE;
double volume = 0;
for (int j = i; j < end; j++) {
high = Math.max(high, source[j].high());
low = Math.min(low, source[j].low());
volume += source[j].volume();
}
output.add(new Bar(source[i].open(), high, low, source[end - 1].close(), volume, source[i].timestamp()));
}
return output.toArray(new Bar[0]);
}
}
@@ -0,0 +1,50 @@
package org.wickra.examples;
import org.wickra.Sma;
import java.util.stream.IntStream;
/** Run SMA(20) batch over a panel of assets, serial vs parallel, and report the speedup. */
public final class ParallelAssets {
public static void main(String[] args) {
int assets = args.length > 0 ? Integer.parseInt(args[0]) : 500;
int bars = args.length > 1 ? Integer.parseInt(args[1]) : 20_000;
double[][] panel = new double[assets][];
for (int a = 0; a < assets; a++) {
panel[a] = MarketData.syntheticPrices(bars, 50.0 + a * 0.1);
}
// Warm up the JIT and thread pool so the comparison is fair.
try (Sma warm = new Sma(20)) {
warm.batch(panel[0]);
}
double sink = 0.0;
long t0 = System.nanoTime();
for (int a = 0; a < assets; a++) {
try (Sma sma = new Sma(20)) {
double[] result = sma.batch(panel[a]);
sink += result[result.length - 1];
}
}
double serialMs = (System.nanoTime() - t0) / 1e6;
double[] lasts = new double[assets];
long t1 = System.nanoTime();
IntStream.range(0, assets).parallel().forEach(a -> {
try (Sma sma = new Sma(20)) {
double[] result = sma.batch(panel[a]);
lasts[a] = result[result.length - 1];
}
});
double parallelMs = (System.nanoTime() - t1) / 1e6;
System.out.printf("%d assets x %d bars, SMA(20) batch:%n", assets, bars);
System.out.printf(" serial %8.1f ms%n", serialMs);
System.out.printf(" parallel %8.1f ms (%.1fx speedup)%n", parallelMs, serialMs / Math.max(parallelMs, 1e-9));
if (sink == Double.NaN || lasts.length < 0) {
System.out.println(sink); // keep `sink` live
}
}
}
@@ -0,0 +1,56 @@
package org.wickra.examples;
import org.wickra.Atr;
import org.wickra.BollingerBands;
import org.wickra.BollingerOutput;
import org.wickra.examples.MarketData.Bar;
import java.util.ArrayList;
import java.util.List;
/**
* Breakout: when Bollinger bandwidth is tight (a "squeeze") and price closes above the
* upper band, go long with an ATR(14) trailing stop.
*/
public final class StrategyBollingerSqueeze {
public static void main(String[] args) throws Exception {
Bar[] bars = args.length > 0 ? MarketData.loadOhlcvCsv(args[0]) : MarketData.syntheticCandles(2000);
try (BollingerBands bollinger = new BollingerBands(20, 2.0);
Atr atr = new Atr(14)) {
List<Double> returns = new ArrayList<>();
int trades = 0;
boolean inPosition = false;
double entry = 0.0;
double stop = 0.0;
for (Bar b : bars) {
BollingerOutput band = bollinger.update(b.close());
double atrValue = atr.update(b.open(), b.high(), b.low(), b.close(), b.volume(), b.timestamp());
if (band == null || !Double.isFinite(atrValue)) {
continue;
}
double bandwidth = band.middle() != 0.0
? (band.upper() - band.lower()) / band.middle()
: Double.MAX_VALUE;
if (!inPosition && bandwidth < 0.06 && b.close() > band.upper()) {
inPosition = true;
entry = b.close();
stop = b.close() - 2.0 * atrValue;
trades++;
} else if (inPosition) {
stop = Math.max(stop, b.close() - 2.0 * atrValue); // trail the stop up
if (b.close() < stop) {
returns.add((b.close() - entry) / entry);
inPosition = false;
}
}
}
Equity.print("Bollinger squeeze", Equity.summarize(returns, trades));
}
}
}
@@ -0,0 +1,53 @@
package org.wickra.examples;
import org.wickra.Adx;
import org.wickra.AdxOutput;
import org.wickra.MacdIndicator;
import org.wickra.MacdOutput;
import org.wickra.examples.MarketData.Bar;
import java.util.ArrayList;
import java.util.List;
/**
* Trend follower: enter long on a MACD histogram cross up, but only when ADX(14) &gt; 20
* confirms a trend; exit when the histogram crosses back below zero.
*/
public final class StrategyMacdAdx {
public static void main(String[] args) throws Exception {
Bar[] bars = args.length > 0 ? MarketData.loadOhlcvCsv(args[0]) : MarketData.syntheticCandles(2000);
try (MacdIndicator macd = new MacdIndicator(12, 26, 9);
Adx adx = new Adx(14)) {
List<Double> returns = new ArrayList<>();
int trades = 0;
boolean inPosition = false;
double entry = 0.0;
double prevHistogram = Double.NaN;
for (Bar b : bars) {
MacdOutput m = macd.update(b.close());
AdxOutput a = adx.update(b.open(), b.high(), b.low(), b.close(), b.volume(), b.timestamp());
if (m == null || a == null) {
continue;
}
boolean trending = a.adx() > 20.0;
if (!inPosition && trending && Double.isFinite(prevHistogram)
&& prevHistogram <= 0.0 && m.histogram() > 0.0) {
inPosition = true;
entry = b.close();
trades++;
} else if (inPosition && m.histogram() < 0.0) {
returns.add((b.close() - entry) / entry);
inPosition = false;
}
prevHistogram = m.histogram();
}
Equity.print("MACD + ADX trend", Equity.summarize(returns, trades));
}
}
}
@@ -0,0 +1,38 @@
package org.wickra.examples;
import org.wickra.Rsi;
import org.wickra.examples.MarketData.Bar;
import java.util.ArrayList;
import java.util.List;
/** Mean reversion: go long when RSI(14) drops below 30, exit when it recovers above 50. */
public final class StrategyRsiMeanReversion {
public static void main(String[] args) throws Exception {
Bar[] bars = args.length > 0 ? MarketData.loadOhlcvCsv(args[0]) : MarketData.syntheticCandles(2000);
try (Rsi rsi = new Rsi(14)) {
List<Double> returns = new ArrayList<>();
int trades = 0;
boolean inPosition = false;
double entry = 0.0;
for (Bar b : bars) {
double value = rsi.update(b.close());
if (!Double.isFinite(value)) {
continue;
}
if (!inPosition && value < 30.0) {
inPosition = true;
entry = b.close();
trades++;
} else if (inPosition && value > 50.0) {
returns.add((b.close() - entry) / entry);
inPosition = false;
}
}
Equity.print("RSI mean-reversion", Equity.summarize(returns, trades));
}
}
}
@@ -0,0 +1,38 @@
package org.wickra.examples;
import org.wickra.Ema;
import org.wickra.MacdIndicator;
import org.wickra.MacdOutput;
import org.wickra.Rsi;
import org.wickra.Sma;
/** Feed a synthetic price series through several indicators tick by tick (O(1) each). */
public final class Streaming {
public static void main(String[] args) {
double[] prices = MarketData.syntheticPrices(500);
try (Sma sma = new Sma(20);
Ema ema = new Ema(20);
Rsi rsi = new Rsi(14);
MacdIndicator macd = new MacdIndicator(12, 26, 9)) {
double lastSma = 0, lastEma = 0, lastRsi = 0;
MacdOutput lastMacd = null;
for (double price : prices) {
lastSma = sma.update(price);
lastEma = ema.update(price);
lastRsi = rsi.update(price);
lastMacd = macd.update(price);
}
System.out.printf("Streamed %d prices through SMA(20), EMA(20), RSI(14), MACD(12,26,9):%n", prices.length);
System.out.printf(" SMA = %.4f%n", lastSma);
System.out.printf(" EMA = %.4f%n", lastEma);
System.out.printf(" RSI = %.4f%n", lastRsi);
if (lastMacd != null) {
System.out.printf(" MACD = %.4f signal=%.4f hist=%.4f%n",
lastMacd.macd(), lastMacd.signal(), lastMacd.histogram());
}
}
}
}