From 962ced0712b447f6f32b4d2b28cfb9f2e313c42c Mon Sep 17 00:00:00 2001 From: kingchenc Date: Sat, 23 May 2026 00:15:48 +0200 Subject: [PATCH] examples: add multi-timeframe demos for Rust and Node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Python's examples/python/multi_timeframe.py had no Rust or Node sibling. Add both — the Rust version uses wickra-data's `Resampler` / `resample_all` (the canonical path; no manual roll-up), the Node version mirrors the Python one's inline aggregation because wickra-data's resampler is currently Rust-only. * examples/rust/src/bin/multi_timeframe.rs — reads the bundled 1m CSV via `CandleReader`, resamples to 5m / 15m / 1h / 4h / 1d via `resample_all`, prints last RSI(14), MACD(12,26,9) histogram and ADX(14) per timeframe. * examples/node/multi_timeframe.js — same outputs from a hand-rolled bucket aggregator; reuses the new examples/data/ default path. * examples/README.md gains the new rows. Run side by side: the Rust and Node summaries are bit-identical at every timeframe (50000 / 10000 / 3334 / 834 / 209 / 35 bars; same RSI, MACD histogram and ADX to two decimals) — confirming both the Rust resampler and the inline Node aggregator produce the same OHLC buckets. --- examples/README.md | 2 + examples/node/multi_timeframe.js | 154 +++++++++++++++++++++++ examples/rust/src/bin/multi_timeframe.rs | 85 +++++++++++++ 3 files changed, 241 insertions(+) create mode 100644 examples/node/multi_timeframe.js create mode 100644 examples/rust/src/bin/multi_timeframe.rs diff --git a/examples/README.md b/examples/README.md index 5477a933..bc749596 100644 --- a/examples/README.md +++ b/examples/README.md @@ -13,6 +13,7 @@ The Rust examples live in the `wickra-examples` workspace member crate. | --- | --- | --- | | `streaming.rs` | Feed a synthetic price series through SMA / EMA / RSI / MACD tick by tick. | `cargo run -p wickra-examples --bin streaming` | | `backtest.rs` | Compute a basket of indicators over an OHLCV CSV and print a summary. | `cargo run -p wickra-examples --bin backtest -- ` | +| `multi_timeframe.rs` | Resample a 1-minute CSV via wickra-data and print indicators per timeframe. | `cargo run -p wickra-examples --bin multi_timeframe` | | `fetch_btcusdt.rs` | Download real BTCUSDT klines from the Binance REST API into `examples/data/`. | `cargo run -p wickra-examples --bin fetch_btcusdt` | | `live_binance.rs` | Stream live Binance klines through an indicator over a resilient WebSocket. | `cargo run -p wickra-examples --bin live_binance` | @@ -41,6 +42,7 @@ cd ../../examples/node && npm install # links wickra + installs `ws` | --- | --- | --- | | `streaming.js` | Feed a synthetic price series through several indicators tick by tick. | `node streaming.js` | | `backtest.js` | Basket of indicators over an OHLCV CSV; defaults to the bundled BTCUSDT daily dataset. | `node backtest.js [ohlcv.csv]` | +| `multi_timeframe.js` | Roll a 1-minute CSV up to 5m / 15m / 1h / 4h / 1d and print indicators per timeframe. | `node multi_timeframe.js [path/to/1m.csv]` | | `live_trading.js` | Live Binance feed → RSI / MACD / Bollinger → signals. | `node live_trading.js --symbol BTCUSDT --interval 1m` | ## WebAssembly — `examples/wasm/` diff --git a/examples/node/multi_timeframe.js b/examples/node/multi_timeframe.js new file mode 100644 index 00000000..c903698b --- /dev/null +++ b/examples/node/multi_timeframe.js @@ -0,0 +1,154 @@ +// Multi-timeframe indicators with the Wickra Node binding. +// +// Reads the bundled 1-minute BTCUSDT CSV (or a path passed on the command +// line), rolls it up to coarser timeframes (5m / 15m / 1h / 4h / 1d) and +// prints the last RSI(14), MACD(12,26,9) histogram and ADX(14) on each. +// Mirrors examples/python/multi_timeframe.py — wickra-data's Resampler is +// only exposed in Rust today, so the roll-up is computed inline here. +// +// Run with: +// node examples/node/multi_timeframe.js [path/to/1m.csv] + +const fs = require('node:fs'); +const path = require('node:path'); + +const wickra = require('wickra'); + +const REQUIRED_COLUMNS = ['timestamp', 'open', 'high', 'low', 'close', 'volume']; +const DEFAULT_CSV = path.join(__dirname, '..', 'data', 'btcusdt-1m.csv'); +const ONE_MINUTE_MS = 60_000; + +function readCsv(csvPath) { + const text = fs.readFileSync(csvPath, 'utf8'); + const lines = text.split(/\r?\n/).filter((line) => line.length > 0); + if (lines.length === 0) { + throw new Error(`${csvPath}: file is empty`); + } + const header = lines[0].split(',').map((cell) => cell.trim()); + const missing = REQUIRED_COLUMNS.filter((col) => !header.includes(col)); + if (missing.length > 0) { + throw new Error( + `${csvPath}: missing required column(s): ${missing.join(', ')}; found: ${header.join(', ')}`, + ); + } + if (lines.length === 1) { + throw new Error(`${csvPath}: CSV has a header but no data rows`); + } + const idx = {}; + for (const col of REQUIRED_COLUMNS) { + idx[col] = header.indexOf(col); + } + const cols = { timestamp: [], open: [], high: [], low: [], close: [], volume: [] }; + for (let i = 1; i < lines.length; i++) { + const cells = lines[i].split(','); + for (const col of REQUIRED_COLUMNS) { + const value = Number(cells[idx[col]]); + if (!Number.isFinite(value)) { + throw new Error( + `${csvPath}: row ${i + 1} column '${col}' is not numeric: ${JSON.stringify(cells[idx[col]])}`, + ); + } + cols[col].push(value); + } + } + return cols; +} + +// Roll an OHLCV series up to `bucketMs`-sized buckets keyed on each bar's +// `floor(timestamp / bucketMs)`. Input timestamps must be monotonic +// non-decreasing (the bundled BTCUSDT-1m dataset is contiguous, so this +// holds by construction). +function resample(cols, bucketMs) { + if (cols.timestamp.length === 0) { + throw new Error('resample: empty input series'); + } + const out = { timestamp: [], open: [], high: [], low: [], close: [], volume: [] }; + let bucketStart = Math.floor(cols.timestamp[0] / bucketMs) * bucketMs; + let [o, h, l, c, v] = [cols.open[0], cols.high[0], cols.low[0], cols.close[0], cols.volume[0]]; + + for (let i = 1; i < cols.timestamp.length; i++) { + const start = Math.floor(cols.timestamp[i] / bucketMs) * bucketMs; + if (start === bucketStart) { + if (cols.high[i] > h) h = cols.high[i]; + if (cols.low[i] < l) l = cols.low[i]; + c = cols.close[i]; + v += cols.volume[i]; + } else { + out.timestamp.push(bucketStart); + out.open.push(o); + out.high.push(h); + out.low.push(l); + out.close.push(c); + out.volume.push(v); + bucketStart = start; + o = cols.open[i]; + h = cols.high[i]; + l = cols.low[i]; + c = cols.close[i]; + v = cols.volume[i]; + } + } + // Flush the final open bucket. + out.timestamp.push(bucketStart); + out.open.push(o); + out.high.push(h); + out.low.push(l); + out.close.push(c); + out.volume.push(v); + return out; +} + +function summarize(label, cols) { + if (cols.close.length === 0) { + console.log(` ${label.padEnd(5)} (empty)`); + return; + } + const rsi = new wickra.RSI(14); + const macd = new wickra.MACD(12, 26, 9); + const adx = new wickra.ADX(14); + + let lastRsi = null; + let lastHist = null; + let lastAdx = null; + for (let i = 0; i < cols.close.length; i++) { + const r = rsi.update(cols.close[i]); + if (r !== null) lastRsi = r; + const m = macd.update(cols.close[i]); + if (m) lastHist = m.histogram; + const a = adx.update(cols.high[i], cols.low[i], cols.close[i]); + if (a) lastAdx = a.adx; + } + const lastClose = cols.close[cols.close.length - 1]; + const fmtR = lastRsi === null ? ' --' : lastRsi.toFixed(2).padStart(6); + const fmtH = lastHist === null ? ' -- ' : `${lastHist >= 0 ? '+' : ''}${lastHist.toFixed(2)}`.padStart(6); + const fmtA = lastAdx === null ? ' --' : lastAdx.toFixed(2).padStart(6); + console.log( + ` ${label.padEnd(5)} bars=${String(cols.close.length).padStart(5)} ` + + `last_close=${lastClose.toFixed(2).padStart(10)} ` + + `rsi=${fmtR} macd_hist=${fmtH} adx=${fmtA}`, + ); +} + +function main() { + const csvPath = process.argv[2] || DEFAULT_CSV; + let cols; + try { + cols = readCsv(csvPath); + } catch (err) { + console.error(`error: ${err.message}`); + process.exit(1); + } + console.log(`Multi-timeframe view of ${csvPath}`); + summarize('1m', cols); + for (const [label, mins] of [ + ['5m', 5], + ['15m', 15], + ['1h', 60], + ['4h', 240], + ['1d', 1440], + ]) { + summarize(label, resample(cols, mins * ONE_MINUTE_MS)); + } +} + +main(); diff --git a/examples/rust/src/bin/multi_timeframe.rs b/examples/rust/src/bin/multi_timeframe.rs new file mode 100644 index 00000000..26c9669b --- /dev/null +++ b/examples/rust/src/bin/multi_timeframe.rs @@ -0,0 +1,85 @@ +//! Multi-timeframe indicators with the Wickra Rust stack. +//! +//! Reads the bundled 1-minute BTCUSDT CSV (or a path passed on the command +//! line), resamples it via [`wickra_data::resample::resample_all`] to 5m / +//! 15m / 1h / 4h / 1d, and prints the last RSI(14), MACD(12,26,9) histogram +//! and ADX(14) at each timeframe. The Rust counterpart of +//! `examples/python/multi_timeframe.py`. +//! +//! Run with: +//! ```text +//! cargo run --release -p wickra-examples --bin multi_timeframe +//! ``` + +use std::env; +use std::path::PathBuf; + +use wickra::{Adx, Candle, Indicator, MacdIndicator, Rsi}; +use wickra_data::aggregator::Timeframe; +use wickra_data::csv::CandleReader; +use wickra_data::resample::resample_all; + +const ONE_MINUTE_MS: i64 = 60_000; + +fn default_csv() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("data") + .join("btcusdt-1m.csv") +} + +fn summarize(label: &str, candles: &[Candle]) { + if candles.is_empty() { + println!(" {label:<5} (empty)"); + return; + } + let mut rsi = Rsi::new(14).expect("RSI(14) constructor cannot fail"); + let mut macd = MacdIndicator::new(12, 26, 9).expect("MACD(12,26,9) constructor cannot fail"); + let mut adx = Adx::new(14).expect("ADX(14) constructor cannot fail"); + + let mut last_rsi: Option = None; + let mut last_hist: Option = None; + let mut last_adx: Option = None; + for c in candles { + if let Some(v) = rsi.update(c.close) { + last_rsi = Some(v); + } + if let Some(m) = macd.update(c.close) { + last_hist = Some(m.histogram); + } + if let Some(a) = adx.update(*c) { + last_adx = Some(a.adx); + } + } + let last_close = candles.last().expect("non-empty").close; + println!( + " {label:<5} bars={:>5} last_close={last_close:>10.2} rsi={} macd_hist={} adx={}", + candles.len(), + last_rsi.map_or_else(|| " --".to_string(), |v| format!("{v:>6.2}")), + last_hist.map_or_else(|| " -- ".to_string(), |v| format!("{v:+6.2}")), + last_adx.map_or_else(|| " --".to_string(), |v| format!("{v:>6.2}")), + ); +} + +fn main() -> Result<(), Box> { + let path = env::args().nth(1).map_or_else(default_csv, PathBuf::from); + + println!("Multi-timeframe view of {}", path.display()); + + let mut reader = CandleReader::open(&path)?; + let ones: Vec = reader.read_all()?; + summarize("1m", &ones); + + for &(label, minutes) in &[ + ("5m", 5_i64), + ("15m", 15), + ("1h", 60), + ("4h", 240), + ("1d", 1440), + ] { + let tf = Timeframe::millis(minutes * ONE_MINUTE_MS)?; + let resampled = resample_all(tf, ones.iter().copied().map(Ok))?; + summarize(label, &resampled); + } + Ok(()) +}