Files
wickra/examples/r/multi_timeframe.R
T
kingchenc 677ea37402 examples: migrate to the native data layer (drop ws/coder-websocket/jackson/jsonlite) (#316)
Stacked on #315 (the native Binance REST fetcher). Retarget to `main` once #315 merges.

Migrates the runnable examples off third-party data-I/O packages onto Wickra's
native data layer (`CandleReader`, `Resampler`, `BinanceFeed`, `fetch_*klines`).

## Third-party packages removed (the zero-dep selling point)
- **Node**: `ws` (live feed → BinanceFeed) — dropped from package.json + lockfile
- **Go**: `github.com/coder/websocket` — dropped from go.mod / go.sum (`go mod tidy`)
- **Java**: `jackson-databind` (live feed + REST fetch) — dropped from pom.xml
- **R**: `jsonlite` + `websocket` + `later` — dropped from the README notes

Each language's CSV loading now goes through `CandleReader`, manual resampling
through `Resampler`, the live feed through `BinanceFeed`, and (Java/R) the REST
download through the native fetcher.

## Verification
Ran the offline examples per language against the bundled data — backtest and
multi_timeframe produce identical output across Python / Node / Go / Java / R
(e.g. ATR(14) last 345.1010; 1h→5m resamples to 240 bars, →15m to 80 bars).

C# / C / WASM (stdlib-only, no third-party deps to remove) follow in this branch.

Note: the streaming `strategy_*` examples have pre-existing candle-indicator
runtime bugs (CI only syntax-smokes them); the CSV migration preserves their
shape and leaves those bugs for a separate fix.
2026-06-17 01:49:11 +02:00

32 lines
1.3 KiB
R

# Resample a 1-minute series into higher timeframes and run an indicator per timeframe.
library(wickra)
source("_common.R")
resample <- function(bars, factor) {
if (factor <= 1) return(bars)
# Native Resampler: bucket by an absolute timeframe (synthetic bars step 60000 ms,
# so factor minutes == factor*60000 ms). update() yields NA until a bucket closes;
# flush() returns the final partial bucket. No hand-written bucketing.
r <- Resampler(factor * 60000)
out <- list()
for (i in seq_len(nrow(bars))) {
c <- update(r, bars$open[i], bars$high[i], bars$low[i], bars$close[i],
bars$volume[i], bars$timestamp[i])
if (!is.na(c[1])) out[[length(out) + 1L]] <- c
}
f <- flush(r)
if (!is.null(f)) out[[length(out) + 1L]] <- f
m <- do.call(rbind, out)
data.frame(open = m[, 1], high = m[, 2], low = m[, 3], close = m[, 4],
volume = m[, 5], timestamp = m[, 6])
}
one_minute <- synthetic_candles(1200, step_ms = 60000)
cat("EMA(20) of close across timeframes (resampled from 1-minute bars):\n")
for (factor in c(1, 5, 15)) {
bars <- resample(one_minute, factor)
ema <- Ema(20); last <- NA_real_
for (cl in bars$close) last <- update(ema, cl)
cat(sprintf(" %2dm: %5d bars EMA(20) last = %.4f\n", factor, nrow(bars), last))
}