Content
# Stock SDK
[](https://www.npmjs.com/package/stock-sdk)
[](https://www.npmjs.com/package/stock-sdk)
[](https://github.com/chengzuopeng/stock-sdk/blob/master/LICENSE)
[](https://stock-sdk.linkdiary.cn/mcp/)
[](https://stock-sdk.linkdiary.cn/mcp/)
**[English](./README_EN.md)** | English
A JavaScript SDK for stock market data, designed for frontend and Node.js.
No Python, no backend services required. Get real-time stock quotes and K-line data for A-shares, Hong Kong stocks, US stocks, and public funds directly in the browser or Node.js. Comes with a command-line tool and MCP server for easy access to market data and AI integration.
**✨ Zero dependencies, lightweight package | 🌐 Browser + Node.js | 📦 ESM + CJS + subpath | 🧠 Complete TypeScript types | 🖥️ CLI | 🤖 MCP**
> ✨ **v2.0.0**: A major architecture upgrade (namespace API, unified symbol model, identifiable union of Quote, unified error system, CLI / MCP / subpath export).
> Installation: `npm i stock-sdk`. For v1 upgrade, read [v1 → v2 migration guide](https://stock-sdk.linkdiary.cn/guide/migration-v1-to-v2) (breaking changes, no compatibility aliases).
## 📖 Official Documentation
> ## 👉 https://stock-sdk.linkdiary.cn
>
> Complete API, namespace overview, CLI / MCP guide, online Playground, and v1 → v2 migration documentation.
📦 [NPM](https://www.npmjs.com/package/stock-sdk) | 📖 [GitHub](https://github.com/chengzuopeng/stock-sdk) | 🎮 [Online Playground](https://stock-sdk.linkdiary.cn/playground/)
🧭 [Stock Dashboard](https://chengzuopeng.github.io/stock-dashboard/): A stock data dashboard demo built with stock-sdk.
## Why stock-sdk?
As a frontend engineer, you may have encountered these issues:
* Most stock market data tools are built with Python and are difficult to use directly in frontend applications.
* You want to create a stock dashboard or demo without maintaining a backend service.
* Financial interfaces often have inconsistent return formats, complex encoding (GBK, concurrency, batching).
**The goal of stock-sdk is simple:**
> To allow frontend engineers to obtain stock market data elegantly using JavaScript / TypeScript.
## Use Cases
* 📊 Stock market dashboards (Web / Admin)
* 📈 Data visualization (ECharts / TradingView)
* 🎓 Stock / finance course demos
* 🧪 Quantitative strategy prototype verification (JS / Node)
* 🕒 Node.js scheduled task to fetch market data
* 🖥️ Command-line tool for temporary market data queries / 🤖 AI tool integration
## Features
- ✅ **Zero dependencies**, runs on both browser and Node.js 18+; provides both **ESM** and **CommonJS**.
- ✅ **Namespace API**: `sdk.quotes.cn()` / `sdk.kline.cn()` / `sdk.options.etf.dailyKline()`, grouped by domain, with IDE auto-completion.
- ✅ **Unified symbol model**: `string` is a first-class citizen, `sh600519` / `600519` / `600519.SH` / `00700` / `hk00700` / `AAPL` / `105.AAPL` are parsed with tolerance; supports special indices (e.g., `930955`, `H30533`, `HSHCI`, `GDAXI`).
- ✅ **Real-time quotes and historical K-line data** for A-shares, Hong Kong stocks, US stocks, and public funds.
- ✅ **Technical indicators**: MA, MACD, BOLL, KDJ, RSI, WR, BIAS, CCI, ATR, OBV, ROC, DMI, SAR, KC.
- ✅ **Chip distribution (CYQ)**:获利比例 / 平均成本 / 90-70 成本区间与集中度 / 筹码峰直方图.
- ✅ **Signal / stock selection / backtesting**: `calcSignals` (event recognition, e.g., golden cross, overbought/oversold), chain stock selector, local backtesting.
- ✅ **Futures / options / capital flow / dragon and tiger list / northbound / large transactions / margin trading / limit up** and other extended data.
- ✅ **Fund depth data**: historical net value, real-time estimation, similar ranking trend, fund/ETF dividend distribution, **theme fund**.
- ✅ **Subpath export**: `stock-sdk/{indicators,signals,symbols,screener,cache,errors}`, pure computation without network layer, tree-shake friendly.
- ✅ **Unified error system**: only throws `SdkError` with standard `code`, importable from `stock-sdk/errors`.
- ✅ **Request governance**: provider-level retry / rate limiting / circuit breaking + injectable `fetchImpl` / `signal` / lifecycle `hooks`.
- ✅ **CLI**: `stock-sdk quote 600519` for terminal market data queries.
- ✅ **Built-in MCP server**: `stock-sdk mcp` for one-line AI tool integration (zero dependencies, no `@modelcontextprotocol/sdk`).
## Installation
```bash
# Latest version (v2: namespace API / CLI / MCP)
npm install stock-sdk
# Legacy version (v1: archived, only critical fixes)
npm install stock-sdk@legacy
```
## Quick Start
```ts
import { StockSDK } from 'stock-sdk';
const sdk = new StockSDK();
// Namespace API (v2) — symbol writing tolerance, '600519' / 'sh600519' / '600519.SH' are all valid
const quotes = await sdk.quotes.cnSimple(['sh000001', 'sz000858', 'sh600519']);
quotes.forEach((q) => {
console.log(`${q.name}: ${q.price} (${q.changePercent}%)`);
});
// Historical K-line data + technical indicators
const kline = await sdk.kline.withIndicators('600519', {
period: 'daily',
indicators: { ma: { periods: [5, 10, 20] }, macd: {} },
});
// Full market A-share quotes (5000+ stocks, built-in concurrency control)
const all = await sdk.batch.cn({ concurrency: 5 });
console.log(`Total ${all.length} stocks`);
```
## Command-Line Tool (CLI)
After installation, you get the `stock-sdk` command (or use `npx`):
```bash
# Market data (automatically identifies market by code)
npx stock-sdk quote 600519 00700 AAPL
# K-line data + output truncation
npx stock-sdk kline 600519 --period weekly --limit 30
# With technical indicators
npx stock-sdk indicators 600519 --ma 5,10,20 --macd
# Search
npx stock-sdk search 茅台
# Direct access to any namespace method
npx stock-sdk quotes cn sh600519 sz000001
```
Default JSON output, add `--format table|csv`, `--pretty`, `--limit N`.
## 🤖 AI / MCP Integration
v2 comes with a built-in zero-dependency MCP server, start with one command:
```bash
npx stock-sdk mcp
```
Integrate with Cursor / Claude Desktop / Codex / Gemini (configure `mcpServers`):
```json
{
"mcpServers": {
"stock-sdk": {
"command": "npx",
"args": ["-y", "stock-sdk", "mcp"]
}
}
}
```
Environment variable `STOCK_SDK_MCP_TOOLS=core|full|<comma-separated tool names>` controls the toolset range (default `core`).
👉 [Full MCP documentation](https://stock-sdk.linkdiary.cn/mcp/)
## Signal / Stock Selection / Backtesting
```ts
import { calcSignals } from 'stock-sdk/signals';
import { screen, backtest } from 'stock-sdk/screener';
// Event recognition (e.g., golden cross, overbought/oversold) based on K-line data with indicators
const signals = calcSignals(klineWithIndicators, {
ma: { fast: 5, slow: 20 },
rsi: {},
});
// Chain stock selector (input any quote array, pure local, no network)
const picks = screen(allQuotes)
.where((q) => q.pe != null && q.pe < 20)
.where((q) => q.changePercent > 3)
.sortBy((q) => q.amount)
.top(20);
// Local backtesting
const report = backtest({
klines,
strategy: (bar, i, all) => 'hold', // returns 'buy' | 'sell' | 'hold'
});
console.log(report.totalReturn, report.winRate, report.maxDrawdown);
```
## Request Governance and Errors
```ts
import { StockSDK } from 'stock-sdk';
import { HttpError, getSdkErrorCode } from 'stock-sdk/errors';
const sdk = new StockSDK({
retry: { maxRetries: 2, baseDelay: 500 },
providerPolicies: {
eastmoney: { timeout: 12000, rateLimit: { requestsPerSecond: 3, maxBurst: 3 } },
},
});
try {
await sdk.quotes.cnSimple(['sh600519']);
} catch (error) {
// v2 only throws SdkError with unified code
if (error instanceof HttpError) console.log(error.status, error.statusText);
console.log(getSdkErrorCode(error)); // HTTP_ERROR / NETWORK_ERROR / TIMEOUT / ABORTED / PARSE_ERROR ...
}
```
## Subpath Export
For pure computation (indicators / symbols / signals / stock selection), import from subpath, bundle will not include `RequestClient` and providers:
```ts
// 14 indicators, 17 pure functions:
// calcSMA / calcEMA / calcWMA / calcMA / calcMACD / calcBOLL / calcKDJ /
// calcRSI / calcWR / calcBIAS / calcCCI / calcATR / calcOBV / calcROC /
// calcDMI / calcSAR / calcKC
import { calcMACD, calcKDJ } from 'stock-sdk/indicators';
import { normalizeSymbol, toTencentSymbol } from 'stock-sdk/symbols';
import { calcSignals } from 'stock-sdk/signals';
import { screen, backtest } from 'stock-sdk/screener';
import { MemoryCacheStore, cacheThrough } from 'stock-sdk/cache';
import { SdkError, isSdkError, getSdkErrorCode } from 'stock-sdk/errors';
```
## Market Support Matrix
The coverage of different markets varies, use this table to quickly determine if SDK covers your scenario.
- ✅ Supported | ⚠️ Partially supported (see notes) | ❌ Not implemented | — Not applicable
| Capability | A-shares | Hong Kong stocks | US stocks | Public funds | Futures | Options |
|------|:----:|:----:|:----:|:--------:|:----:|:----:|
| Real-time quotes | ✅ | ✅ | ✅ | ✅ | ✅ Global futures | ✅ ETF / 中金所 / Commodity |
| Historical K-line data (daily/weekly/monthly) | ✅ | ✅ | ✅ | ⚠️ On-site ETF/LOF | ✅ Domestic + Global | ✅ |
| Minute K-line data (5/15/30/60) | ✅ | ✅ `kline.hkMinute` | ✅ `kline.usMinute` | ⚠️ On-site ETF/LOF | ❌ | ❌ |
| Chip distribution (CYQ) | ✅ `chips.cn` | ✅ `chips.hk` | ✅ `chips.us` | — | — | — |
| Intraday ticks (1 minute) | ✅ `quotes.timeline` | ✅ `kline.hkMinute`(period='1') | ✅ `kline.usMinute`(period='1') | ⚠️ On-site ETF/LOF | ❌ | ✅ ETF options |
| Dividend distribution | ✅ | ❌ | ❌ | ✅ Funds + ETFs | — | — |
| Capital flow | ✅ Individual stocks/index/rankings/sections | ❌ | ❌ | — | — | — |
| Sections (industry / concept) | ✅ | ❌ | ❌ | ❌ | — | — |
| Dragon and tiger list | ✅ | — | — | — | — | ✅ Options dragon and tiger list |
| Shanghai-Hong Kong-Shenzhen Stock Connect / Northbound funds | ✅ Northbound | ✅ Southbound | — | — | — | — |
| Large transactions / margin trading | ✅ | ❌ | ❌ | — | — | — |
| Limit up / abnormal trading | ✅ | — | — | — | — | — |
| Full market code list / batch quotes | ✅ 5000+ | ✅ | ✅ | ✅ Code | ❌ | ❌ |
| Inventory data | — | — | — | — | ✅ Domestic + COMEX | — |
| Trading calendar | ✅ `calendar.*` | ⚠️ Only market status | ⚠️ Only market status | — | — | — |
> **Data delay**: Real-time quotes come from public interfaces like Tencent Finance / East Money, **not real-time matching**, usually with tens of seconds to minutes delay, not suitable for high-frequency trading decisions.
## API Overview (Namespaces)
💡 For the complete API, see [official documentation](https://stock-sdk.linkdiary.cn/api/). All v2 methods are mounted under the namespace:
| Namespace | Representative Methods |
|---|---|
| `sdk.quotes` | `.cn` / `.cnSimple` / `.hk` / `.us` / `.fund` / `.fundFlow` / `.largeOrder` / `.timeline` |
| `sdk.codes` | `.cn` / `.us` / `.hk` / `.fund` |
| `sdk.batch` | `.cn` / `.hk` / `.us` / `.byCodes` / `.raw` |
| `sdk.kline` | `.cn` / `.cnMinute` / `.hk` / `.hkMinute` / `.us` / `.usMinute` / `.withIndicators` |
| `sdk.chips` | `.cn` / `.hk` / `.us` (Chip distribution: profit ratio / average cost / cost interval / chip peak) |
| `sdk.board` | `.industry.*` / `.concept.*` (`list` / `spot` / `constituents` / `kline` / `minuteKline`) |
| `sdk.options` | `.index.*` / `.etf.*` / `.commodity.*` / `.cffex.*` / `.lhb` |
| `sdk.futures` | `.kline` / `.globalSpot` / `.globalKline` / `.inventory` / `.comexInventory` … |
| `sdk.fundFlow` | `.individual` / `.market` / `.rank` / `.sectorRank` / `.sectorHistory` |
| `sdk.northbound` | `.minute` / `.summary` / `.holdingRank` / `.history` / `.individual` |
| `sdk.marketEvent` | `.ztPool` / `.stockChanges`(support multiple types / `'all'`) / `.boardChanges` / `.individualChanges` / `.individualChangesHistory`(stock anomalies) |
| `sdk.dragonTiger` | `.detail` / `.stockStats` / `.institution` / `.branchRank` / `.seatDetail` |
| `sdk.blockTrade` / `sdk.margin` | Block trading / margin trading |
| `sdk.fund` | `.dividendList` / `.navHistory` / `.estimate` / `.rankHistory` / `.theme` |
| `sdk.calendar` | `.isTradingDay` / `.nextTradingDay` / `.prevTradingDay` / `.marketStatus` |
| `sdk.reference` | `.dividendDetail` / `.tradingCalendar` |
| Top-level | `sdk.search(keyword)` |
> Indicator calculations changed from main package to subpath: `import { calcMACD } from 'stock-sdk/indicators'`.
> Migration from v1 flat API? See [v1 → v2 migration guide](https://stock-sdk.linkdiary.cn/guide/migration-v1-to-v2) (including complete `sdk.getXxx()` → `sdk.<ns>.<method>()` mapping table).
---
## Development Verification
```bash
pnpm typecheck
pnpm build
pnpm test
pnpm test:integration:smoke # Smoke integration (real network)
pnpm test:integration:full # Full integration regression
```
---
## License
[ISC](./LICENSE)
---
🌐 [Official Website](https://stock-sdk.linkdiary.cn) | 📦 [NPM](https://www.npmjs.com/package/stock-sdk) | 📖 [GitHub](https://github.com/chengzuopeng/stock-sdk) | 🎮 [Online Demo](https://stock-sdk.linkdiary.cn/playground/) | 🧭 [Stock Dashboard](https://chengzuopeng.github.io/stock-dashboard/) | 🐛 [Issues](https://github.com/chengzuopeng/stock-sdk/issues)
---
If this project helps you, welcome to Star ⭐ or raise an Issue for feedback.
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available