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-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-full

  • Both 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

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

SMA

new SMA(period)

Simple Moving Average

EMA

new EMA(period)

Exponential Moving Average

WMA

new WMA(period)

Weighted Moving Average

DEMA

new DEMA(period)

Double Exponential MA

TEMA

new TEMA(period)

Triple Exponential MA

KAMA

new KAMA(period?)

Kaufman Adaptive MA

TRIMA

new TRIMA(period)

Triangular MA

T3

new T3(period?, vfactor?)

T3 Moving Average

Momentum Indicators

Class

Constructor

Description

RSI

new RSI(period?)

Relative Strength Index

MACD

new MACD(config?)

MACD

STOCH

new STOCH(config?)

Stochastic Oscillator

STOCHF

new STOCHF(k?, d?)

Fast Stochastic

CCI

new CCI(period?)

Commodity Channel Index

ADX

new ADX(period?)

Average Directional Index

MOM

new MOM(period?)

Momentum

ROC

new ROC(period?)

Rate of Change

WILLR

new WILLR(period?)

Williams %R

MFI

new MFI(period?)

Money Flow Index

APO

new APO(fast?, slow?)

Absolute Price Oscillator

PPO

new PPO(fast?, slow?)

Percentage Price Oscillator

CMO

new CMO(period?)

Chande Momentum Oscillator

AROON

new AROON(period?)

Aroon Indicator

ULTOSC

new ULTOSC(p1?, p2?, p3?)

Ultimate Oscillator

TRIX

new TRIX(period?)

Triple Exponential Average

Volatility Indicators

Class

Constructor

Notes

ATR

new ATR(period?)

Requires OHLCV

NATR

new NATR(period?)

Requires OHLCV

TRANGE

new TRANGE()

Requires OHLCV

BBANDS

new BBANDS(config?)

Multi-output

Volume Indicators

Class

Constructor

OBV

new OBV()

AD

new AD()

ADOSC

new ADOSC(fast?, slow?)

Statistics

Class

Constructor

STDDEV

new STDDEV(period?, nbdev?)

VAR

new VAR(period?)

LINEARREG

new LINEARREG(period?)

LINEARREG_SLOPE

new LINEARREG_SLOPE(period?)

LINEARREG_INTERCEPT

new LINEARREG_INTERCEPT(period?)

LINEARREG_ANGLE

new LINEARREG_ANGLE(period?)

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

  1. 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();
    }
    
  2. 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);
    
  3. Prefer native backend when available:

    try {
        await initWithBackend('native');
    } catch {
        await initWithBackend('wasm');
    }