Node.js / WebAssembly API Reference
Complete API reference for TechKit Node.js bindings. TechKit provides two npm packages: techkit (core) and techkit-full (full version).
Package Selection Guide
techkit (Core) - Recommended for Most Users
Features:
✅ 158+ core indicators (TA-Lib compatible)
✅ Small size (WASM ~200KB)
✅ Node.js and Browser support
✅ Auto-selects optimal backend (Native or WASM)
Use Cases:
Most applications
Common technical indicators (SMA, RSI, MACD, BBANDS, etc.)
Size constraints
No advanced analytics needed
Installation:
npm install techkit
techkit-full (Full Version) - Complete Features
Features:
✅ All 189 indicators
✅ Advanced analytics (risk metrics, volatility models, pattern recognition)
✅ Larger size (WASM ~800KB)
✅ Node.js and Browser support
Use Cases:
Complete feature set needed
Risk metrics (Sharpe Ratio, Sortino Ratio, VaR, etc.)
Volatility models (GARCH, EWMA, etc.)
Pattern recognition (harmonic patterns, chart patterns, etc.)
Installation:
npm install techkit-full
Feature Comparison
Feature |
techkit |
techkit-full |
|---|---|---|
Core Indicators (TA-Lib) |
✅ 158 |
✅ 158 |
Advanced Analytics |
❌ |
✅ 31 |
Risk Metrics |
❌ |
✅ Sharpe, Sortino, VaR, CVaR |
Volatility Models |
❌ |
✅ GARCH, EWMA, Parkinson |
Pattern Recognition |
❌ |
✅ Harmonic, Chart Patterns |
Candlestick Patterns |
✅ 19 core |
✅ 61 complete |
WASM Size |
~200KB |
~800KB |
Node.js Native |
✅ |
✅ |
Browser Support |
✅ |
✅ |
How to Choose:
If unsure, choose
techkit(core)If you need risk analysis, pattern recognition, etc., choose
techkit-fullBoth packages have identical APIs, seamless switching
Quick Start
techkit (Core) Example
import { init, SMA, RSI, MACD, getBackend } from 'techkit';
// Step 1: Initialize (required before use)
await init();
console.log(`Backend: ${getBackend()}`); // Output: 'native' or 'wasm'
// Step 2: Create indicator instances
const sma = new SMA(20); // 20-period Simple Moving Average
const rsi = new RSI(14); // 14-period Relative Strength Index
const macd = new MACD({
fastPeriod: 12, // Fast EMA period
slowPeriod: 26, // Slow EMA period
signalPeriod: 9 // Signal EMA period
});
// Step 3: Incremental update (for real-time streams)
const result = sma.update(100.5);
if (result.valid) {
console.log('SMA:', result.value);
}
// Step 4: Batch calculation (for historical data)
const prices = new Float64Array([100, 101, 102, 103, 104, 105]);
const smaValues = sma.calculate(prices);
console.log('SMA values:', smaValues);
// Step 5: Cleanup (important!)
sma.dispose();
rsi.dispose();
macd.dispose();
techkit-full Example
// Same import pattern, just different package name
import { init, SMA, RSI, SharpeRatio, GARCHVolatility } from 'techkit-full';
await init();
// Core indicators (same as techkit)
const sma = new SMA(20);
const rsi = new RSI(14);
// Advanced features (techkit-full only)
const sharpe = new SharpeRatio({ period: 252, riskFreeRate: 0.02 });
const garch = new GARCHVolatility({ alpha: 0.1, beta: 0.85, omega: 0.0001 });
// Same usage pattern
const returns = new Float64Array([0.01, 0.02, -0.01, 0.03, -0.02]);
const sharpeValue = sharpe.calculate(returns);
console.log('Sharpe Ratio:', sharpeValue);
// Cleanup
sma.dispose();
rsi.dispose();
sharpe.dispose();
garch.dispose();
Browser Usage (CDN)
<script type="module">
import { init, SMA, RSI, MACD } from 'https://unpkg.com/techkit@1.2.5/dist/browser.mjs';
await init();
const sma = new SMA(20);
const result = sma.update(100.5);
if (result.valid) {
console.log(`SMA: ${result.value}`);
}
</script>
Backend Selection
TechKit supports two backends: Native (N-API) and WebAssembly (WASM). The system auto-selects the optimal backend, or you can manually specify.
Backend Comparison
Feature |
Native (N-API) |
WASM |
|---|---|---|
Performance |
⚡ Fastest (native C++) |
🚀 Very fast (near-native) |
Platform Support |
Linux, macOS, Windows |
All platforms |
Package Size |
Larger (platform-specific) |
Smaller (universal) |
Load Speed |
Fast |
Slightly slower (needs compilation) |
Browser Support |
❌ |
✅ |
Recommended |
Node.js server-side |
Browser, cross-platform |
Auto-Selection (Recommended)
TechKit automatically selects the optimal backend:
Node.js environment: Tries Native first, falls back to WASM
Browser environment: Automatically uses WASM
import { init, getBackend, isInitialized } from 'techkit';
// Auto-select optimal backend
await init();
// Check which backend is active
console.log(`Current backend: ${getBackend()}`); // Output: 'native' or 'wasm'
console.log(`Initialized: ${isInitialized()}`); // Output: true
Manual Backend Selection
To force a specific backend:
import { initWithBackend, getBackend } from 'techkit';
// Force Native backend (Node.js only)
try {
await initWithBackend('native');
console.log('Native backend loaded');
} catch (error) {
console.error('Native unavailable, falling back to WASM');
await initWithBackend('wasm');
}
// Force WASM backend (all environments)
await initWithBackend('wasm');
console.log(`Current backend: ${getBackend()}`); // Output: 'wasm'
API Reference
Initialization
// Auto-select best backend
function init(): Promise<void>;
// Force specific backend
function initWithBackend(backend: 'native' | 'wasm'): Promise<void>;
// Check status
function isInitialized(): boolean;
function getBackend(): 'native' | 'wasm' | null;
// Version info
function version(): string; // "1.2.5"
function versionTuple(): [number, number, number]; // [1, 2, 5]
Result Types
interface IndicatorResult {
value: number; // Calculated value
valid: boolean; // True if warmup complete
}
interface MACDResult {
macd: number;
signal: number;
histogram: number;
valid: boolean;
}
interface BBandsResult {
upper: number;
middle: number;
lower: number;
valid: boolean;
}
interface StochResult {
k: number;
d: number;
valid: boolean;
}
interface OHLCV {
open: number;
high: number;
low: number;
close: number;
volume: number;
}
Indicator Base Class
All indicators extend Indicator:
abstract class Indicator {
// Update with single value
update(value: number): IndicatorResult;
// Update with OHLCV bar
updateOHLCV(bar: OHLCV): IndicatorResult;
// Batch calculation
calculate(data: Float64Array | number[]): Float64Array;
// Calculate with OHLCV data
calculateOHLCV(
open: Float64Array | number[],
high: Float64Array | number[],
low: Float64Array | number[],
close: Float64Array | number[],
volume: Float64Array | number[]
): Float64Array;
// Reset to initial state
reset(): void;
// Check if warmup complete
isReady(): boolean;
// Properties
readonly lookback: number; // Warmup period
readonly name: string; // Indicator name
// Cleanup (important for WASM!)
dispose(): void;
destroy(): void; // Alias for dispose()
}
Moving Averages
Class |
Constructor |
Description |
|---|---|---|
|
|
Simple Moving Average |
|
|
Exponential Moving Average |
|
|
Weighted Moving Average |
|
|
Double Exponential MA |
|
|
Triple Exponential MA |
|
|
Kaufman Adaptive MA |
|
|
Triangular MA |
|
|
T3 Moving Average |
Momentum Indicators
Class |
Constructor |
Description |
|---|---|---|
|
|
Relative Strength Index |
|
|
MACD |
|
|
Stochastic Oscillator |
|
|
Fast Stochastic |
|
|
Commodity Channel Index |
|
|
Average Directional Index |
|
|
Momentum |
|
|
Rate of Change |
|
|
Williams %R |
|
|
Money Flow Index |
|
|
Absolute Price Oscillator |
|
|
Percentage Price Oscillator |
|
|
Chande Momentum Oscillator |
|
|
Aroon Indicator |
|
|
Ultimate Oscillator |
|
|
Triple Exponential Average |
Volatility Indicators
Class |
Constructor |
Notes |
|---|---|---|
|
|
Requires OHLCV |
|
|
Requires OHLCV |
|
|
Requires OHLCV |
|
|
Multi-output |
Volume Indicators
Class |
Constructor |
|---|---|
|
|
|
|
|
|
Statistics
Class |
Constructor |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Candlestick Patterns
19 essential patterns available in core:
import { CDL_DOJI, CDL_HAMMER, CDL_ENGULFING } from 'techkit';
const doji = new CDL_DOJI();
const result = doji.updateOHLCV({ open, high, low, close, volume });
// result.value: +100 (bullish), -100 (bearish), 0 (none)
doji.dispose();
Available CDL patterns: CDL_DOJI, CDL_HAMMER, CDL_HANGINGMAN,
CDL_ENGULFING, CDL_MORNINGSTAR, CDL_EVENINGSTAR, CDL_SHOOTINGSTAR,
CDL_INVERTEDHAMMER, CDL_PIERCING, CDL_DARKCLOUDCOVER, CDL_HARAMI,
CDL_3WHITESOLDIERS, CDL_3BLACKCROWS, CDL_MARUBOZU, CDL_SPINNINGTOP,
CDL_DRAGONFLYDOJI, CDL_GRAVESTONEDOJI, CDL_ABANDONEDBABY, CDL_BELTHOLD
Indicator Chaining
import { Chain, RSI, EMA } from 'techkit';
// RSI smoothed by EMA
const chain = new Chain([new RSI(14), new EMA(9)]);
const smoothedRSI = chain.calculate(prices);
chain.dispose();
TypeScript Support
Full TypeScript definitions are included:
import {
SMA, RSI, MACD, BBANDS,
IndicatorResult, MACDResult, BBandsResult,
SMAConfig, MACDConfig, BBandsConfig,
OHLCV, MAType
} from 'techkit';
const sma = new SMA(20);
const result: IndicatorResult = sma.update(100.5);
const macd = new MACD({ fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 });
const macdResult: MACDResult = macd.update(100.5);
Real-Time Chart Integration Example
import { init, SMA, RSI, MACD, BBANDS } from 'techkit';
class ChartIndicators {
constructor() {
this.sma20 = null;
this.sma50 = null;
this.rsi = null;
this.macd = null;
this.bbands = null;
}
async initialize() {
await init();
this.sma20 = new SMA(20);
this.sma50 = new SMA(50);
this.rsi = new RSI(14);
this.macd = new MACD();
this.bbands = new BBANDS({ period: 20 });
}
onNewBar(bar) {
const price = bar.close;
const sma20Result = this.sma20.update(price);
const sma50Result = this.sma50.update(price);
const rsiResult = this.rsi.update(price);
const macdResult = this.macd.update(price);
const bbandsResult = this.bbands.update(price);
return {
sma20: sma20Result.valid ? sma20Result.value : null,
sma50: sma50Result.valid ? sma50Result.value : null,
rsi: rsiResult.valid ? rsiResult.value : null,
macd: macdResult.valid ? {
macd: macdResult.macd,
signal: macdResult.signal,
histogram: macdResult.histogram
} : null,
bbands: bbandsResult.valid ? {
upper: bbandsResult.upper,
middle: bbandsResult.middle,
lower: bbandsResult.lower
} : null
};
}
dispose() {
this.sma20?.dispose();
this.sma50?.dispose();
this.rsi?.dispose();
this.macd?.dispose();
this.bbands?.dispose();
}
}
// Usage
const indicators = new ChartIndicators();
await indicators.initialize();
for (const bar of priceData) {
const values = indicators.onNewBar(bar);
renderChart(values);
}
indicators.dispose();
Memory Management
⚠️ Important: Always call dispose() when done with indicators!
// Good: proper cleanup
const sma = new SMA(20);
try {
const result = sma.calculate(prices);
// use result
} finally {
sma.dispose();
}
// Bad: memory leak (especially in WASM mode)
function calculate() {
const sma = new SMA(20);
return sma.calculate(prices);
// sma never disposed!
}
Performance Tips
Reuse indicator instances:
// Good const sma = new SMA(20); for (const dataset of datasets) { sma.reset(); const result = sma.calculate(dataset); } sma.dispose(); // Bad: creates new instance each time for (const dataset of datasets) { const sma = new SMA(20); const result = sma.calculate(dataset); sma.dispose(); }
Use Float64Array for large datasets:
// Faster const prices = new Float64Array([100, 101, 102, ...]); const result = sma.calculate(prices); // Slower (conversion overhead) const prices = [100, 101, 102, ...]; const result = sma.calculate(prices);
Prefer native backend when available:
try { await initWithBackend('native'); } catch { await initWithBackend('wasm'); }