feat(data): native live Binance kline feed in 9 languages (+ 3d/1M intervals) (#313)

* feat(data): C-ABI Binance feed + Go binding (F4 wip)

C ABI exposes the existing async BinanceKlineStream (tokio + TLS, auto-reconnect,
mock-server-tested in wickra-data) through a blocking poll: wickra_binance_connect
/ _next(out, timeout_ms) -> {1 event, 0 timeout, -1 closed} / _close / _free over
an opaque BinanceStream that owns a current-thread runtime. WickraKlineEvent
carries OHLCV + open_time + is_closed + a 16-byte symbol buffer. `live-binance`
is now a default feature of wickra-c (the published DLL ships the feed; the wasm
build drops it via --no-default-features).

Go: NewBinanceFeed(symbols, interval, baseURL) + Next(timeout) + Close, with a
deterministic error-path smoke (the connect->event pipeline is covered by the
Rust mock-WS-server tests).

* feat(data): Binance feed C# + Java bindings (F4 wip)

C#: BinanceFeed(symbols, interval, baseUrl?) + Next(timeout) -> KlineEvent? +
Dispose; bespoke WickraKlineEvent native struct (fixed symbol buffer + byte
is_closed) since the scalar struct parser can't model it. `char` maps to `byte`
for the const char* params.

Java: BinanceFeed + KlineEvent record + BinanceInterval enum over Panama FFM;
the event is read at hand-computed offsets (symbol@0, doubles@16..48,
open_time@56, is_closed@64; 72-byte struct). Both with deterministic error-path
smokes (pipeline covered by the Rust mock-WS-server tests).

* feat(data): Binance feed R binding (F4 wip)

R: BinanceFeed(symbols, interval, base_url) + binance_next(feed, timeout_ms) ->
named list | NULL + binance_close, via bespoke .Call glue (wk_binance_*). The
glue + its registration entries are gated out of the Emscripten/wasm build
(#ifndef __EMSCRIPTEN__) since r-universe/webR has no raw sockets. NAMESPACE
exports added by hand (roxygen2 not installed locally). Deterministic error-path
smoke; pipeline covered by the Rust mock-WS-server tests.

* feat(data): native Binance feed for Node + Python; CHANGELOG (F4 complete)

Node (napi) BinanceFeed: new(symbols, interval, baseUrl?) + next(timeoutMs) ->
KlineEvent | null + close. Python (pyo3) BinanceFeed: same, with next releasing
the GIL (py.detach) while it waits. Both drive the mock-server-tested async
BinanceKlineStream on a single-thread tokio runtime (blocking poll); wickra-data
gains the live-binance feature + tokio in each binding.

Completes F4: the live Binance kline feed is now native in all 9 languages
(WASM excluded), with no third-party WebSocket client in any of them.
This commit is contained in:
kingchenc
2026-06-16 02:01:37 +02:00
committed by GitHub
parent baf4d0ff47
commit 3a709d9a66
30 changed files with 1127 additions and 5 deletions
+3 -1
View File
@@ -25,9 +25,11 @@ workspace = true
[dependencies]
wickra-core = { workspace = true }
wickra-data = { workspace = true }
wickra-data = { workspace = true, features = ["live-binance"] }
napi = { version = "2.16", features = ["napi8"] }
napi-derive = "2.16"
# Drives the async Binance feed behind the blocking poll.
tokio = { version = "1", features = ["rt", "net", "time"] }
[build-dependencies]
napi-build = "2"
+19
View File
@@ -0,0 +1,19 @@
// The live Binance feed's connect → read → reconnect pipeline is covered
// deterministically by the Rust mock-WS-server tests in wickra-data. Here we only
// assert the binding's error paths, which need no network.
const test = require('node:test');
const assert = require('node:assert/strict');
const { BinanceFeed } = require('..');
test('binance feed rejects an unknown interval', () => {
assert.throws(() => new BinanceFeed('BTCUSDT', 99));
});
test('binance feed rejects an empty symbol list', () => {
assert.throws(() => new BinanceFeed('', 1));
});
test('binance feed rejects an unreachable endpoint', () => {
assert.throws(() => new BinanceFeed('BTCUSDT', 1, 'ws://127.0.0.1:1'));
});
+35
View File
@@ -603,6 +603,17 @@ export interface CandleValue {
volume: number
timestamp: number
}
/** One event from the live Binance feed. */
export interface KlineEvent {
symbol: string
open: number
high: number
low: number
close: number
volume: number
openTime: number
isClosed: boolean
}
export type SmaNode = SMA
export declare class SMA {
constructor(period: number)
@@ -5939,6 +5950,30 @@ export declare class VolumeWeightedMacd {
isReady(): boolean
warmupPeriod(): number
}
export type BinanceFeedNode = BinanceFeed
/**
* A live Binance kline feed. `next` is a blocking poll (it waits up to the
* timeout on the calling thread) driving the mock-server-tested wickra-data
* `BinanceKlineStream` on a single-thread tokio runtime — use a short timeout in
* a loop, or run it on a Worker thread, to keep the event loop responsive.
*/
export declare class BinanceFeed {
/**
* Connect to Binance's live kline stream for the given comma-separated
* `symbols` (case-insensitive) at the given `interval` code (`0..=15`).
* `baseUrl` overrides the endpoint (omit for production; pass a `ws://` URL
* to target a test server).
*/
constructor(symbols: string, interval: number, baseUrl?: string | undefined | null)
/**
* Poll for the next kline event, waiting up to `timeoutMs` milliseconds.
* Returns the event, or `null` on timeout (call again). Throws once the
* stream is closed.
*/
next(timeoutMs: number): KlineEvent | null
/** Close the stream; subsequent `next` calls throw. */
close(): void
}
export type TickAggregatorNode = TickAggregator
/** Roll trade ticks up into fixed-timeframe OHLCV candles. */
export declare class TickAggregator {
File diff suppressed because one or more lines are too long
+132
View File
@@ -21884,6 +21884,138 @@ pub struct CandleValue {
pub timestamp: f64,
}
/// One event from the live Binance feed.
#[napi(object)]
pub struct KlineEvent {
pub symbol: String,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
pub open_time: f64,
pub is_closed: bool,
}
/// Map a `u8` interval code (`0..=15`, the `Interval` declaration order) to the
/// feed interval.
fn binance_interval(code: u8) -> Option<wickra_data::live::binance::Interval> {
use wickra_data::live::binance::Interval;
Some(match code {
0 => Interval::OneSecond,
1 => Interval::OneMinute,
2 => Interval::ThreeMinutes,
3 => Interval::FiveMinutes,
4 => Interval::FifteenMinutes,
5 => Interval::ThirtyMinutes,
6 => Interval::OneHour,
7 => Interval::TwoHours,
8 => Interval::FourHours,
9 => Interval::SixHours,
10 => Interval::EightHours,
11 => Interval::TwelveHours,
12 => Interval::OneDay,
13 => Interval::ThreeDays,
14 => Interval::OneWeek,
15 => Interval::OneMonth,
_ => return None,
})
}
/// A live Binance kline feed. `next` is a blocking poll (it waits up to the
/// timeout on the calling thread) driving the mock-server-tested wickra-data
/// `BinanceKlineStream` on a single-thread tokio runtime — use a short timeout in
/// a loop, or run it on a Worker thread, to keep the event loop responsive.
#[napi(js_name = "BinanceFeed")]
pub struct BinanceFeedNode {
runtime: tokio::runtime::Runtime,
inner: wickra_data::live::binance::BinanceKlineStream,
}
#[napi]
impl BinanceFeedNode {
/// Connect to Binance's live kline stream for the given comma-separated
/// `symbols` (case-insensitive) at the given `interval` code (`0..=15`).
/// `baseUrl` overrides the endpoint (omit for production; pass a `ws://` URL
/// to target a test server).
#[napi(constructor)]
pub fn new(symbols: String, interval: u8, base_url: Option<String>) -> napi::Result<Self> {
let iv = binance_interval(interval).ok_or_else(|| {
NapiError::new(
Status::InvalidArg,
"unknown interval code (expected 0..=15)",
)
})?;
let symbol_list: Vec<String> = symbols
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.collect();
if symbol_list.is_empty() {
return Err(NapiError::new(
Status::InvalidArg,
"at least one symbol is required",
));
}
let mut config = wickra_data::live::binance::BinanceConfig::default();
if let Some(url) = base_url {
config.base_url = url;
}
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| NapiError::new(Status::GenericFailure, e.to_string()))?;
let inner = runtime
.block_on(
wickra_data::live::binance::BinanceKlineStream::connect_with_config(
&symbol_list,
iv,
config,
),
)
.map_err(map_data_err)?;
Ok(Self { runtime, inner })
}
/// Poll for the next kline event, waiting up to `timeoutMs` milliseconds.
/// Returns the event, or `null` on timeout (call again). Throws once the
/// stream is closed.
#[napi]
pub fn next(&mut self, timeout_ms: f64) -> napi::Result<Option<KlineEvent>> {
let dur = std::time::Duration::from_millis(timeout_ms.max(0.0) as u64);
let runtime = &self.runtime;
let inner = &mut self.inner;
let result = runtime.block_on(tokio::time::timeout(dur, inner.next_event()));
match result {
Ok(Ok(Some(ev))) => Ok(Some(KlineEvent {
symbol: ev.symbol,
open: ev.candle.open,
high: ev.candle.high,
low: ev.candle.low,
close: ev.candle.close,
volume: ev.candle.volume,
#[allow(clippy::cast_precision_loss)]
open_time: ev.candle.timestamp as f64,
is_closed: ev.is_closed,
})),
Ok(Ok(None) | Err(_)) => Err(NapiError::new(
Status::GenericFailure,
"binance feed closed",
)),
Err(_) => Ok(None),
}
}
/// Close the stream; subsequent `next` calls throw.
#[napi]
pub fn close(&mut self) {
let runtime = &self.runtime;
let inner = &mut self.inner;
let _ = runtime.block_on(inner.close());
}
}
/// Roll trade ticks up into fixed-timeframe OHLCV candles.
#[napi(js_name = "TickAggregator")]
pub struct TickAggregatorNode {