@dshtrading/connector-finnhub 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,75 @@
1
+ Copyright (c) 2026 zhu1090093659 (dsh-trading)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
14
+
15
+ ## Distribution License
16
+
17
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
18
+
19
+ ## Notices
20
+
21
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
22
+
23
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @dshtrading/connector-template
2
+
3
+ **本包是脚手架源,不是可安装的连接器**:不入任何 bundle 依赖,仅在 `pnpm -r build/test`
4
+ 基线内保证可编译、冒烟测试绿。真实接入用生成器:
5
+
6
+ ```sh
7
+ node scripts/new-connector.mjs --slug bybit --title Bybit --market crypto
8
+ ```
9
+
10
+ 生成后按 [docs/connector-playbook.md](../../docs/connector-playbook.md) 的填写顺序
11
+ (src/rest.ts 头部清单 7 项)实现 TODO。每个 TODO 的参照段都在 connector-okx
12
+ (packages/connector-okx/),它是本仓第一个真实 TradeService 连接器。
13
+
14
+ ## 结构
15
+
16
+ - `src/rest.ts` —— 错误载体(TradingServiceError)+ 通用请求管线(超时/错误映射/
17
+ 模拟盘头/注入 fetch)直接可用;签名与端点 TODO。
18
+ - `src/index.ts` —— Config(enabled/env/dryRun/liveTrading + 三 ref 凭证组)、
19
+ 闸门三态判定、凭证解析(BYOK + 环境变量回落)、MarketDataService/TradeService 骨架、
20
+ 7 个市场前缀工具注册(duplicate-safe)、apply(enabled=false 静默退出)。
21
+ - `test/template.test.ts` —— 结构冒烟 7 用例。
22
+
23
+ ## Token
24
+
25
+ `finnhub`(slug)/ `Finnhub`(title)/ `FINNHUB`(ref 前缀)/
26
+ `us`(工具前缀)/ `Us`(服务键 infix)。token 未展开也可编译;
27
+ 生成器保证全部替换。
28
+
29
+ ## 注意(勿改的坑)
30
+
31
+ - 服务类用 TS 编译期 `private`(禁 ECMAScript `#`,realm 代理会炸)。
32
+ - 工具名 = 市场前缀 + 语义词(不带交易所名)——base 闸门正则只认市场前缀。
33
+ - 行 id = `dsh-trading-<market>-connector-<slug>`,全仓唯一(insert-only 铁律 #1)。
34
+ - 凭证只进 ref,绝不内置/落日志(铁律 #3/#5)。
@@ -0,0 +1,7 @@
1
+ import { Config } from "./index.js";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+ //#region src/dataplane.d.ts
4
+ declare const inject: string[];
5
+ declare function apply(ctx: Context, config: Config): void;
6
+ //#endregion
7
+ export { apply, inject };
@@ -0,0 +1,23 @@
1
+ import { FinnhubMarketDataService, TRADING_US_MARKET_DATA_KEY } from "./index.js";
2
+ //#region src/dataplane.ts
3
+ const inject = [];
4
+ function resolveMarketDataRegistry(ctx) {
5
+ const candidate = ctx.get?.("tradingMarketDataRegistry", false);
6
+ return candidate !== void 0 ? candidate : void 0;
7
+ }
8
+ const ROUTER_PROVIDER = "finnhub";
9
+ const MARKET = "us";
10
+ function apply(ctx, config) {
11
+ if (!config.enabled) return;
12
+ const apiKey = process.env[config.apiKeyRef];
13
+ const registry = resolveMarketDataRegistry(ctx);
14
+ if (registry === void 0) {
15
+ new FinnhubMarketDataService(ctx, { apiKey });
16
+ return;
17
+ }
18
+ const inner = ctx.isolate(TRADING_US_MARKET_DATA_KEY);
19
+ const service = new FinnhubMarketDataService(inner, { apiKey });
20
+ ctx.effect(() => registry.register(MARKET, ROUTER_PROVIDER, service));
21
+ }
22
+ //#endregion
23
+ export { apply, inject };
package/lib/index.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { AccountBalance, FinnhubRestClient, FinnhubRestOptions, INTERVAL_VOCABULARY, Interval, Kline, Order, Position, Ticker, TradingServiceError, normalizeUsSymbol, parseIntervalSeconds, toFinnhubResolution } from "./rest.js";
2
+ import { Context, Service } from "@deepseek-ai/cordis";
3
+ import Schema from "@deepseek-ai/schemastery";
4
+ import { AccountBalance as AccountBalance$1, Disposable, Interval as Interval$1, Kline as Kline$1, MarketDataService, Order as Order$1, OrderRequest, Position as Position$1, StockFundamentals, Ticker as Ticker$1, TradeService } from "@dshtrading/api";
5
+ //#region src/index.d.ts
6
+ declare const name = "dsh-trading-us-connector-finnhub";
7
+ interface Config {
8
+ enabled: boolean;
9
+ env: 'demo' | 'live';
10
+ dryRun: boolean;
11
+ liveTrading: boolean;
12
+ apiKeyRef: string;
13
+ }
14
+ declare const Config: Schema<Config>;
15
+ declare const TRADING_US_MARKET_DATA_KEY = "tradingUsMarketData";
16
+ declare const TRADING_US_TRADE_KEY = "tradingUsTrade";
17
+ declare class FinnhubMarketDataService extends Service implements MarketDataService {
18
+ private readonly client;
19
+ constructor(ctx: Context, options?: FinnhubRestOptions, serviceName?: string);
20
+ getTicker(symbol: string): Promise<Ticker$1>;
21
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
22
+ getNews(symbol: string): Promise<Array<Record<string, unknown>>>;
23
+ listInstruments(query?: string): Promise<Array<{
24
+ symbol: string;
25
+ name: string;
26
+ }>>;
27
+ getFundamentals(symbol: string): Promise<StockFundamentals>;
28
+ subscribeTicker(symbol: string, cb: (ticker: Ticker$1) => void, options?: {
29
+ intervalMs?: number;
30
+ }): Disposable;
31
+ }
32
+ declare class FinnhubTradeService extends Service implements TradeService {
33
+ private readonly client;
34
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
35
+ private readonly config;
36
+ constructor(ctx: Context, options: FinnhubRestOptions & {
37
+ config: Config;
38
+ }, serviceName?: string);
39
+ getBalance(): Promise<AccountBalance$1>;
40
+ placeOrder(order: OrderRequest): Promise<Order$1>;
41
+ cancelOrder(orderId: string, _symbol?: string): Promise<void>;
42
+ getPositions(): Promise<Position$1[]>;
43
+ getOrders(): Promise<Order$1[]>;
44
+ }
45
+ declare const ROUTER_PROVIDER = "finnhub";
46
+ declare function routeAllows(ctx: Context, config: Config, market: string): boolean;
47
+ declare function apply(ctx: Context, config: Config): void;
48
+ //#endregion
49
+ export { type AccountBalance, Config, FinnhubMarketDataService, FinnhubRestClient, FinnhubRestOptions, FinnhubTradeService, INTERVAL_VOCABULARY, type Interval, type Kline, type Order, type Position, ROUTER_PROVIDER, TRADING_US_MARKET_DATA_KEY, TRADING_US_TRADE_KEY, type Ticker, TradingServiceError, apply, name, normalizeUsSymbol, parseIntervalSeconds, routeAllows, toFinnhubResolution };
package/lib/index.js ADDED
@@ -0,0 +1,182 @@
1
+ import { FinnhubRestClient, INTERVAL_VOCABULARY, TradingServiceError, normalizeUsSymbol, parseIntervalSeconds, toFinnhubResolution } from "./rest.js";
2
+ import { Service } from "@deepseek-ai/cordis";
3
+ import { defineTool } from "@deepseek-ai/dsh-tools";
4
+ import Schema from "@deepseek-ai/schemastery";
5
+ //#region src/index.ts
6
+ const name = "dsh-trading-us-connector-finnhub";
7
+ const Config = Schema.object({
8
+ enabled: Schema.boolean().default(true).description("是否激活 Finnhub 连接器"),
9
+ env: Schema.union(["demo", "live"]).default("demo").description("运行环境"),
10
+ dryRun: Schema.boolean().default(true).description("默认模拟下单"),
11
+ liveTrading: Schema.boolean().default(false).description("是否允许实盘交易"),
12
+ apiKeyRef: Schema.string().default("FINNHUB_API_KEY").description("Finnhub API Key 环境变量名 (BYOK)")
13
+ });
14
+ const TRADING_US_MARKET_DATA_KEY = "tradingUsMarketData";
15
+ const TRADING_US_TRADE_KEY = "tradingUsTrade";
16
+ var FinnhubMarketDataService = class extends Service {
17
+ client;
18
+ constructor(ctx, options = {}, serviceName = TRADING_US_MARKET_DATA_KEY) {
19
+ super(ctx, serviceName);
20
+ this.client = new FinnhubRestClient(options);
21
+ }
22
+ async getTicker(symbol) {
23
+ return this.client.getTicker(symbol);
24
+ }
25
+ async getKlines(symbol, interval = "1d", limit = 100) {
26
+ return this.client.getKlines(symbol, interval, limit);
27
+ }
28
+ async getNews(symbol) {
29
+ return this.client.getNews(symbol);
30
+ }
31
+ async listInstruments(query) {
32
+ return this.client.listInstruments(query);
33
+ }
34
+ async getFundamentals(symbol) {
35
+ return this.client.getFundamentals(symbol);
36
+ }
37
+ subscribeTicker(symbol, cb, options) {
38
+ const ms = Math.max(options?.intervalMs ?? 5e3, 1e3);
39
+ const tick = () => {
40
+ this.getTicker(symbol).then(cb, () => {});
41
+ };
42
+ tick();
43
+ const timer = setInterval(tick, ms);
44
+ return { dispose: () => clearInterval(timer) };
45
+ }
46
+ };
47
+ var FinnhubTradeService = class extends Service {
48
+ client;
49
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
50
+ config;
51
+ constructor(ctx, options, serviceName = TRADING_US_TRADE_KEY) {
52
+ super(ctx, serviceName);
53
+ this.client = new FinnhubRestClient(options);
54
+ this.config = options.config;
55
+ }
56
+ async getBalance() {
57
+ return this.client.getBalance();
58
+ }
59
+ async placeOrder(order) {
60
+ const requestedDryRun = order.dryRun ?? true;
61
+ if (!requestedDryRun && !this.config.liveTrading) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", `Finnhub TradeService.placeOrder rejected: the request asks for real execution (dryRun=${String(order.dryRun)}) but liveTrading=false — enable liveTrading explicitly or keep dryRun=true for a simulated fill.`);
62
+ if (requestedDryRun || this.config.dryRun) return {
63
+ id: `dry-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
64
+ symbol: order.symbol,
65
+ side: order.side,
66
+ type: order.type,
67
+ status: "filled",
68
+ ...order.price !== void 0 ? { price: order.price } : {},
69
+ quantity: order.quantity,
70
+ dryRun: true,
71
+ timestamp: Date.now()
72
+ };
73
+ return this.client.placeOrder(void 0, order);
74
+ }
75
+ async cancelOrder(orderId, _symbol) {
76
+ if (!this.config.liveTrading || this.config.dryRun) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", "Finnhub TradeService.cancelOrder rejected at the service seam: cancel is a live action and requires liveTrading=true with dryRun=false.");
77
+ return this.client.cancelOrder(void 0, orderId);
78
+ }
79
+ async getPositions() {
80
+ return [];
81
+ }
82
+ async getOrders() {
83
+ return [];
84
+ }
85
+ };
86
+ const ROUTER_PROVIDER = "finnhub";
87
+ function routeAllows(ctx, config, market) {
88
+ if (!config.enabled) return false;
89
+ const router = ctx.get?.("tradingMarketRouter", false);
90
+ if (router === void 0) return true;
91
+ return router.activeProvider(market) === ROUTER_PROVIDER;
92
+ }
93
+ function apply(ctx, config) {
94
+ if (!config.enabled) return;
95
+ if (!routeAllows(ctx, config, "us")) return;
96
+ const apiKey = ((ctx.get?.("tradingMarketRouter", false))?.getCredential?.("finnhub"))?.apiKey || process.env[config.apiKeyRef];
97
+ const marketData = new FinnhubMarketDataService(ctx, { apiKey });
98
+ new FinnhubTradeService(ctx, {
99
+ apiKey,
100
+ config
101
+ });
102
+ ctx.inject(["tools"], (ctx) => {
103
+ const tools = ctx.tools;
104
+ const register = (t) => {
105
+ if (tools.get(t.name) === void 0) tools.register(t);
106
+ };
107
+ register(defineTool({
108
+ name: "us_get_ticker",
109
+ description: "Get the latest trade price and quote for a US stock via Finnhub API.",
110
+ parameters: { symbol: {
111
+ type: "string",
112
+ required: true,
113
+ description: "US stock symbol, e.g. AAPL"
114
+ } },
115
+ output: {
116
+ schema: { type: "string" },
117
+ render: (_a, v) => [{
118
+ type: "text",
119
+ text: v
120
+ }]
121
+ },
122
+ async execute(args) {
123
+ return JSON.stringify(await marketData.getTicker(args.symbol));
124
+ }
125
+ }));
126
+ register(defineTool({
127
+ name: "us_get_klines",
128
+ description: "Get recent public klines for a US stock via Finnhub API. Supports 1m/5m/15m/30m/1h/1d/1w/1M.",
129
+ parameters: {
130
+ symbol: {
131
+ type: "string",
132
+ required: true,
133
+ description: "US stock symbol, e.g. AAPL"
134
+ },
135
+ interval: {
136
+ type: "string",
137
+ enum: INTERVAL_VOCABULARY,
138
+ default: "1d",
139
+ description: "Interval"
140
+ },
141
+ limit: {
142
+ type: "integer",
143
+ default: 100,
144
+ description: "Limit"
145
+ }
146
+ },
147
+ output: {
148
+ schema: { type: "string" },
149
+ render: (_a, v) => [{
150
+ type: "text",
151
+ text: v
152
+ }]
153
+ },
154
+ async execute(args) {
155
+ const klines = await marketData.getKlines(args.symbol, args.interval ?? "1d", args.limit);
156
+ return JSON.stringify(klines);
157
+ }
158
+ }));
159
+ register(defineTool({
160
+ name: "us_get_news",
161
+ description: "Get recent company news and market headlines for a US stock via Finnhub.",
162
+ parameters: { symbol: {
163
+ type: "string",
164
+ required: true,
165
+ description: "US stock symbol, e.g. AAPL"
166
+ } },
167
+ output: {
168
+ schema: { type: "string" },
169
+ render: (_a, v) => [{
170
+ type: "text",
171
+ text: v
172
+ }]
173
+ },
174
+ async execute(args) {
175
+ const news = await marketData.getNews(args.symbol);
176
+ return JSON.stringify(news);
177
+ }
178
+ }));
179
+ });
180
+ }
181
+ //#endregion
182
+ export { Config, FinnhubMarketDataService, FinnhubRestClient, FinnhubTradeService, INTERVAL_VOCABULARY, ROUTER_PROVIDER, TRADING_US_MARKET_DATA_KEY, TRADING_US_TRADE_KEY, TradingServiceError, apply, name, normalizeUsSymbol, parseIntervalSeconds, routeAllows, toFinnhubResolution };
package/lib/rest.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { AccountBalance as AccountBalance$1, Interval as Interval$1, Kline as Kline$1, Order as Order$1, OrderRequest, Position as Position$1, StockFundamentals, Ticker as Ticker$1, TradingErrorCode } from "@dshtrading/api";
2
+ //#region src/rest.d.ts
3
+ declare class TradingServiceError extends Error {
4
+ readonly code: TradingErrorCode;
5
+ constructor(code: TradingErrorCode, message: string, cause?: unknown);
6
+ }
7
+ declare const INTERVAL_VOCABULARY: readonly ["1m", "5m", "15m", "30m", "1h", "1d", "1w", "1M"];
8
+ declare function toFinnhubResolution(interval: Interval$1): string;
9
+ declare function parseIntervalSeconds(interval: Interval$1): number;
10
+ declare function normalizeUsSymbol(raw: string): string;
11
+ interface FinnhubRestOptions {
12
+ baseUrl?: string;
13
+ apiKey?: string;
14
+ fetchImpl?: typeof fetch;
15
+ }
16
+ declare class FinnhubRestClient {
17
+ readonly baseUrl: string;
18
+ private readonly apiKey?;
19
+ private readonly fetchImpl;
20
+ constructor(options?: FinnhubRestOptions);
21
+ private requestJson;
22
+ getTicker(symbol: string): Promise<Ticker$1>;
23
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
24
+ getNews(symbol: string): Promise<Array<Record<string, unknown>>>;
25
+ getFundamentals(symbol: string): Promise<StockFundamentals>;
26
+ listInstruments(query?: string): Promise<Array<{
27
+ symbol: string;
28
+ name: string;
29
+ }>>;
30
+ getBalance(): Promise<AccountBalance$1>;
31
+ placeOrder(_creds: unknown, req: OrderRequest): Promise<Order$1>;
32
+ cancelOrder(_creds: unknown, orderId: string): Promise<{
33
+ orderId: string;
34
+ status: 'canceled';
35
+ }>;
36
+ }
37
+ //#endregion
38
+ export { type AccountBalance$1 as AccountBalance, FinnhubRestClient, FinnhubRestOptions, INTERVAL_VOCABULARY, type Interval$1 as Interval, type Kline$1 as Kline, type Order$1 as Order, type Position$1 as Position, type Ticker$1 as Ticker, TradingServiceError, normalizeUsSymbol, parseIntervalSeconds, toFinnhubResolution };
package/lib/rest.js ADDED
@@ -0,0 +1,164 @@
1
+ //#region src/rest.ts
2
+ var TradingServiceError = class extends Error {
3
+ code;
4
+ constructor(code, message, cause) {
5
+ super(message);
6
+ this.name = "TradingServiceError";
7
+ this.code = code;
8
+ if (cause !== void 0) this.cause = cause;
9
+ }
10
+ };
11
+ const INTERVAL_VOCABULARY = [
12
+ "1m",
13
+ "5m",
14
+ "15m",
15
+ "30m",
16
+ "1h",
17
+ "1d",
18
+ "1w",
19
+ "1M"
20
+ ];
21
+ function toFinnhubResolution(interval) {
22
+ switch (interval) {
23
+ case "1m": return "1";
24
+ case "5m": return "5";
25
+ case "15m": return "15";
26
+ case "30m": return "30";
27
+ case "1h": return "60";
28
+ case "1d": return "D";
29
+ case "1w": return "W";
30
+ case "1M": return "M";
31
+ }
32
+ }
33
+ function parseIntervalSeconds(interval) {
34
+ switch (interval) {
35
+ case "1m": return 60;
36
+ case "5m": return 300;
37
+ case "15m": return 900;
38
+ case "30m": return 1800;
39
+ case "1h": return 3600;
40
+ case "1d": return 86400;
41
+ case "1w": return 604800;
42
+ case "1M": return 2592e3;
43
+ }
44
+ }
45
+ function normalizeUsSymbol(raw) {
46
+ const clean = raw.trim().toUpperCase();
47
+ if (!clean) throw new TradingServiceError("TRADING_INVALID_ARGUMENT", "Symbol cannot be empty");
48
+ return clean;
49
+ }
50
+ var FinnhubRestClient = class {
51
+ baseUrl;
52
+ apiKey;
53
+ fetchImpl;
54
+ constructor(options = {}) {
55
+ this.baseUrl = options.baseUrl ?? "https://finnhub.io/api/v1";
56
+ this.apiKey = options.apiKey;
57
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
58
+ }
59
+ async requestJson(path) {
60
+ const sep = path.includes("?") ? "&" : "?";
61
+ const tokenQuery = this.apiKey ? `${sep}token=${encodeURIComponent(this.apiKey)}` : "";
62
+ const url = `${this.baseUrl}${path}${tokenQuery}`;
63
+ try {
64
+ const res = await this.fetchImpl(url, { headers: { "Accept": "application/json" } });
65
+ if (!res.ok) throw new TradingServiceError("TRADING_UPSTREAM_ERROR", `Finnhub request failed: HTTP ${res.status}`);
66
+ return await res.json();
67
+ } catch (err) {
68
+ if (err instanceof TradingServiceError) throw err;
69
+ throw new TradingServiceError("TRADING_NETWORK", `Finnhub network error: ${err instanceof Error ? err.message : String(err)}`, err);
70
+ }
71
+ }
72
+ async getTicker(symbol) {
73
+ const sym = normalizeUsSymbol(symbol);
74
+ const data = await this.requestJson(`/quote?symbol=${sym}`);
75
+ if (data.c === void 0 || data.c === 0) throw new TradingServiceError("TRADING_SYMBOL_NOT_FOUND", `Finnhub quote not found for ${sym}`);
76
+ return {
77
+ symbol: sym,
78
+ price: data.c,
79
+ timestamp: typeof data.t === "number" && data.t > 0 ? data.t * 1e3 : Date.now()
80
+ };
81
+ }
82
+ async getKlines(symbol, interval = "1d", limit = 100) {
83
+ const sym = normalizeUsSymbol(symbol);
84
+ const resolution = toFinnhubResolution(interval);
85
+ const stepSec = parseIntervalSeconds(interval);
86
+ const nowSec = Math.floor(Date.now() / 1e3);
87
+ const fromSec = nowSec - limit * stepSec * 2;
88
+ const data = await this.requestJson(`/stock/candle?symbol=${sym}&resolution=${resolution}&from=${fromSec}&to=${nowSec}`);
89
+ if (data.s !== "ok" || !Array.isArray(data.t) || data.t.length === 0) return [];
90
+ const count = Math.min(data.t.length, limit);
91
+ const startIdx = data.t.length - count;
92
+ const klines = [];
93
+ for (let i = startIdx; i < data.t.length; i++) {
94
+ const openTime = data.t[i] * 1e3;
95
+ klines.push({
96
+ openTime,
97
+ open: data.o?.[i] ?? 0,
98
+ high: data.h?.[i] ?? 0,
99
+ low: data.l?.[i] ?? 0,
100
+ close: data.c?.[i] ?? 0,
101
+ volume: data.v?.[i] ?? 0,
102
+ closeTime: openTime + stepSec * 1e3 - 1
103
+ });
104
+ }
105
+ return klines;
106
+ }
107
+ async getNews(symbol) {
108
+ const sym = normalizeUsSymbol(symbol);
109
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
110
+ const from = (/* @__PURE__ */ new Date(Date.now() - 6048e5)).toISOString().slice(0, 10);
111
+ const data = await this.requestJson(`/company-news?symbol=${sym}&from=${from}&to=${today}`);
112
+ return Array.isArray(data) ? data.slice(0, 10) : [];
113
+ }
114
+ async getFundamentals(symbol) {
115
+ const sym = normalizeUsSymbol(symbol);
116
+ const m = (await this.requestJson(`/stock/metric?symbol=${sym}&metric=all`).catch(() => ({ metric: void 0 })))?.metric ?? {};
117
+ return {
118
+ symbol: sym,
119
+ peTtm: m.peNormalizedAnnual ?? m.peTTM ?? m.peBasicExclExtraTTM,
120
+ pb: m.pbAnnual ?? m.pbTTM,
121
+ ps: m.psTTM ?? m.psAnnual,
122
+ dividendYield: m.dividendYieldIndicatedAnnual,
123
+ fiftyTwoWeekHigh: m["52WeekHigh"],
124
+ fiftyTwoWeekLow: m["52WeekLow"],
125
+ marketCap: m.marketCapitalization ? m.marketCapitalization * 1e6 : void 0,
126
+ timestamp: Date.now()
127
+ };
128
+ }
129
+ async listInstruments(query) {
130
+ if (!query) return [];
131
+ return ((await this.requestJson(`/search?q=${encodeURIComponent(query)}`)).result ?? []).map((r) => ({
132
+ symbol: r.symbol,
133
+ name: r.description
134
+ }));
135
+ }
136
+ async getBalance() {
137
+ return {
138
+ currency: "USD",
139
+ available: 1e5,
140
+ total: 1e5
141
+ };
142
+ }
143
+ async placeOrder(_creds, req) {
144
+ return {
145
+ id: `sim-finnhub-${Date.now()}`,
146
+ symbol: req.symbol,
147
+ side: req.side,
148
+ type: req.type,
149
+ status: "filled",
150
+ quantity: req.quantity,
151
+ price: req.price ?? 0,
152
+ dryRun: true,
153
+ timestamp: Date.now()
154
+ };
155
+ }
156
+ async cancelOrder(_creds, orderId) {
157
+ return {
158
+ orderId,
159
+ status: "canceled"
160
+ };
161
+ }
162
+ };
163
+ //#endregion
164
+ export { FinnhubRestClient, INTERVAL_VOCABULARY, TradingServiceError, normalizeUsSymbol, parseIntervalSeconds, toFinnhubResolution };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dshtrading/connector-finnhub",
3
+ "description": "【模板】交易所连接器插件脚手架:Finnhub(finnhub)v2 插件骨架 —— 市场数据服务 + 交易服务 + 三态闸门 + BYOK 凭证 ref。生成器:node scripts/new-connector.mjs --slug <exchange>",
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./dataplane": {
14
+ "types": "./lib/dataplane.d.ts",
15
+ "default": "./lib/dataplane.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib"
21
+ ],
22
+ "license": "PolyForm-Noncommercial-1.0.0",
23
+ "dependencies": {
24
+ "@dshtrading/api": "^0.1.0"
25
+ },
26
+ "peerDependencies": {
27
+ "@deepseek-ai/cordis": ">=4.0.0",
28
+ "@deepseek-ai/dsh-tools": ">=0.1.2-alpha.1",
29
+ "@deepseek-ai/schemastery": ">=3.18.0"
30
+ },
31
+ "devDependencies": {
32
+ "tsdown": "^0.22.0",
33
+ "vitest": "^3.0.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "test": "vitest run"
38
+ }
39
+ }