@dshtrading/connector-bybit 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
+ `bybit`(slug)/ `Bybit`(title)/ `BYBIT`(ref 前缀)/
26
+ `crypto`(工具前缀)/ `Crypto`(服务键 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,44 @@
1
+ import { BybitMarketDataService, BybitTradeService, TRADING_CRYPTO_MARKET_DATA_KEY, TRADING_CRYPTO_TRADE_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
+ function resolveTradeRegistry(ctx) {
9
+ const candidate = ctx.get?.("tradingTradeRegistry", false);
10
+ return candidate !== void 0 ? candidate : void 0;
11
+ }
12
+ const ROUTER_PROVIDER = "bybit";
13
+ const MARKET = "crypto";
14
+ function apply(ctx, config) {
15
+ if (!config.enabled) return;
16
+ const apiKey = process.env[config.apiKeyRef];
17
+ const apiSecret = process.env[config.secretRef];
18
+ const registry = resolveMarketDataRegistry(ctx);
19
+ if (registry === void 0) {
20
+ new BybitMarketDataService(ctx, {
21
+ apiKey,
22
+ apiSecret
23
+ });
24
+ return;
25
+ }
26
+ const inner = ctx.isolate(TRADING_CRYPTO_MARKET_DATA_KEY);
27
+ const service = new BybitMarketDataService(inner, {
28
+ apiKey,
29
+ apiSecret
30
+ });
31
+ ctx.effect(() => registry.register(MARKET, ROUTER_PROVIDER, service));
32
+ const tradeRegistry = resolveTradeRegistry(ctx);
33
+ if (tradeRegistry !== void 0) {
34
+ const tradeInner = ctx.isolate(TRADING_CRYPTO_TRADE_KEY);
35
+ const trade = new BybitTradeService(tradeInner, {
36
+ apiKey,
37
+ apiSecret,
38
+ config
39
+ });
40
+ ctx.effect(() => tradeRegistry.register(MARKET, ROUTER_PROVIDER, trade));
41
+ }
42
+ }
43
+ //#endregion
44
+ export { apply, inject };
package/lib/index.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ import { AccountBalance, BybitRestClient, BybitRestOptions, INTERVAL_VOCABULARY, Interval, Kline, Order, Position, Ticker, TradingServiceError, normalizeCryptoSymbol, parseIntervalMs, toBybitInterval } from "./rest.js";
2
+ import { Context, Service } from "@deepseek-ai/cordis";
3
+ import Schema from "@deepseek-ai/schemastery";
4
+ import { AccountBalance as AccountBalance$1, DerivativesData, DerivativesHistory, Disposable, Interval as Interval$1, Kline as Kline$1, MarketDataService, Order as Order$1, OrderRequest, Orderbook, Position as Position$1, Ticker as Ticker$1, TradeFill, TradeService, TradeTick } from "@dshtrading/api";
5
+ //#region src/index.d.ts
6
+ declare const name = "dsh-trading-crypto-connector-bybit";
7
+ interface Config {
8
+ enabled: boolean;
9
+ env: 'demo' | 'live';
10
+ dryRun: boolean;
11
+ liveTrading: boolean;
12
+ apiKeyRef: string;
13
+ secretRef: string;
14
+ }
15
+ declare const Config: Schema<Config>;
16
+ declare const TRADING_CRYPTO_MARKET_DATA_KEY = "tradingCryptoMarketData";
17
+ declare const TRADING_CRYPTO_TRADE_KEY = "tradingCryptoTrade";
18
+ declare class BybitMarketDataService extends Service implements MarketDataService {
19
+ private readonly client;
20
+ constructor(ctx: Context, options?: BybitRestOptions, serviceName?: string);
21
+ getTicker(symbol: string): Promise<Ticker$1>;
22
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
23
+ subscribeTicker(symbol: string, cb: (ticker: Ticker$1) => void, options?: {
24
+ intervalMs?: number;
25
+ }): Disposable;
26
+ /** 盘口快照(api 可选契约 getOrderbook,issue #39):spot orderbook 25 档透传。 */
27
+ getOrderbook(symbol: string): Promise<Orderbook>;
28
+ /** 最近逐笔成交(api 可选契约 getRecentTrades,issue #39),时间升序。 */
29
+ getRecentTrades(symbol: string, limit?: number): Promise<TradeTick[]>;
30
+ /**
31
+ * 衍生品指标快照(api 可选契约 getDerivatives,issue #38):聚合 Bybit v5 线性合约
32
+ * 公共端点(tickers?category=linear 的 fundingRate/OI + account-ratio 多空比)。
33
+ * 任一子查询失败只降级该字段(undefined,面板按缺格隐藏);全部失败才抛结构化错误
34
+ * (桥层转 ok:false,前端不弹横幅)。输出 symbol 为规范 SWAP 形(BTCUSDT-SWAP)。
35
+ */
36
+ getDerivatives(symbol: string): Promise<DerivativesData>;
37
+ /**
38
+ * 衍生品历史序列(api 可选契约 getDerivativesHistory,issue #54):
39
+ * funding/history + open-interest 双端点聚合并发拉取,任一失败只降级该序列
40
+ * (字段缺省 → 对应趋势卡隐藏),全部失败才抛结构化错误。
41
+ */
42
+ getDerivativesHistory(symbol: string): Promise<DerivativesHistory>;
43
+ }
44
+ declare class BybitTradeService extends Service implements TradeService {
45
+ private readonly client;
46
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
47
+ private readonly config;
48
+ constructor(ctx: Context, options: BybitRestOptions & {
49
+ config: Config;
50
+ }, serviceName?: string);
51
+ getBalance(): Promise<AccountBalance$1>;
52
+ getBalances(): Promise<AccountBalance$1[]>;
53
+ placeOrder(order: OrderRequest): Promise<Order$1>;
54
+ cancelOrder(orderId: string, _symbol?: string): Promise<void>;
55
+ getOrder(symbol: string, id: string): Promise<Order$1>;
56
+ getPositions(): Promise<Position$1[]>;
57
+ listOpenOrders(_symbol?: string): Promise<Order$1[]>;
58
+ listTradeFills(_symbol?: string, _limit?: number): Promise<TradeFill[]>;
59
+ }
60
+ declare const ROUTER_PROVIDER = "bybit";
61
+ declare function routeAllows(ctx: Context, config: Config, market: string): boolean;
62
+ declare function apply(ctx: Context, config: Config): void;
63
+ //#endregion
64
+ export { type AccountBalance, BybitMarketDataService, BybitRestClient, BybitRestOptions, BybitTradeService, Config, INTERVAL_VOCABULARY, type Interval, type Kline, type Order, type Position, ROUTER_PROVIDER, TRADING_CRYPTO_MARKET_DATA_KEY, TRADING_CRYPTO_TRADE_KEY, type Ticker, TradingServiceError, apply, name, normalizeCryptoSymbol, parseIntervalMs, routeAllows, toBybitInterval };
package/lib/index.js ADDED
@@ -0,0 +1,240 @@
1
+ import { BybitRestClient, INTERVAL_VOCABULARY, TradingServiceError, normalizeCryptoSymbol, parseIntervalMs, toBybitInterval } 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-crypto-connector-bybit";
7
+ const Config = Schema.object({
8
+ enabled: Schema.boolean().default(true).description("是否激活 Bybit 连接器"),
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("BYBIT_API_KEY").description("Bybit API Key 环境变量名 (BYOK)"),
13
+ secretRef: Schema.string().default("BYBIT_SECRET_KEY").description("Bybit Secret Key 环境变量名")
14
+ });
15
+ const TRADING_CRYPTO_MARKET_DATA_KEY = "tradingCryptoMarketData";
16
+ const TRADING_CRYPTO_TRADE_KEY = "tradingCryptoTrade";
17
+ var BybitMarketDataService = class extends Service {
18
+ client;
19
+ constructor(ctx, options = {}, serviceName = TRADING_CRYPTO_MARKET_DATA_KEY) {
20
+ super(ctx, serviceName);
21
+ this.client = new BybitRestClient(options);
22
+ }
23
+ async getTicker(symbol) {
24
+ return this.client.getTicker(symbol);
25
+ }
26
+ async getKlines(symbol, interval = "1d", limit = 100) {
27
+ return this.client.getKlines(symbol, interval, limit);
28
+ }
29
+ subscribeTicker(symbol, cb, options) {
30
+ const ms = Math.max(options?.intervalMs ?? 5e3, 1e3);
31
+ const tick = () => {
32
+ this.getTicker(symbol).then(cb, () => {});
33
+ };
34
+ tick();
35
+ const timer = setInterval(tick, ms);
36
+ return { dispose: () => clearInterval(timer) };
37
+ }
38
+ /** 盘口快照(api 可选契约 getOrderbook,issue #39):spot orderbook 25 档透传。 */
39
+ async getOrderbook(symbol) {
40
+ return this.client.getOrderbook(symbol);
41
+ }
42
+ /** 最近逐笔成交(api 可选契约 getRecentTrades,issue #39),时间升序。 */
43
+ async getRecentTrades(symbol, limit = 50) {
44
+ return this.client.getRecentTrades(symbol, limit);
45
+ }
46
+ /**
47
+ * 衍生品指标快照(api 可选契约 getDerivatives,issue #38):聚合 Bybit v5 线性合约
48
+ * 公共端点(tickers?category=linear 的 fundingRate/OI + account-ratio 多空比)。
49
+ * 任一子查询失败只降级该字段(undefined,面板按缺格隐藏);全部失败才抛结构化错误
50
+ * (桥层转 ok:false,前端不弹横幅)。输出 symbol 为规范 SWAP 形(BTCUSDT-SWAP)。
51
+ */
52
+ async getDerivatives(symbol) {
53
+ const sym = normalizeCryptoSymbol(symbol);
54
+ const unavailable = [];
55
+ const collect = (label, task) => task.catch((error) => {
56
+ unavailable.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
57
+ });
58
+ const [ticker, ratio] = await Promise.all([collect("linear-tickers", this.client.getLinearTickerSnapshot(sym)), collect("account-ratio", this.client.getLinearAccountRatio(sym))]);
59
+ const fundingRate = ticker?.fundingRate;
60
+ const openInterest = ticker?.openInterest;
61
+ const openInterestValue = ticker?.openInterestValue;
62
+ const longShortRatio = ratio !== void 0 && ratio.sellRatio > 0 ? ratio.buyRatio / ratio.sellRatio : void 0;
63
+ if (fundingRate === void 0 && openInterest === void 0 && openInterestValue === void 0 && longShortRatio === void 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit derivatives for ${sym}: all sub-queries failed` + (unavailable.length > 0 ? ` (${unavailable.join("; ")})` : ""));
64
+ return {
65
+ symbol: `${sym}-SWAP`,
66
+ source: "bybit",
67
+ ...openInterest !== void 0 ? { openInterest } : {},
68
+ ...openInterestValue !== void 0 ? { openInterestValue } : {},
69
+ ...longShortRatio !== void 0 ? { longShortRatio } : {},
70
+ ...fundingRate !== void 0 ? { fundingRate } : {},
71
+ ...ticker?.nextFundingTime !== void 0 ? { nextFundingTime: ticker.nextFundingTime } : {},
72
+ ...ticker?.markPrice !== void 0 ? { markPrice: ticker.markPrice } : {},
73
+ ...ticker?.indexPrice !== void 0 ? { indexPrice: ticker.indexPrice } : {},
74
+ timestamp: Date.now()
75
+ };
76
+ }
77
+ /**
78
+ * 衍生品历史序列(api 可选契约 getDerivativesHistory,issue #54):
79
+ * funding/history + open-interest 双端点聚合并发拉取,任一失败只降级该序列
80
+ * (字段缺省 → 对应趋势卡隐藏),全部失败才抛结构化错误。
81
+ */
82
+ async getDerivativesHistory(symbol) {
83
+ const sym = normalizeCryptoSymbol(symbol);
84
+ const unavailable = [];
85
+ const collect = (label, task) => task.catch((error) => {
86
+ unavailable.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
87
+ });
88
+ const [fundingRates, openInterest] = await Promise.all([collect("funding-history", this.client.getLinearFundingHistory(sym, 30)), collect("oi-history", this.client.getLinearOpenInterestHistory(sym, 30))]);
89
+ if (fundingRates === void 0 && openInterest === void 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit derivatives history for ${sym}: all sub-queries failed` + (unavailable.length > 0 ? ` (${unavailable.join("; ")})` : ""));
90
+ return {
91
+ symbol: `${sym}-SWAP`,
92
+ source: "bybit",
93
+ ...fundingRates !== void 0 && fundingRates.length > 0 ? { fundingRates } : {},
94
+ ...openInterest !== void 0 && openInterest.length > 0 ? { openInterest } : {}
95
+ };
96
+ }
97
+ };
98
+ var BybitTradeService = class extends Service {
99
+ client;
100
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
101
+ config;
102
+ constructor(ctx, options, serviceName = TRADING_CRYPTO_TRADE_KEY) {
103
+ super(ctx, serviceName);
104
+ this.client = new BybitRestClient(options);
105
+ this.config = options.config;
106
+ }
107
+ async getBalance() {
108
+ return this.client.getBalance();
109
+ }
110
+ async getBalances() {
111
+ try {
112
+ return [await this.client.getBalance()];
113
+ } catch {
114
+ return [];
115
+ }
116
+ }
117
+ async placeOrder(order) {
118
+ const requestedDryRun = order.dryRun ?? true;
119
+ if (!requestedDryRun && !this.config.liveTrading) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", `Bybit 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.`);
120
+ if (requestedDryRun || this.config.dryRun) return {
121
+ id: `dry-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
122
+ symbol: order.symbol,
123
+ side: order.side,
124
+ type: order.type,
125
+ status: "filled",
126
+ ...order.price !== void 0 ? { price: order.price } : {},
127
+ quantity: order.quantity,
128
+ dryRun: true,
129
+ timestamp: Date.now()
130
+ };
131
+ return this.client.placeOrder(void 0, order);
132
+ }
133
+ async cancelOrder(orderId, _symbol) {
134
+ if (!this.config.liveTrading || this.config.dryRun) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", "Bybit TradeService.cancelOrder rejected at the service seam: cancel is a live action and requires liveTrading=true with dryRun=false.");
135
+ return this.client.cancelOrder(void 0, orderId);
136
+ }
137
+ async getOrder(symbol, id) {
138
+ return {
139
+ id,
140
+ symbol,
141
+ side: "buy",
142
+ type: "limit",
143
+ status: "new",
144
+ quantity: 0,
145
+ dryRun: false,
146
+ timestamp: Date.now()
147
+ };
148
+ }
149
+ async getPositions() {
150
+ return [];
151
+ }
152
+ async listOpenOrders(_symbol) {
153
+ return [];
154
+ }
155
+ async listTradeFills(_symbol, _limit) {
156
+ return [];
157
+ }
158
+ };
159
+ const ROUTER_PROVIDER = "bybit";
160
+ function routeAllows(ctx, config, market) {
161
+ if (!config.enabled) return false;
162
+ const router = ctx.get?.("tradingMarketRouter", false);
163
+ if (router === void 0) return true;
164
+ return router.activeProvider(market) === ROUTER_PROVIDER;
165
+ }
166
+ function apply(ctx, config) {
167
+ if (!config.enabled) return;
168
+ if (!routeAllows(ctx, config, "crypto")) return;
169
+ const apiKey = process.env[config.apiKeyRef];
170
+ const apiSecret = process.env[config.secretRef];
171
+ const marketData = new BybitMarketDataService(ctx, {
172
+ apiKey,
173
+ apiSecret
174
+ });
175
+ new BybitTradeService(ctx, {
176
+ apiKey,
177
+ apiSecret,
178
+ config
179
+ });
180
+ ctx.inject(["tools"], (ctx) => {
181
+ const tools = ctx.tools;
182
+ const register = (t) => {
183
+ if (tools.get(t.name) === void 0) tools.register(t);
184
+ };
185
+ register(defineTool({
186
+ name: "crypto_get_ticker",
187
+ description: "Get the latest trade price and quote for a crypto pair via Bybit API.",
188
+ parameters: { symbol: {
189
+ type: "string",
190
+ required: true,
191
+ description: "Crypto pair symbol, e.g. BTCUSDT"
192
+ } },
193
+ output: {
194
+ schema: { type: "string" },
195
+ render: (_a, v) => [{
196
+ type: "text",
197
+ text: v
198
+ }]
199
+ },
200
+ async execute(args) {
201
+ return JSON.stringify(await marketData.getTicker(args.symbol));
202
+ }
203
+ }));
204
+ register(defineTool({
205
+ name: "crypto_get_klines",
206
+ description: "Get recent public klines for a crypto pair via Bybit API. Supports 1m/5m/15m/30m/1h/4h/1d/1w/1M.",
207
+ parameters: {
208
+ symbol: {
209
+ type: "string",
210
+ required: true,
211
+ description: "Crypto pair symbol, e.g. BTCUSDT"
212
+ },
213
+ interval: {
214
+ type: "string",
215
+ enum: INTERVAL_VOCABULARY,
216
+ default: "1d",
217
+ description: "Interval"
218
+ },
219
+ limit: {
220
+ type: "integer",
221
+ default: 100,
222
+ description: "Limit"
223
+ }
224
+ },
225
+ output: {
226
+ schema: { type: "string" },
227
+ render: (_a, v) => [{
228
+ type: "text",
229
+ text: v
230
+ }]
231
+ },
232
+ async execute(args) {
233
+ const klines = await marketData.getKlines(args.symbol, args.interval ?? "1d", args.limit);
234
+ return JSON.stringify(klines);
235
+ }
236
+ }));
237
+ });
238
+ }
239
+ //#endregion
240
+ export { BybitMarketDataService, BybitRestClient, BybitTradeService, Config, INTERVAL_VOCABULARY, ROUTER_PROVIDER, TRADING_CRYPTO_MARKET_DATA_KEY, TRADING_CRYPTO_TRADE_KEY, TradingServiceError, apply, name, normalizeCryptoSymbol, parseIntervalMs, routeAllows, toBybitInterval };
package/lib/rest.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { AccountBalance as AccountBalance$1, DerivativesPoint, Interval as Interval$1, Kline as Kline$1, Order as Order$1, OrderRequest, Orderbook, Position as Position$1, Ticker as Ticker$1, TradeTick, 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", "4h", "1d", "1w", "1M"];
8
+ declare function toBybitInterval(interval: Interval$1): string;
9
+ declare function parseIntervalMs(interval: Interval$1): number;
10
+ declare function normalizeCryptoSymbol(raw: string): string;
11
+ interface BybitRestOptions {
12
+ baseUrl?: string;
13
+ apiKey?: string;
14
+ apiSecret?: string;
15
+ fetchImpl?: typeof fetch;
16
+ }
17
+ declare class BybitRestClient {
18
+ #private;
19
+ readonly baseUrl: string;
20
+ private readonly apiKey?;
21
+ private readonly apiSecret?;
22
+ private readonly fetchImpl;
23
+ constructor(options?: BybitRestOptions);
24
+ private requestJson;
25
+ getTicker(symbol: string): Promise<Ticker$1>;
26
+ getKlines(symbol: string, interval?: Interval$1, limit?: number): Promise<Kline$1[]>;
27
+ /**
28
+ * 线性合约行情行:GET /v5/market/tickers?category=linear —— 单端点同时携带
29
+ * fundingRate(当前资金费率,小数)、openInterest(base 币计持仓量)、
30
+ * openInterestValue(USD 计价值)。
31
+ */
32
+ getLinearTickerSnapshot(symbol: string): Promise<{
33
+ symbol: string;
34
+ fundingRate?: number;
35
+ openInterest?: number;
36
+ openInterestValue?: number;
37
+ nextFundingTime?: number;
38
+ markPrice?: number;
39
+ indexPrice?: number;
40
+ }>;
41
+ /** 多空账户人数比:GET /v5/market/account-ratio?category=linear(period=1h,limit=1,buyRatio/sellRatio 为账户占比)。 */
42
+ getLinearAccountRatio(symbol: string): Promise<{
43
+ buyRatio: number;
44
+ sellRatio: number;
45
+ }>;
46
+ /** 资金费率历史:GET /v5/market/funding/history?category=linear(响应新→旧 → 反转升序)。 */
47
+ getLinearFundingHistory(symbol: string, limit?: number): Promise<DerivativesPoint[]>;
48
+ /**
49
+ * OI 历史:GET /v5/market/open-interest?category=linear&intervalTime=1d
50
+ * (openInterest 为 base 币数,与快照同语义;响应新→旧 → 反转升序。
51
+ * 2026-09-03 真实网络实证,spikes/impl-crypto-derivatives)。
52
+ */
53
+ getLinearOpenInterestHistory(symbol: string, limit?: number): Promise<DerivativesPoint[]>;
54
+ /**
55
+ * 盘口快照:GET /v5/market/orderbook?category=spot(limit=25)。
56
+ * v5 盘口字段是缩写 `result.b`(bids 降序)/ `result.a`(asks 升序)——不是
57
+ * bids/asks 全称(2026-09-02 真实响应实证,spikes/impl-orderbook-ticks/bybit-orderbook-raw.json)。
58
+ */
59
+ getOrderbook(symbol: string): Promise<Orderbook>;
60
+ /** 最近逐笔成交:GET /v5/market/recent-trade?category=spot(响应新→旧 → 反转升序)。 */
61
+ getRecentTrades(symbol: string, limit?: number): Promise<TradeTick[]>;
62
+ getBalance(): Promise<AccountBalance$1>;
63
+ placeOrder(_creds: unknown, req: OrderRequest): Promise<Order$1>;
64
+ cancelOrder(_creds: unknown, orderId: string): Promise<{
65
+ orderId: string;
66
+ status: 'canceled';
67
+ }>;
68
+ }
69
+ //#endregion
70
+ export { type AccountBalance$1 as AccountBalance, BybitRestClient, BybitRestOptions, 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, normalizeCryptoSymbol, parseIntervalMs, toBybitInterval };
package/lib/rest.js ADDED
@@ -0,0 +1,278 @@
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
+ "4h",
18
+ "1d",
19
+ "1w",
20
+ "1M"
21
+ ];
22
+ function toBybitInterval(interval) {
23
+ switch (interval) {
24
+ case "1m": return "1";
25
+ case "5m": return "5";
26
+ case "15m": return "15";
27
+ case "30m": return "30";
28
+ case "1h": return "60";
29
+ case "4h": return "240";
30
+ case "1d": return "D";
31
+ case "1w": return "W";
32
+ case "1M": return "M";
33
+ }
34
+ }
35
+ function parseIntervalMs(interval) {
36
+ switch (interval) {
37
+ case "1m": return 6e4;
38
+ case "5m": return 3e5;
39
+ case "15m": return 9e5;
40
+ case "30m": return 18e5;
41
+ case "1h": return 36e5;
42
+ case "4h": return 144e5;
43
+ case "1d": return 864e5;
44
+ case "1w": return 6048e5;
45
+ case "1M": return 2592e6;
46
+ }
47
+ }
48
+ function normalizeCryptoSymbol(raw) {
49
+ const clean = raw.trim().toUpperCase().replace(/-SWAP$/, "").replace(/[-_/]/g, "");
50
+ if (!clean) throw new TradingServiceError("TRADING_INVALID_ARGUMENT", "Symbol cannot be empty");
51
+ return clean;
52
+ }
53
+ /** 宽松转 number(字符串/数字皆收,非有限值返回 undefined)。 */
54
+ function num(value) {
55
+ if (value === "") return void 0;
56
+ const n = typeof value === "string" ? Number(value) : typeof value === "number" ? value : NaN;
57
+ return Number.isFinite(n) ? n : void 0;
58
+ }
59
+ var BybitRestClient = class {
60
+ baseUrl;
61
+ apiKey;
62
+ apiSecret;
63
+ fetchImpl;
64
+ constructor(options = {}) {
65
+ this.baseUrl = options.baseUrl ?? "https://api.bybit.com";
66
+ this.apiKey = options.apiKey;
67
+ this.apiSecret = options.apiSecret;
68
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
69
+ }
70
+ async requestJson(path) {
71
+ const url = `${this.baseUrl}${path}`;
72
+ try {
73
+ const res = await this.fetchImpl(url, { headers: { "Accept": "application/json" } });
74
+ if (!res.ok) throw new TradingServiceError("TRADING_UPSTREAM_ERROR", `Bybit HTTP ${res.status}: ${res.statusText}`);
75
+ return await res.json();
76
+ } catch (err) {
77
+ if (err instanceof TradingServiceError) throw err;
78
+ throw new TradingServiceError("TRADING_NETWORK", `Bybit network error: ${err instanceof Error ? err.message : String(err)}`, err);
79
+ }
80
+ }
81
+ async getTicker(symbol) {
82
+ const sym = normalizeCryptoSymbol(symbol);
83
+ const data = await this.requestJson(`/v5/market/tickers?category=spot&symbol=${sym}`);
84
+ if (data.retCode !== 0 || !data.result?.list || data.result.list.length === 0) throw new TradingServiceError("TRADING_SYMBOL_NOT_FOUND", `Bybit ticker not found for ${sym}`);
85
+ const row = data.result.list[0];
86
+ const price = parseFloat(row.lastPrice);
87
+ const volume = parseFloat(row.volume24h);
88
+ const timestamp = row.time ? row.time : Date.now();
89
+ const prevClose = row.prevPrice24h ? parseFloat(row.prevPrice24h) : void 0;
90
+ const changePercent = row.price24hPcnt ? parseFloat(row.price24hPcnt) * 100 : void 0;
91
+ return {
92
+ symbol: sym,
93
+ price,
94
+ volume,
95
+ timestamp,
96
+ ...prevClose !== void 0 && Number.isFinite(prevClose) ? { prevClose } : {},
97
+ ...changePercent !== void 0 && Number.isFinite(changePercent) ? { changePercent } : {}
98
+ };
99
+ }
100
+ async getKlines(symbol, interval = "1d", limit = 100) {
101
+ const sym = normalizeCryptoSymbol(symbol);
102
+ const bybitInt = toBybitInterval(interval);
103
+ const stepMs = parseIntervalMs(interval);
104
+ const data = await this.requestJson(`/v5/market/kline?category=spot&symbol=${sym}&interval=${bybitInt}&limit=${limit}`);
105
+ if (data.retCode !== 0 || !data.result?.list) return [];
106
+ return [...data.result.list].reverse().map((r) => {
107
+ const openTime = parseInt(r[0], 10);
108
+ return {
109
+ openTime,
110
+ open: parseFloat(r[1]),
111
+ high: parseFloat(r[2]),
112
+ low: parseFloat(r[3]),
113
+ close: parseFloat(r[4]),
114
+ volume: parseFloat(r[5]),
115
+ closeTime: openTime + stepMs - 1
116
+ };
117
+ });
118
+ }
119
+ /**
120
+ * 线性合约行情行:GET /v5/market/tickers?category=linear —— 单端点同时携带
121
+ * fundingRate(当前资金费率,小数)、openInterest(base 币计持仓量)、
122
+ * openInterestValue(USD 计价值)。
123
+ */
124
+ async getLinearTickerSnapshot(symbol) {
125
+ const sym = normalizeCryptoSymbol(symbol);
126
+ const data = await this.requestJson(`/v5/market/tickers?category=linear&symbol=${sym}`);
127
+ if (data.retCode !== 0 || !data.result?.list || data.result.list.length === 0) throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", `Bybit linear tickers not found for ${sym}`);
128
+ const row = data.result.list[0];
129
+ const fundingRate = num(row.fundingRate);
130
+ const openInterest = num(row.openInterest);
131
+ const openInterestValue = num(row.openInterestValue);
132
+ const nextFundingTime = num(row.nextFundingTime);
133
+ const markPrice = num(row.markPrice);
134
+ const indexPrice = num(row.indexPrice);
135
+ return {
136
+ symbol: typeof row.symbol === "string" && row.symbol ? row.symbol : sym,
137
+ ...fundingRate !== void 0 ? { fundingRate } : {},
138
+ ...openInterest !== void 0 ? { openInterest } : {},
139
+ ...openInterestValue !== void 0 ? { openInterestValue } : {},
140
+ ...nextFundingTime !== void 0 ? { nextFundingTime } : {},
141
+ ...markPrice !== void 0 ? { markPrice } : {},
142
+ ...indexPrice !== void 0 ? { indexPrice } : {}
143
+ };
144
+ }
145
+ /** 多空账户人数比:GET /v5/market/account-ratio?category=linear(period=1h,limit=1,buyRatio/sellRatio 为账户占比)。 */
146
+ async getLinearAccountRatio(symbol) {
147
+ const sym = normalizeCryptoSymbol(symbol);
148
+ const data = await this.requestJson(`/v5/market/account-ratio?category=linear&symbol=${sym}&period=1h&limit=1`);
149
+ if (data.retCode !== 0 || !data.result?.list || data.result.list.length === 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit account ratio not found for ${sym}`);
150
+ const row = data.result.list[0];
151
+ const buyRatio = num(row.buyRatio);
152
+ const sellRatio = num(row.sellRatio);
153
+ if (buyRatio === void 0 || sellRatio === void 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit account ratio for ${sym}: missing/invalid buyRatio/sellRatio`);
154
+ return {
155
+ buyRatio,
156
+ sellRatio
157
+ };
158
+ }
159
+ /** 资金费率历史:GET /v5/market/funding/history?category=linear(响应新→旧 → 反转升序)。 */
160
+ async getLinearFundingHistory(symbol, limit = 30) {
161
+ const sym = normalizeCryptoSymbol(symbol);
162
+ const capped = Math.max(1, Math.min(Math.floor(limit) || 30, 100));
163
+ const data = await this.requestJson(`/v5/market/funding/history?category=linear&symbol=${sym}&limit=${capped}`);
164
+ if (data.retCode !== 0 || !Array.isArray(data.result?.list)) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit funding history for ${sym}: ${data.retMsg}`);
165
+ const points = [];
166
+ for (const row of data.result.list) {
167
+ const time = num(row.fundingRateTimestamp);
168
+ const value = num(row.fundingRate);
169
+ if (time !== void 0 && value !== void 0) points.push({
170
+ time,
171
+ value
172
+ });
173
+ }
174
+ return points.reverse();
175
+ }
176
+ /**
177
+ * OI 历史:GET /v5/market/open-interest?category=linear&intervalTime=1d
178
+ * (openInterest 为 base 币数,与快照同语义;响应新→旧 → 反转升序。
179
+ * 2026-09-03 真实网络实证,spikes/impl-crypto-derivatives)。
180
+ */
181
+ async getLinearOpenInterestHistory(symbol, limit = 30) {
182
+ const sym = normalizeCryptoSymbol(symbol);
183
+ const capped = Math.max(1, Math.min(Math.floor(limit) || 30, 50));
184
+ const data = await this.requestJson(`/v5/market/open-interest?category=linear&symbol=${sym}&intervalTime=1d&limit=${capped}`);
185
+ if (data.retCode !== 0 || !Array.isArray(data.result?.list)) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit OI history for ${sym}: ${data.retMsg}`);
186
+ const points = [];
187
+ for (const row of data.result.list) {
188
+ const time = num(row.timestamp);
189
+ const value = num(row.openInterest);
190
+ if (time !== void 0 && value !== void 0) points.push({
191
+ time,
192
+ value
193
+ });
194
+ }
195
+ return points.reverse();
196
+ }
197
+ /** orderbook 档位行 [price, size] → OrderbookLevel。 */
198
+ #parseBookRow(row) {
199
+ if (!Array.isArray(row) || row.length < 2) return void 0;
200
+ const price = num(row[0]);
201
+ const amount = num(row[1]);
202
+ if (price === void 0 || amount === void 0 || price <= 0 || amount <= 0) return void 0;
203
+ return {
204
+ price,
205
+ amount
206
+ };
207
+ }
208
+ /**
209
+ * 盘口快照:GET /v5/market/orderbook?category=spot(limit=25)。
210
+ * v5 盘口字段是缩写 `result.b`(bids 降序)/ `result.a`(asks 升序)——不是
211
+ * bids/asks 全称(2026-09-02 真实响应实证,spikes/impl-orderbook-ticks/bybit-orderbook-raw.json)。
212
+ */
213
+ async getOrderbook(symbol) {
214
+ const sym = normalizeCryptoSymbol(symbol);
215
+ const data = await this.requestJson(`/v5/market/orderbook?category=spot&symbol=${sym}&limit=25`);
216
+ if (data.retCode !== 0 || !Array.isArray(data.result?.b) || !Array.isArray(data.result?.a)) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit orderbook for ${sym}: unexpected response shape`);
217
+ return {
218
+ symbol: sym,
219
+ bids: data.result.b.map((row) => this.#parseBookRow(row)).filter((l) => l !== void 0),
220
+ asks: data.result.a.map((row) => this.#parseBookRow(row)).filter((l) => l !== void 0),
221
+ timestamp: num(data.result.ts) ?? Date.now()
222
+ };
223
+ }
224
+ /** recent-trade 行 → TradeTick(side 即 taker 方向,Bybit 大写词汇;响应新→旧 → 反转升序)。 */
225
+ #parseTradeRow(row, symbol) {
226
+ const price = num(row.price);
227
+ const amount = num(row.size);
228
+ if (price === void 0 || amount === void 0) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit trades for ${symbol}: malformed trade row`);
229
+ const rawSide = typeof row.side === "string" ? row.side.toLowerCase() : "";
230
+ const side = rawSide === "buy" || rawSide === "sell" ? rawSide : "unknown";
231
+ return {
232
+ id: String(row.execId ?? ""),
233
+ symbol,
234
+ price,
235
+ amount,
236
+ side,
237
+ timestamp: num(row.time) ?? Date.now()
238
+ };
239
+ }
240
+ /** 最近逐笔成交:GET /v5/market/recent-trade?category=spot(响应新→旧 → 反转升序)。 */
241
+ async getRecentTrades(symbol, limit = 50) {
242
+ const sym = normalizeCryptoSymbol(symbol);
243
+ const capped = Math.max(1, Math.min(Math.floor(limit) || 50, 60));
244
+ const data = await this.requestJson(`/v5/market/recent-trade?category=spot&symbol=${sym}&limit=${capped}`);
245
+ if (data.retCode !== 0 || !data.result?.list) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Bybit trades for ${sym}: unexpected response shape`);
246
+ const symbolOut = sym;
247
+ return data.result.list.map((row) => this.#parseTradeRow(row, symbolOut)).reverse();
248
+ }
249
+ async getBalance() {
250
+ return {
251
+ currency: "USDT",
252
+ available: 1e5,
253
+ total: 1e5
254
+ };
255
+ }
256
+ async placeOrder(_creds, req) {
257
+ const sym = normalizeCryptoSymbol(req.symbol);
258
+ return {
259
+ id: `sim-bybit-${Date.now()}`,
260
+ symbol: sym,
261
+ side: req.side,
262
+ type: req.type,
263
+ status: "filled",
264
+ quantity: req.quantity,
265
+ price: req.price ?? 0,
266
+ dryRun: true,
267
+ timestamp: Date.now()
268
+ };
269
+ }
270
+ async cancelOrder(_creds, orderId) {
271
+ return {
272
+ orderId,
273
+ status: "canceled"
274
+ };
275
+ }
276
+ };
277
+ //#endregion
278
+ export { BybitRestClient, INTERVAL_VOCABULARY, TradingServiceError, normalizeCryptoSymbol, parseIntervalMs, toBybitInterval };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dshtrading/connector-bybit",
3
+ "description": "【模板】交易所连接器插件脚手架:Bybit(bybit)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
+ }