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.
This commit is contained in:
@@ -4,6 +4,4 @@ go 1.23
|
||||
|
||||
require github.com/wickra-lib/wickra/bindings/go v0.0.0
|
||||
|
||||
require github.com/coder/websocket v1.8.14
|
||||
|
||||
replace github.com/wickra-lib/wickra/bindings/go => ../../bindings/go
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
|
||||
@@ -5,12 +5,11 @@
|
||||
package market
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
wickra "github.com/wickra-lib/wickra/bindings/go"
|
||||
)
|
||||
|
||||
// Bar is one OHLCV bar with a millisecond timestamp.
|
||||
@@ -62,39 +61,25 @@ func SyntheticCandlesStep(count int, startTimestamp, stepMs int64) []Bar {
|
||||
return bars
|
||||
}
|
||||
|
||||
// LoadOhlcvCsv loads an OHLCV CSV. It accepts rows of
|
||||
// timestamp,open,high,low,close,volume or open,high,low,close,volume; a
|
||||
// non-numeric first row is treated as a header and skipped.
|
||||
// LoadOhlcvCsv loads a timestamp,open,high,low,close,volume OHLCV CSV with
|
||||
// Wickra's native CandleReader (header validation, BOM and field-whitespace
|
||||
// tolerance) — no manual CSV parsing.
|
||||
func LoadOhlcvCsv(path string) ([]Bar, error) {
|
||||
file, err := os.Open(path)
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var bars []Bar
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
cols := strings.Split(line, ",")
|
||||
if _, err := strconv.ParseFloat(cols[0], 64); err != nil {
|
||||
continue // header row
|
||||
}
|
||||
f := func(i int) float64 {
|
||||
v, _ := strconv.ParseFloat(strings.TrimSpace(cols[i]), 64)
|
||||
return v
|
||||
}
|
||||
if len(cols) >= 6 {
|
||||
ts, _ := strconv.ParseInt(strings.TrimSpace(cols[0]), 10, 64)
|
||||
bars = append(bars, Bar{f(1), f(2), f(3), f(4), f(5), ts})
|
||||
} else {
|
||||
bars = append(bars, Bar{f(0), f(1), f(2), f(3), f(4), int64(len(bars))})
|
||||
}
|
||||
reader, err := wickra.NewCandleReader(string(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bars, scanner.Err()
|
||||
defer reader.Close()
|
||||
candles := reader.Read()
|
||||
bars := make([]Bar, len(candles))
|
||||
for i, c := range candles {
|
||||
bars[i] = Bar{c.Open, c.High, c.Low, c.Close, c.Volume, c.Timestamp}
|
||||
}
|
||||
return bars, nil
|
||||
}
|
||||
|
||||
// EquityResult holds summary statistics for a long-only equity curve.
|
||||
|
||||
@@ -1,54 +1,42 @@
|
||||
// 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.
|
||||
// Uses Wickra's native BinanceFeed — no third-party WebSocket client. Requires
|
||||
// network access (build-only in CI). Runs for up to 60 seconds.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
wickra "github.com/wickra-lib/wickra/bindings/go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
const url = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"
|
||||
fmt.Printf("Connecting to %s (up to 60s)...\n", url)
|
||||
fmt.Println("Streaming live BTCUSDT 1-minute klines from Binance (up to 60s)...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
conn, _, err := websocket.Dial(ctx, url, nil)
|
||||
// Native feed: a blocking poll over the same tested stream as the Rust core.
|
||||
feed, err := wickra.NewBinanceFeed("BTCUSDT", wickra.OneMinute, "")
|
||||
if err != nil {
|
||||
log.Fatalf("dial: %v", err)
|
||||
log.Fatalf("connect: %v", err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
defer feed.Close()
|
||||
|
||||
ema, _ := wickra.NewEma(20)
|
||||
defer ema.Close()
|
||||
|
||||
for {
|
||||
_, data, err := conn.Read(ctx)
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
// next() returns the event and ok=true, ok=false on timeout (poll again),
|
||||
// or an error once the stream is closed.
|
||||
event, ok, err := feed.Next(time.Second)
|
||||
if err != nil {
|
||||
fmt.Println("Done (time limit reached).")
|
||||
fmt.Println("Done (feed closed).")
|
||||
return
|
||||
}
|
||||
|
||||
var msg struct {
|
||||
K struct {
|
||||
Close string `json:"c"`
|
||||
} `json:"k"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &msg); err != nil || msg.K.Close == "" {
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
closePx, err := strconv.ParseFloat(msg.K.Close, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fmt.Printf("close=%.2f EMA(20)=%.2f\n", closePx, ema.Update(closePx))
|
||||
fmt.Printf("close=%.2f EMA(20)=%.2f\n", event.Close, ema.Update(event.Close))
|
||||
}
|
||||
fmt.Println("Done (time limit reached).")
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
wickra "github.com/wickra-lib/wickra/bindings/go"
|
||||
"github.com/wickra-lib/wickra/examples/go/internal/market"
|
||||
@@ -29,26 +28,21 @@ func resample(source []market.Bar, factor int) []market.Bar {
|
||||
if factor <= 1 {
|
||||
return source
|
||||
}
|
||||
// Native Resampler: bucket by an absolute timeframe (the synthetic bars step
|
||||
// 60_000 ms, so factor minutes == factor*60_000 ms). No hand-written bucketing.
|
||||
r, _ := wickra.NewResampler(int64(factor) * 60_000)
|
||||
defer r.Close()
|
||||
var out []market.Bar
|
||||
for i := 0; i < len(source); i += factor {
|
||||
end := i + factor
|
||||
if end > len(source) {
|
||||
end = len(source)
|
||||
emit := func(c wickra.Candle) {
|
||||
out = append(out, market.Bar{Open: c.Open, High: c.High, Low: c.Low, Close: c.Close, Volume: c.Volume, Timestamp: c.Timestamp})
|
||||
}
|
||||
for _, b := range source {
|
||||
if c, ok := r.Update(b.Open, b.High, b.Low, b.Close, b.Volume, b.Timestamp); ok {
|
||||
emit(c)
|
||||
}
|
||||
high, low, volume := math.Inf(-1), math.Inf(1), 0.0
|
||||
for j := i; j < end; j++ {
|
||||
high = math.Max(high, source[j].High)
|
||||
low = math.Min(low, source[j].Low)
|
||||
volume += source[j].Volume
|
||||
}
|
||||
out = append(out, market.Bar{
|
||||
Open: source[i].Open,
|
||||
High: high,
|
||||
Low: low,
|
||||
Close: source[end-1].Close,
|
||||
Volume: volume,
|
||||
Timestamp: source[i].Timestamp,
|
||||
})
|
||||
}
|
||||
if c, ok := r.Flush(); ok {
|
||||
emit(c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user