npm package: @rki-js/sdk
Description: RKI - RSI & KD Phase Identification System SDK
Latest version: 0.0.1

# @rki/sdk

**RSI & KD 阶段识别系统** — 市场阶段分析 TypeScript SDK。

> TradingView Pine Script v6 RKI 指标的 1:1 TypeScript 移植版，零运行时依赖。

**RSI & KD Phase Identification System** — TypeScript SDK for market stage analysis.

> A 1:1 port of the TradingView Pine Script v6 RKI indicator to TypeScript, with zero runtime dependencies.

---

## 目录 / Contents

- [安装 / Installation](#安装--installation)
- [快速上手 / Quick Start](#快速上手--quick-start)
- [API 概览 / API Overview](#api-概览--api-overview)
  - [核心引擎 / Core Engine](#核心引擎--core-engine)
  - [数据适配器 / Data Adapters](#数据适配器--data-adapters)
  - [可视化工具 / Visualization Utilities](#可视化工具--visualization-utilities)
  - [价格预测 / Price Prediction](#价格预测--price-prediction)
- [配置参数 / Configuration](#配置参数--configuration)
- [市场阶段值 / Market Stage Values](#市场阶段值--market-stage-values)
- [类型定义 / Type Definitions](#类型定义--type-definitions)
- [执行原理 / How It Works](#执行原理--how-it-works)

---

## 安装 / Installation

```bash
npm install @rki/sdk
# 或 / or
pnpm add @rki/sdk
```

**运行环境 / Runtime:** Node.js >= 22.0.0，支持 ESM 和 CJS 双格式 / supports both ESM and CJS.

---

## 快速上手 / Quick Start

### 批量处理历史数据 / Batch Process Historical Bars

```typescript
import { processBars, createBinanceAdapter } from '@rki/sdk'

// 获取历史 K 线数据 / Fetch historical OHLCV
const adapter = createBinanceAdapter()
const bars = await adapter.fetchOHLCV('BTCUSDT', '4h', { limit: 300 })

// 批量计算所有 bar 的指标 / Compute all snapshots
const { snapshots } = processBars(bars)

// 获取最新结果 / Get latest result
const latest = snapshots[snapshots.length - 1]
console.log(`综合市场阶段 / Market Stage: ${latest.marketStage}`) // -8 to +8
console.log(`RSI: ${latest.rsiVal.toFixed(1)}, K: ${latest.kVal.toFixed(1)}`)
console.log(`回调轮数 / Pullback Rounds: ${latest.pullbackRounds}`)
console.log(`预测价格 / Predicted Price: ${latest.predPrice.toFixed(2)}`)
```

### 逐 bar 实时处理 / Real-time Bar-by-Bar Processing

```typescript
import { createInitialState, processBar } from '@rki/sdk'
import type { OHLCVBar } from '@rki/sdk'

const { state: initialState, config } = createInitialState()
let state = initialState

function onNewBar(bar: OHLCVBar) {
  const result = processBar(state, bar, config)
  state = result.state // 更新状态以处理下一根 bar / update state for next bar
  console.log(result.snapshot.marketStage) // 综合阶段 / combined stage
}
```

### 自定义配置 / Custom Configuration

```typescript
import { processBars } from '@rki/sdk'

const { snapshots } = processBars(bars, {
  kd: { kd_k_len: 9, kd_ob: 75 },   // 覆盖 KD 参数 / override KD params
  rsi: { rsi_len: 21, rsi_ob: 65 },  // 覆盖 RSI 参数 / override RSI params
})
```

---

## API 概览 / API Overview

### 核心引擎 / Core Engine

```typescript
import { createInitialState, processBar, processBars } from '@rki/sdk'
```

#### `createInitialState(config?)`

创建初始 RKI 状态和已合并的配置对象。
Creates the initial RKI state and merged config object.

```typescript
createInitialState(config?: Partial<RKIConfig>): { state: RKIState, config: RKIConfig }
```

#### `processBar(state, bar, config)`

处理单根 K 线，返回新的不可变状态和当前快照。
Processes a single OHLCV bar. Returns new immutable state and the snapshot for this bar.

```typescript
processBar(state: RKIState, bar: OHLCVBar, config: RKIConfig): { state: RKIState, snapshot: RKISnapshot }
```

**执行顺序（每 bar）/ Per-bar execution order:**
1. RSI RMA 计算（gains / losses）
2. Stochastic %K / %D 计算
3. KD 阶段状态机更新
4. RSI 阶段状态机更新
5. 综合市场阶段合并（stage synthesis）
6. 回调轮数计数器更新
7. 价格预测（二分法，50 次迭代）
8. 输出快照 `RKISnapshot`

#### `processBars(bars, config?)`

批量处理所有 K 线，返回每 bar 的快照数组和最终状态。
Batch processes all bars. Returns an array of per-bar snapshots and the final state.

```typescript
processBars(bars: OHLCVBar[], config?: Partial<RKIConfig>): { state: RKIState, snapshots: RKISnapshot[] }
```

---

### 数据适配器 / Data Adapters

```typescript
import { createBinanceAdapter, createOKXAdapter } from '@rki/sdk'
```

#### Binance 适配器 / Binance Adapter

```typescript
const binance = createBinanceAdapter()

// 基础用法 / Basic usage
const bars = await binance.fetchOHLCV('BTCUSDT', '4h', { limit: 500 })

// 时间范围 / Time range
const bars2 = await binance.fetchOHLCV('BTCUSDT', '1h', {
  limit: 200,
  startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // 7天前 / 7 days ago
  endTime: Date.now(),
})
```

**支持的 interval：** `1s` `1m` `3m` `5m` `15m` `30m` `1h` `2h` `4h` `6h` `8h` `12h` `1d` `3d` `1w` `1M`

#### OKX 适配器 / OKX Adapter

```typescript
const okx = createOKXAdapter()
const bars = await okx.fetchOHLCV('BTC/USDT', '4h', { limit: 100 })
```

**支持的 interval：** `1m` `3m` `5m` `15m` `30m` `1H` `2H` `4H` `6H` `12H` `1D` `3D` `1W` `1M`
（传入小写 `4h` 会自动转为 `4H` / lowercase `4h` is auto-mapped to `4H`）

#### 自定义适配器 / Custom Adapter

```typescript
import type { DataAdapter, OHLCVBar } from '@rki/sdk'

const myAdapter: DataAdapter = {
  async fetchOHLCV(symbol, interval, options): Promise<OHLCVBar[]> {
    const raw = await fetchFromMyAPI(symbol, interval)
    return raw.map(r => ({
      time:   r.ts,
      open:   r.o,
      high:   r.h,
      low:    r.l,
      close:  r.c,
      volume: r.v,
    }))
  },
}
```

---

### 可视化工具 / Visualization Utilities

```typescript
import { getStageText, getStageColor, getBarHeight, getPullbackColor } from '@rki/sdk'
```

| 函数 / Function | 入参 / Input | 返回值示例 / Example Output |
|---|---|---|
| `getStageText(stage)` | marketStage (-8 to +8) | `'R:TD'`, `'K:BA'`, `'—'` |
| `getStageColor(stage)` | marketStage (-8 to +8) | `'#2265D4'`, `'#FFFFFF'` |
| `getBarHeight(stage)` | marketStage (-8 to +8) | `6` (max), `0` (neutral) |
| `getPullbackColor(rounds)` | pullbackRounds (0+) | `'#37F053'` / `'#EF4444'` |

```typescript
// 阶段标签 / Stage label
getStageText(8)     // 'R:TD'
getStageText(-3)    // 'K:BA'
getStageText(0)     // '—'

// 颜色（HEX）/ Color (hex)
getStageColor(8)    // '#2265D4'  RSI 出货 / RSI distribution (blue)
getStageColor(-8)   // '#37F053'  RSI 启动 / RSI breakout (green)
getStageColor(0)    // '#FFFFFF'  中性 / neutral (white)

// 信号条高度 1-6 / Signal bar height 1-6
getBarHeight(8)     // 6
getBarHeight(1)     // 3
getBarHeight(0)     // 0

// 回调轮数颜色 / Pullback rounds color
getPullbackColor(0) // '#37F053'  绿 / green
getPullbackColor(1) // '#F59E0B'  橙 / amber
getPullbackColor(2) // '#EF4444'  红 / red
getPullbackColor(3) // '#DC2626'  深红 / deep red
```

---

### 价格预测 / Price Prediction

```typescript
import { predictRSIAtPrice, findRSIMACrossPrice } from '@rki/sdk'
```

#### `predictRSIAtPrice(targetPrice, currentClose, gains, losses, rsiLen)`

给定**目标收盘价**，预测下一根 bar 结束后的 RSI 值。
Given a **target close price**, predicts the RSI value after the next bar closes.

```typescript
predictRSIAtPrice(
  targetPrice:  number,  // 假设的下一 bar 收盘价 / hypothetical next close
  currentClose: number,  // 当前收盘价 / current close
  rsiGains:     number,  // 当前 RMA gains（来自内部状态）/ current RMA gains
  rsiLosses:    number,  // 当前 RMA losses / current RMA losses
  rsiLen:       number,  // RSI 周期 / RSI period
): number
```

#### `findRSIMACrossPrice(rsiVal, rsiMaVal, close, gains, losses, rsiLen)`

二分法求解 **RSI 等于 RSI MA** 时所对应的未来价格（最多 50 次迭代，精度 0.5）。
Finds the price where **RSI would equal RSI MA** via bisection (50 iterations, 0.5 precision).

- 当 RSI > MA：返回 RSI 回落至 MA 水平所需的**下跌价格**
- 当 RSI < MA：返回 RSI 上升至 MA 水平所需的**上涨价格**
- 当 RSI == MA：返回 `NaN`

```typescript
findRSIMACrossPrice(
  rsiVal:    number,  // 当前 RSI / current RSI
  rsiMaVal:  number,  // 当前 RSI MA / current RSI MA
  close:     number,  // 当前收盘价 / current close
  gains:     number,  // 当前 RMA gains / current RMA gains
  losses:    number,  // 当前 RMA losses / current RMA losses
  rsiLen:    number,  // RSI 周期 / RSI period
): number             // 预测价格，RSI==MA 时为 NaN / predicted price, NaN when RSI==MA
```

`RKISnapshot.predPrice` 和 `RKISnapshot.predPct` 由此函数自动填充：
`RKISnapshot.predPrice` and `RKISnapshot.predPct` are filled by this function automatically:

```typescript
const latest = snapshots[snapshots.length - 1]
const changePct = latest.predPct   // 预测涨跌幅 % / predicted change %
const crossPrice = latest.predPrice // RSI 交叉价格 / RSI/MA cross price
```

---

## 配置参数 / Configuration

所有参数均与 TradingView Pine Script v6 默认值一致。/ All parameters match TradingView Pine Script v6 defaults.

### KD 配置 / KD Config (`config.kd`)

| 参数 / Parameter | 默认值 / Default | 描述 / Description |
|---|---|---|
| `kd_k_len` | 14 | Stochastic K 周期 / K period |
| `kd_d_smooth` | 3 | Stochastic D 平滑周期 / D smoothing period |
| `kd_ob` | 80 | 超买判定线 / Overbought level |
| `kd_os` | 20 | 超卖判定线 / Oversold level |
| `kd_top_exhaust_lvl` | 70 | 顶部衰竭触发线（K 跌破此线进入 P3）/ Top exhaust trigger (K crosses below → P3) |
| `kd_bot_recovery_lvl` | 40 | 底部修复触发线（K 升破此线进入 P3）/ Bottom recovery trigger (K crosses above → P3) |
| `kd_retrace_lvl` | 50 | 顶部重置回调线（K,D 均跌破清除阶段）/ Top reset retrace line |
| `kd_bounce_lvl` | 50 | 底部重置反弹线（K,D 均升破清除阶段）/ Bottom reset bounce line |

### RSI 配置 / RSI Config (`config.rsi`)

| 参数 / Parameter | 默认值 / Default | 描述 / Description |
|---|---|---|
| `rsi_len` | 14 | RSI 计算周期 / RSI period |
| `rsi_ma_len` | 14 | RSI MA 平滑周期 / RSI MA smoothing period |
| `rsi_ob` | 70 | RSI 超买判定线 / RSI overbought level |
| `rsi_os` | 30 | RSI 超卖判定线 / RSI oversold level |
| `rsi_top_exhaust_lvl` | 70 | 顶部衰竭线（MA 跌破此线进入 P3）/ Top exhaust (MA crosses below → P3) |
| `rsi_bot_recovery_lvl` | 35 | 底部修复触发线（RSI 升破此线退出底部）/ Bottom recovery trigger |
| `rsi_retrace_lvl` | 55 | 顶部重置回调线（RSI 跌破清除阶段）/ Top reset retrace line |
| `rsi_bounce_lvl` | 45 | 底部重置反弹线（RSI 升破清除阶段）/ Bottom reset bounce line |
| `rsi_extreme_lvl` | 20 | 极度超卖线（直接进入 ACCUM）/ Extreme oversold (direct entry to ACCUM) |
| `rsi_bot_gap_thr` | 10 | RSI/MA 间距阈值（触发 ACCUM 需小于此值）/ Bottom gap threshold |

---

## 市场阶段值 / Market Stage Values

综合市场阶段（`marketStage`）范围为 **-8 至 +8**，正值表示顶部周期，负值表示底部周期，0 为中性。

Combined market stage (`marketStage`) ranges **-8 to +8**: positive = top cycle, negative = bottom cycle, 0 = neutral.

### 顶部阶段 / Top Cycle

| 阶段值 / Stage | 短码 / Code | 中文描述 | English Description |
|---|---|---|---|
| +1 | K:TI | KD 顶部启动 | KD Top Init — K,D enter overbought zone |
| +2 | R:TI | RSI 顶部启动 | RSI Top Init — RSI enters overbought zone |
| +3 | K:TB | KD 顶部构建 | KD Top Build — sustained overbought momentum |
| +4 | R:TB | RSI 顶部构建 | RSI Top Build — RSI holds above OB, MA below |
| +5 | K:TE | KD 动能衰竭 | KD Top Exhaust — K drops below exhaust level |
| +6 | R:TE | RSI 动能衰竭 | RSI Top Exhaust — RSI MA drops below exhaust level |
| +7 | K:TD | KD 出货阶段 | KD Top Distribution — K crosses below D above OS |
| +8 | R:TD | RSI 出货阶段 | RSI Top Distribution — RSI crosses below MA above OS |

### 底部阶段 / Bottom Cycle

| 阶段值 / Stage | 短码 / Code | 中文描述 | English Description |
|---|---|---|---|
| -1 | K:BP | KD 恐慌杀跌 | KD Bottom Panic — K,D enter oversold zone |
| -2 | R:BP | RSI 恐慌杀跌 | RSI Bottom Panic — RSI enters oversold zone |
| -3 | K:BA | KD 吸筹筑底 | KD Bottom Accum — K > D while in oversold |
| -4 | R:BA | RSI 吸筹筑底 | RSI Bottom Accum — RSI/MA gap narrows or extreme |
| -5 | K:BR | KD 修复阶段 | KD Bottom Recovery — K crosses above recovery level |
| -6 | R:BR | RSI 修复阶段 | RSI Bottom Recovery — RSI crosses above recovery level |
| -7 | K:BB | KD 启动上涨 | KD Bottom Breakout — K crosses above D while recovering |
| -8 | R:BB | RSI 启动上涨 | RSI Bottom Breakout — RSI crosses above MA while recovering |

### 阶段合并规则 / Synthesis Rules

同一 bar 上 KD 和 RSI 可能处于不同阶段，合并逻辑如下：
When KD and RSI are on different phases on the same bar, the synthesis logic is:

1. **冲突屏蔽 / Conflict masking** — RSI 与 KD 方向相反时，KD 阶段被屏蔽为 0
   / KD stage is masked to 0 when KD and RSI are in opposite cycle directions
2. **取大原则 / Take larger** — 取绝对值较大者作为综合阶段值
   / The stage with larger absolute value wins
3. **RSI 优先 / RSI priority** — 绝对值相同时 RSI 优先
   / RSI wins on a tie

---

## 类型定义 / Type Definitions

```typescript
/** 单根 K 线数据 / Single OHLCV bar */
interface OHLCVBar {
  time:   number  // Unix 毫秒时间戳 / Unix ms timestamp
  open:   number
  high:   number
  low:    number
  close:  number
  volume: number
}

/** 每根 bar 的计算结果快照 / Per-bar computed result */
interface RKISnapshot {
  // --- 指标值 / Indicator values ---
  rsiVal:    number  // RSI (0–100)
  rsiMaVal:  number  // RSI MA (0–100)
  kVal:      number  // Stochastic %K (0–100)
  dVal:      number  // Stochastic %D (0–100)

  // --- 子系统阶段（0=无，1=P1，2=P2，3=P3，4=P4）/ Sub-system phases ---
  kdTopPhase:  number  // KD 顶部阶段 / KD top phase
  kdBotPhase:  number  // KD 底部阶段 / KD bottom phase
  rsiTopPhase: number  // RSI 顶部阶段 / RSI top phase
  rsiBotPhase: number  // RSI 底部阶段 / RSI bottom phase

  // --- 子系统有符号阶段 / Subsystem signed stages ---
  kdStage:  number  // KD 有符号综合阶段 (-7 to +7)
  rsiStage: number  // RSI 有符号综合阶段 (-8 to +8)

  // --- 综合市场阶段 / Combined market stage ---
  marketStage: number  // 综合阶段 (-8 to +8)

  // --- 回调统计 / Pullback stats ---
  pullbackRounds: number  // 已记录的回调轮数（0 起）

  // --- 价格预测 / Price prediction ---
  predPrice: number  // RSI/MA 交叉所需价格（RSI==MA 时为 NaN）
  predPct:   number  // 预测涨跌幅 % (NaN if RSI==MA)
}

/** 数据适配器接口 / Data adapter interface */
interface DataAdapter {
  fetchOHLCV(
    symbol:   string,
    interval: string,
    options?: { limit?: number; startTime?: number; endTime?: number }
  ): Promise<OHLCVBar[]>
}
```

---

## 执行原理 / How It Works

### 状态机结构 / State Machine Structure

RKI 的核心是两套**独立的阶段状态机**（KD 和 RSI），每套各有顶部和底部两条路径，共 8 个阶段：

RKI runs two **independent phase state machines** (KD and RSI), each with top and bottom paths of 4 phases:

```
顶部周期 / Top Cycle:
  TOP_INIT (P1) → TOP_BUILD (P2) → TOP_EXHAUST (P3, transient) → TOP_DIST (P4)
         ↑                                    ↓ (auto-clears)
         └──────────── 阶段清除 / phase clear ←──────────────────────────┘

底部周期 / Bottom Cycle:
  BOT_PANIC (P1) → BOT_ACCUM (P2) → BOT_RECOVERY (P3, transient) → BOT_BREAKOUT (P4)
```

P3（衰竭/修复）是**瞬态阶段**，在同一 bar 内完成转换后自动清除。
Phase 3 (Exhaust/Recovery) is a **transient phase** that auto-clears within the same bar after triggering a transition.

### KD 与 RSI 的状态机差异 / KD vs RSI State Machine Differences

| 条件 / Condition | KD | RSI |
|---|---|---|
| TOP_INIT 触发 | K > OB AND D > OB AND K > D | RSI > OB |
| TOP_BUILD 进入 | K > OB AND D > OB AND K ≤ D | RSI > OB AND MA ≤ OB |
| TOP_EXHAUST 触发 | K 跌破 `kd_top_exhaust_lvl` | MA 跌破 `rsi_top_exhaust_lvl` |
| TOP_DIST 进入 | K 跌破 D（均在 OS 之上）| RSI 跌破 MA（均在 OS 之上）|
| 顶部清除 | K AND D 均跌破 `kd_retrace_lvl` | RSI 跌破 `rsi_retrace_lvl` |
| BOT_PANIC 触发 | K < OS AND D < OS | RSI < OS |
| BOT_ACCUM 触发 | K > D（仍在 OS 区域）| MA−RSI < `rsi_bot_gap_thr` OR RSI < `rsi_extreme_lvl` |
| BOT_RECOVERY 触发 | K 升破 `kd_bot_recovery_lvl` | RSI 升破 `rsi_bot_recovery_lvl` |
| BOT_BREAKOUT 进入 | K 升破 D（仍在恢复区间）| RSI 升破 MA（仍在恢复区间）|
| 底部清除 | K AND D 均升破 `kd_bounce_lvl` | RSI 升破 `rsi_bot_recovery_lvl` |

### 回调轮数计数 / Pullback Round Counter

每个 bar 按以下**固定顺序**执行（与 Pine Script 行为一致）：

The pullback counter is updated in the following **fixed order** each bar (matching Pine Script behavior):

1. **重置（最高优先级）** — RSI < OS 时，轮数清零
   / **Reset (highest priority)** — rounds = 0 when RSI < OS
2. **建顶标记** — marketStage >= 3 时，设置"已建顶"标志
   / **Top flag** — sets "hasBuiltTop" when marketStage ≥ 3
3. **计数** — 已建顶 AND marketStage <= -1 时，`rounds += 1`，并清除建顶标志
   / **Count** — increments rounds when hasBuiltTop AND marketStage ≤ -1, then clears flag

---

## License

MIT