Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 75 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,13 @@ const vs = vwapSession(high, low, close, volume, [1, 1]);
## Stateful API (streaming)

```ts
import { createRSI, createVWAPSession } from "ta-crypto";
import { createSMA, createEMA, createRSI, createVWAPSession } from "ta-crypto";

const sma14 = createSMA(14);
const ema14 = createEMA(14);
const rsi14 = createRSI(14);
const nextSma = sma14.next(101.25);
const nextEma = ema14.next(101.25);
const nextRsi = rsi14.next(101.25);

const vwap = createVWAPSession();
Expand All @@ -48,6 +52,24 @@ const nextVwap = vwap.next({
});
```

Websocket-like streaming loop:

```ts
import { createEMA, createRSI } from "ta-crypto";

const ema21 = createEMA(21);
const rsi14 = createRSI(14);

ws.on("message", (tick) => {
const price = Number(tick.last);
const e = ema21.next(price);
const r = rsi14.next(price);
if (e !== null && r !== null) {
// strategy signal path
}
});
```

## Examples

Real-world entry points live in `examples/`:
Expand Down Expand Up @@ -84,9 +106,23 @@ Streaming parity:

External parity:

| Indicator set | Reference libs | Tolerance |
| --- | --- | --- |
| SMA/EMA/RSI/MACD/BBANDS/ATR/ADX | TA-Lib, pandas-ta, technicalindicators | 1e-8 |
Policy source: `scripts/compat-policy.json`

| Indicator | Burn-in | Tolerance | Blocking refs | Non-blocking refs |
| --- | --- | --- | --- | --- |
| SMA(14) | 14 | 1e-10 | TA-Lib, technicalindicators | pandas-ta |
| EMA(14) | 14 | 1e-10 | TA-Lib, technicalindicators | pandas-ta |
| RSI(14) | 28 | 5e-2 | TA-Lib, technicalindicators | pandas-ta |
| MACD(12,26,9) | 80 | 2e-2 | TA-Lib, technicalindicators | pandas-ta |
| BBANDS(20,2) | 20 | 1e-10 | TA-Lib, technicalindicators | pandas-ta |
| ATR(14) | 56 | 1.5e-1 | TA-Lib, technicalindicators | pandas-ta |
| ADX/+DI/-DI(14) | 90 | 1.5 | TA-Lib, technicalindicators | pandas-ta |

Warmup and alignment rules:
- References are left-padded to full series length before comparison.
- Comparison starts at indicator-specific burn-in and uses only overlapping non-null points.
- `TA-Lib` and `technicalindicators` are release-blocking checks in CI.
- `pandas-ta` is telemetry-only (warns when divergent or unavailable by environment).

Generate/review vectors:

Expand Down Expand Up @@ -158,28 +194,57 @@ Limitations:
- Orderflow proxies infer pressure from candle direction and volume; they are not a replacement for L2/L3 order book data.
- Different libraries use different warmup conventions; comparisons use overlapping non-null windows.

## Candle Contracts
## Typing and Inputs

`ta-crypto` public APIs accept two input styles:
- Primitive arrays (`number[]`) for low-level control.
- Candle objects with long keys (`open/high/low/close/volume/time`) or aliases (`o/h/l/c/v/t`).

Single-series APIs (for example `sma`, `ema`, `rsi`, `macd`, `bbands`) accept:

```ts
import { rsi } from "ta-crypto";

const close = [101, 102, 103, 104];
const candles = [{ o: 100, h: 102, l: 99, c: 101, v: 10, t: 1 }];

rsi(close, 14);
rsi(candles, 14); // uses candle close/c
```

OHLC/OHLCV APIs (for example `vwap`, `stoch`, `atr`, `natr`, `mfi`, `adx`) accept:

```ts
import { atr, vwap } from "ta-crypto";

atr([102, 103], [99, 100], [101, 102], 14);
atr([{ open: 100, high: 102, low: 99, close: 101, volume: 10 }], 14);

vwap([102, 103], [99, 100], [101, 102], [10, 12]);
vwap([{ o: 100, h: 102, l: 99, c: 101, v: 10 }]);
```

Use typed candles plus helpers:
Helpers:

```ts
import { pluckClose, toOHLCV } from "ta-crypto";

const close = pluckClose(candles);
const { open, high, low, close: c, volume } = toOHLCV(candles, 0);
const ohlcv = toOHLCV(candles, 0);
const ohlcvFromArrays = toOHLCV({ o: [1, 2], h: [3, 4], l: [0, 1], c: [2, 3], v: [5, 6] });
```

Validation:
- Multi-series indicators enforce equal lengths (`assertSameLength`).
- Candle helpers validate finite numeric fields with index-specific error messages.
- Multi-series APIs enforce equal lengths.
- Numeric inputs are validated as finite numbers with index-aware messages when possible.

## Module Imports

```ts
import { sma } from "ta-crypto/indicators";
import { vwapSession } from "ta-crypto/crypto";
import { toOHLCV } from "ta-crypto/candles";
import { createRSI } from "ta-crypto/stateful";
import { createSMA, createEMA, createRSI } from "ta-crypto/stateful";
```

## Bench (internal baseline, 10k candles)
Expand Down
36 changes: 15 additions & 21 deletions scripts/compare-python-refs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

import numpy as np
import pandas as pd
import talib
try:
import talib
TALIB_ERROR = None
except Exception as exc: # pragma: no cover - environment dependent
talib = None
TALIB_ERROR = exc

try:
import pandas_ta as pta
Expand All @@ -16,26 +21,10 @@

ROOT = Path(__file__).resolve().parents[1]
COMPAT_PATH = ROOT / "test" / "fixtures" / "compat-current.json"

TOL = {
"sma": 1e-10,
"ema": 1e-10,
"rsi": 5e-2,
"macd": 2e-2,
"bbands": 1e-10,
"atr": 1.5e-1,
"adx": 1.5,
}

BURN = {
"sma": 14,
"ema": 14,
"rsi": 28,
"macd": 80,
"bbands": 20,
"atr": 56,
"adx": 90,
}
POLICY_PATH = ROOT / "scripts" / "compat-policy.json"
POLICY = json.loads(POLICY_PATH.read_text(encoding="utf-8"))
TOL = {k: float(v["tolerance"]) for k, v in POLICY["indicators"].items()}
BURN = {k: int(v["burnIn"]) for k, v in POLICY["indicators"].items()}


def as_arr(values):
Expand Down Expand Up @@ -69,6 +58,11 @@ def col(df, prefix):


def main():
if talib is None:
print(f"[compat][python] TA-Lib unavailable: {TALIB_ERROR}")
print("[compat][python] install requirements: pip install -r scripts/requirements-compat.txt")
sys.exit(1)

data = json.loads(COMPAT_PATH.read_text(encoding="utf-8"))
inp = data["input"]
ours = data["ours"]
Expand Down
27 changes: 8 additions & 19 deletions scripts/compare-technicalindicators.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,18 @@ import { resolve } from "node:path";
import { SMA, EMA, RSI, MACD, BollingerBands, ATR, ADX } from "technicalindicators";

const compat = JSON.parse(readFileSync(resolve(process.cwd(), "test/fixtures/compat-current.json"), "utf8"));
const policy = JSON.parse(readFileSync(resolve(process.cwd(), "scripts/compat-policy.json"), "utf8"));
const { close, high, low } = compat.input;
const ours = compat.ours;
const len = close.length;

const toleranceByIndicator = {
sma: 1e-10,
ema: 1e-10,
rsi: 5e-2,
macd: 2e-2,
bbands: 1e-10,
atr: 1.5e-1,
adx: 1.5
};

const burnInByIndicator = {
sma: 14,
ema: 14,
rsi: 28,
macd: 80,
bbands: 20,
atr: 56,
adx: 90
};
const toleranceByIndicator = Object.fromEntries(
Object.entries(policy.indicators).map(([key, value]) => [key, value.tolerance])
);

const burnInByIndicator = Object.fromEntries(
Object.entries(policy.indicators).map(([key, value]) => [key, value.burnIn])
);

let failures = 0;

Expand Down
17 changes: 17 additions & 0 deletions scripts/compat-policy.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"version": 1,
"indicators": {
"sma": { "tolerance": 1e-10, "burnIn": 14 },
"ema": { "tolerance": 1e-10, "burnIn": 14 },
"rsi": { "tolerance": 5e-2, "burnIn": 28 },
"macd": { "tolerance": 2e-2, "burnIn": 80 },
"bbands": { "tolerance": 1e-10, "burnIn": 20 },
"atr": { "tolerance": 1.5e-1, "burnIn": 56 },
"adx": { "tolerance": 1.5, "burnIn": 90 }
},
"rules": {
"alignment": "left-pad reference series with null/NaN to full length and compare only overlapping non-null points",
"blockingReferences": ["TA-Lib", "technicalindicators"],
"nonBlockingReferences": ["pandas-ta"]
}
}
5 changes: 3 additions & 2 deletions scripts/export-compat-vectors.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { writeFileSync } from "node:fs";
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { sma, ema, rsi, macd, bbands, atr, adx } from "../dist/index.js";

Expand Down Expand Up @@ -40,7 +40,8 @@ const ours = {
const payload = {
meta: {
length: input.close.length,
generatedAt: new Date().toISOString()
generatedAt: new Date().toISOString(),
compatPolicy: JSON.parse(readFileSync(resolve(process.cwd(), "scripts/compat-policy.json"), "utf8"))
},
input,
ours
Expand Down
Loading