# Node.js / WebAssembly API 参考 TechKit Node.js 绑定的完整 API 参考。TechKit 提供两个 npm 包:`techkit`(核心版)和 `techkit-full`(完整版)。 ## 包选择指南 ### techkit(核心版)- 推荐大多数用户使用 **特性:** - ✅ 158+ 核心指标(兼容 TA-Lib) - ✅ 体积小(WASM ~200KB) - ✅ 支持 Node.js 和浏览器 - ✅ 自动选择最优后端(原生模块或 WASM) **使用场景:** - 大多数应用 - 常用技术指标(SMA、RSI、MACD、BBANDS 等) - 有体积限制 - 不需要高级分析功能 **安装:** ```bash npm install techkit ``` ### techkit-full(完整版)- 完整功能 **特性:** - ✅ 全部 189 个指标 - ✅ 高级分析(风险指标、波动率模型、形态识别) - ✅ 体积较大(WASM ~800KB) - ✅ 支持 Node.js 和浏览器 **使用场景:** - 需要完整功能集 - 风险指标(夏普比率、索提诺比率、VaR 等) - 波动率模型(GARCH、EWMA 等) - 形态识别(谐波形态、图表形态等) **安装:** ```bash npm install techkit-full ``` ### 功能对比 | 功能 | techkit | techkit-full | |---------|---------|--------------| | 核心指标(TA-Lib) | ✅ 158 | ✅ 158 | | 高级分析 | ❌ | ✅ 31 | | 风险指标 | ❌ | ✅ Sharpe、Sortino、VaR、CVaR | | 波动率模型 | ❌ | ✅ GARCH、EWMA、Parkinson | | 形态识别 | ❌ | ✅ 谐波、图表形态 | | K 线形态 | ✅ 19 核心 | ✅ 61 完整 | | WASM 体积 | ~200KB | ~800KB | | Node.js 原生模块 | ✅ | ✅ | | 浏览器支持 | ✅ | ✅ | **如何选择:** - 如果不确定,选择 `techkit`(核心版) - 如果需要风险分析、形态识别等功能,选择 `techkit-full` - 两个包的 API 完全相同,可无缝切换 ## 快速开始 ### techkit(核心版)示例 ```javascript import { init, SMA, RSI, MACD, getBackend } from 'techkit'; // 步骤 1:初始化(使用前必需) await init(); console.log(`Backend: ${getBackend()}`); // 输出:'native' 或 'wasm' // 步骤 2:创建指标实例 const sma = new SMA(20); // 20 周期简单移动平均线 const rsi = new RSI(14); // 14 周期相对强弱指数 const macd = new MACD({ fastPeriod: 12, // 快线 EMA 周期 slowPeriod: 26, // 慢线 EMA 周期 signalPeriod: 9 // 信号线 EMA 周期 }); // 步骤 3:增量更新(用于实时流) const result = sma.update(100.5); if (result.valid) { console.log('SMA:', result.value); } // 步骤 4:批量计算(用于历史数据) const prices = new Float64Array([100, 101, 102, 103, 104, 105]); const smaValues = sma.calculate(prices); console.log('SMA values:', smaValues); // 步骤 5:清理(重要!) sma.dispose(); rsi.dispose(); macd.dispose(); ``` ### techkit-full 示例 ```javascript // 相同的导入模式,只是包名不同 import { init, SMA, RSI, SharpeRatio, GARCHVolatility } from 'techkit-full'; await init(); // 核心指标(与 techkit 相同) const sma = new SMA(20); const rsi = new RSI(14); // 高级功能(仅 techkit-full) const sharpe = new SharpeRatio({ period: 252, riskFreeRate: 0.02 }); const garch = new GARCHVolatility({ alpha: 0.1, beta: 0.85, omega: 0.0001 }); // 相同的使用模式 const returns = new Float64Array([0.01, 0.02, -0.01, 0.03, -0.02]); const sharpeValue = sharpe.calculate(returns); console.log('Sharpe Ratio:', sharpeValue); // 清理 sma.dispose(); rsi.dispose(); sharpe.dispose(); garch.dispose(); ``` (browser-usage-cdn-zh)= ## 浏览器用法(CDN) ```html ``` ## 后端选择 TechKit 支持两种后端:**原生模块(N-API)**和 **WebAssembly(WASM)**。系统会自动选择最优后端,也可以手动指定。 ### 后端对比 | 特性 | 原生模块(N-API) | WASM | |---------|----------------|------| | **性能** | ⚡ 最快(原生 C++) | 🚀 非常快(接近原生) | | **平台支持** | Linux、macOS、Windows | 所有平台 | | **包体积** | 较大(平台特定) | 较小(通用) | | **加载速度** | 快 | 稍慢(需要编译) | | **浏览器支持** | ❌ | ✅ | | **推荐** | Node.js 服务端 | 浏览器、跨平台 | ### 自动选择(推荐) TechKit 会自动选择最优后端: 1. **Node.js 环境**:优先尝试原生模块,失败则回退到 WASM 2. **浏览器环境**:自动使用 WASM ```javascript import { init, getBackend, isInitialized } from 'techkit'; // 自动选择最优后端 await init(); // 检查当前使用的后端 console.log(`Current backend: ${getBackend()}`); // 输出:'native' 或 'wasm' console.log(`Initialized: ${isInitialized()}`); // 输出:true ``` ### 手动后端选择 强制使用特定后端: ```javascript import { initWithBackend, getBackend } from 'techkit'; // 强制使用原生模块后端(仅 Node.js) try { await initWithBackend('native'); console.log('Native backend loaded'); } catch (error) { console.error('Native unavailable, falling back to WASM'); await initWithBackend('wasm'); } // 强制使用 WASM 后端(所有环境) await initWithBackend('wasm'); console.log(`Current backend: ${getBackend()}`); // 输出:'wasm' ``` ## API 参考 ### 初始化 ```typescript // 自动选择最佳后端 function init(): Promise; // 强制使用特定后端 function initWithBackend(backend: 'native' | 'wasm'): Promise; // 检查状态 function isInitialized(): boolean; function getBackend(): 'native' | 'wasm' | null; // 版本信息 function version(): string; // "1.2.5" function versionTuple(): [number, number, number]; // [1, 2, 5] ``` ### 结果类型 ```typescript interface IndicatorResult { value: number; // 计算值 valid: boolean; // 如果预热完成则为 true } 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`: ```typescript abstract class Indicator { // 使用单个值更新 update(value: number): IndicatorResult; // 使用 OHLCV K 线更新 updateOHLCV(bar: OHLCV): IndicatorResult; // 批量计算 calculate(data: Float64Array | number[]): Float64Array; // 使用 OHLCV 数据计算 calculateOHLCV( open: Float64Array | number[], high: Float64Array | number[], low: Float64Array | number[], close: Float64Array | number[], volume: Float64Array | number[] ): Float64Array; // 重置到初始状态 reset(): void; // 检查预热是否完成 isReady(): boolean; // 属性 readonly lookback: number; // 预热周期 readonly name: string; // 指标名称 // 清理(对 WASM 很重要!) dispose(): void; destroy(): void; // dispose() 的别名 } ``` ### 移动平均线 | 类 | 构造函数 | 描述 | |-------|-------------|-------------| | `SMA` | `new SMA(period)` | 简单移动平均线 | | `EMA` | `new EMA(period)` | 指数移动平均线 | | `WMA` | `new WMA(period)` | 加权移动平均线 | | `DEMA` | `new DEMA(period)` | 双指数移动平均线 | | `TEMA` | `new TEMA(period)` | 三指数移动平均线 | | `KAMA` | `new KAMA(period?)` | 考夫曼自适应移动平均线 | | `TRIMA` | `new TRIMA(period)` | 三角移动平均线 | | `T3` | `new T3(period?, vfactor?)` | T3 移动平均线 | ### 动量指标 | 类 | 构造函数 | 描述 | |-------|-------------|-------------| | `RSI` | `new RSI(period?)` | 相对强弱指数 | | `MACD` | `new MACD(config?)` | MACD | | `STOCH` | `new STOCH(config?)` | 随机振荡器 | | `STOCHF` | `new STOCHF(k?, d?)` | 快速随机指标 | | `CCI` | `new CCI(period?)` | 商品通道指数 | | `ADX` | `new ADX(period?)` | 平均趋向指数 | | `MOM` | `new MOM(period?)` | 动量指标 | | `ROC` | `new ROC(period?)` | 变动率 | | `WILLR` | `new WILLR(period?)` | 威廉指标 %R | | `MFI` | `new MFI(period?)` | 资金流量指标 | | `APO` | `new APO(fast?, slow?)` | 绝对价格振荡器 | | `PPO` | `new PPO(fast?, slow?)` | 百分比价格振荡器 | | `CMO` | `new CMO(period?)` | 钱德动量振荡器 | | `AROON` | `new AROON(period?)` | Aroon 指标 | | `ULTOSC` | `new ULTOSC(p1?, p2?, p3?)` | 终极振荡器 | | `TRIX` | `new TRIX(period?)` | 三重指数平均 | ### 波动率指标 | 类 | 构造函数 | 说明 | |-------|-------------|-------| | `ATR` | `new ATR(period?)` | 需要 OHLCV | | `NATR` | `new NATR(period?)` | 需要 OHLCV | | `TRANGE` | `new TRANGE()` | 需要 OHLCV | | `BBANDS` | `new BBANDS(config?)` | 多输出 | ### 成交量指标 | 类 | 构造函数 | |-------|-------------| | `OBV` | `new OBV()` | | `AD` | `new AD()` | | `ADOSC` | `new ADOSC(fast?, slow?)` | ### 统计函数 | 类 | 构造函数 | |-------|-------------| | `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?)` | ### K 线形态 核心版提供 19 种基本形态: ```javascript 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(看涨)、-100(看跌)、0(无) doji.dispose(); ``` 可用的 CDL 形态:`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` ### 指标链 ```javascript import { Chain, RSI, EMA } from 'techkit'; // RSI 经过 EMA 平滑 const chain = new Chain([new RSI(14), new EMA(9)]); const smoothedRSI = chain.calculate(prices); chain.dispose(); ``` (typescript-support-zh)= ## TypeScript 支持 包含完整的 TypeScript 类型定义: ```typescript 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); ``` ## 实时图表集成示例 ```javascript 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(); } } // 用法 const indicators = new ChartIndicators(); await indicators.initialize(); for (const bar of priceData) { const values = indicators.onNewBar(bar); renderChart(values); } indicators.dispose(); ``` ## 内存管理 ⚠️ **重要**:使用完指标后务必调用 `dispose()`! ```javascript // 正确:适当的清理 const sma = new SMA(20); try { const result = sma.calculate(prices); // 使用结果 } finally { sma.dispose(); } // 错误:内存泄漏(特别是在 WASM 模式下) function calculate() { const sma = new SMA(20); return sma.calculate(prices); // sma 从未被清理! } ``` ## 性能提示 1. **复用指标实例:** ```javascript // 正确 const sma = new SMA(20); for (const dataset of datasets) { sma.reset(); const result = sma.calculate(dataset); } sma.dispose(); // 错误:每次都创建新实例 for (const dataset of datasets) { const sma = new SMA(20); const result = sma.calculate(dataset); sma.dispose(); } ``` 2. **对大型数据集使用 Float64Array:** ```javascript // 更快 const prices = new Float64Array([100, 101, 102, ...]); const result = sma.calculate(prices); // 较慢(转换开销) const prices = [100, 101, 102, ...]; const result = sma.calculate(prices); ``` 3. **优先使用原生模块后端(如果可用):** ```javascript try { await initWithBackend('native'); } catch { await initWithBackend('wasm'); } ```