@dshtrading/connector-alpaca 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
+ `alpaca`(slug)/ `Alpaca`(title)/ `ALPACA`(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,47 @@
1
+ import { AlpacaMarketDataService, AlpacaTradeService, TRADING_US_MARKET_DATA_KEY, TRADING_US_TRADE_KEY, credentialRefsFor, resolveCredentials } from "./index.js";
2
+ //#region src/dataplane.ts
3
+ const inject = [];
4
+ /** 解析注册表服务;老部署(base/router 未升级)返回 undefined → 调用方回退直接 provide。 */
5
+ function resolveMarketDataRegistry(ctx) {
6
+ const candidate = ctx.get?.("tradingMarketDataRegistry", false);
7
+ return candidate !== void 0 ? candidate : void 0;
8
+ }
9
+ /** 解析交易注册表服务(issue #40);老部署返回 undefined → 跳过。 */
10
+ function resolveTradeRegistry(ctx) {
11
+ const candidate = ctx.get?.("tradingTradeRegistry", false);
12
+ return candidate !== void 0 ? candidate : void 0;
13
+ }
14
+ /** 本连接器的路由 provider slug(路由层词汇 = 交易所 slug,docs/exchange-routing.md §2.2)。 */
15
+ const ROUTER_PROVIDER = "alpaca";
16
+ /** 市场短前缀。 */
17
+ const MARKET = "us";
18
+ function apply(ctx, config) {
19
+ if (!config.enabled) return;
20
+ const registry = resolveMarketDataRegistry(ctx);
21
+ if (registry === void 0) {
22
+ new AlpacaMarketDataService(ctx);
23
+ return;
24
+ }
25
+ const inner = ctx.isolate(TRADING_US_MARKET_DATA_KEY);
26
+ const service = new AlpacaMarketDataService(inner, {}, () => {
27
+ const refs = credentialRefsFor(config);
28
+ return resolveCredentials(ctx, refs, config.env);
29
+ });
30
+ ctx.effect(() => registry.register(MARKET, ROUTER_PROVIDER, service));
31
+ const tradeRegistry = resolveTradeRegistry(ctx);
32
+ if (tradeRegistry !== void 0) {
33
+ const tradeInner = ctx.isolate(TRADING_US_TRADE_KEY);
34
+ const trade = new AlpacaTradeService(tradeInner, {
35
+ config,
36
+ env: config.env
37
+ }, async () => {
38
+ const refs = credentialRefsFor(config);
39
+ const creds = await resolveCredentials(ctx, refs, config.env);
40
+ if (!creds) throw new Error("Alpaca credentials missing");
41
+ return creds;
42
+ });
43
+ ctx.effect(() => tradeRegistry.register(MARKET, ROUTER_PROVIDER, trade));
44
+ }
45
+ }
46
+ //#endregion
47
+ export { apply, inject };
package/lib/index.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { AccountBalance, AlpacaCredentials, AlpacaRestClient, AlpacaRestOptions, INTERVAL_TO_ALPACA, INTERVAL_VOCABULARY, Interval, Kline, Order, Orderbook, Position, Ticker, TradeFill, TradingServiceError, normalizeUsSymbol } 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, Orderbook as Orderbook$1, Position as Position$1, Ticker as Ticker$1, TradeFill as TradeFill$1, TradeService } from "@dshtrading/api";
5
+ //#region src/index.d.ts
6
+ declare const name = "dsh-trading-us-connector-alpaca";
7
+ interface Config {
8
+ enabled: boolean;
9
+ env: 'demo' | 'live';
10
+ dryRun: boolean;
11
+ liveTrading: boolean;
12
+ apiKeyRef: string;
13
+ secretRef: string;
14
+ demoApiKeyRef: string;
15
+ demoSecretRef: string;
16
+ }
17
+ declare const Config: Schema<Config>;
18
+ declare const inject: string[];
19
+ declare const TRADING_US_MARKET_DATA_KEY = "tradingUsMarketData";
20
+ declare const TRADING_US_TRADE_KEY = "tradingUsTrade";
21
+ interface CredentialResolverLike {
22
+ resolve(ref: string): Promise<{
23
+ value: string;
24
+ } | undefined>;
25
+ }
26
+ interface CredentialsContext {
27
+ get(name: string): unknown;
28
+ }
29
+ interface ResolvedCredentialRefs {
30
+ readonly apiKeyRef: string;
31
+ readonly secretRef: string;
32
+ }
33
+ declare function credentialRefsFor(config: Config, env?: 'demo' | 'live'): ResolvedCredentialRefs;
34
+ declare function resolveCredentials(ctx: CredentialsContext, refs: ResolvedCredentialRefs, env: 'demo' | 'live'): Promise<AlpacaCredentials | undefined>;
35
+ declare class AlpacaMarketDataService extends Service implements MarketDataService {
36
+ private readonly client;
37
+ private readonly getCredentials;
38
+ constructor(ctx: Context, options?: AlpacaRestOptions, getCredentials?: () => Promise<AlpacaCredentials | undefined>, serviceName?: string);
39
+ getTicker(symbol: string): Promise<Ticker$1>;
40
+ getKlines(symbol: string, interval: Interval$1, limit?: number): Promise<Kline$1[]>;
41
+ listInstruments(): Promise<Array<{
42
+ symbol: string;
43
+ name?: string;
44
+ }>>;
45
+ getOrderbook(symbol: string): Promise<Orderbook$1>;
46
+ subscribeTicker(symbol: string, cb: (ticker: Ticker$1) => void, options?: {
47
+ intervalMs?: number;
48
+ }): Disposable;
49
+ }
50
+ declare class AlpacaTradeService extends Service implements TradeService {
51
+ private readonly client;
52
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
53
+ private readonly config;
54
+ private readonly getCredentials;
55
+ constructor(ctx: Context, options: AlpacaRestOptions & {
56
+ config: Config;
57
+ }, getCredentials: () => Promise<AlpacaCredentials>, serviceName?: string);
58
+ getBalance(): Promise<AccountBalance$1>;
59
+ getBalances(): Promise<AccountBalance$1[]>;
60
+ placeOrder(order: OrderRequest): Promise<Order$1>;
61
+ cancelOrder(orderId: string, _symbol?: string): Promise<void>;
62
+ getOrder(_symbol: string, id: string): Promise<Order$1>;
63
+ getPositions(): Promise<Position$1[]>;
64
+ listOpenOrders(symbol?: string): Promise<Order$1[]>;
65
+ listTradeFills(symbol?: string, limit?: number): Promise<TradeFill$1[]>;
66
+ }
67
+ interface PlaceOrderArgs {
68
+ readonly symbol: string;
69
+ readonly side: 'BUY' | 'SELL';
70
+ readonly type: 'MARKET' | 'LIMIT';
71
+ readonly quantity: number;
72
+ readonly price?: number;
73
+ readonly dryRun?: boolean;
74
+ }
75
+ type OrderGateVerdict = {
76
+ action: 'reject';
77
+ code: 'TRADING_LIVE_TRADING_DISABLED';
78
+ message: string;
79
+ } | {
80
+ action: 'simulate';
81
+ } | {
82
+ action: 'live';
83
+ };
84
+ declare function evaluateOrderGate(config: Config, args: PlaceOrderArgs): OrderGateVerdict;
85
+ declare function createPlaceOrderTool(deps: {
86
+ marketData: Pick<MarketDataService, 'getTicker'>;
87
+ trade?: TradeService;
88
+ config: Config;
89
+ }): import("@deepseek-ai/dsh-tools").ToolDefinition;
90
+ declare const ROUTER_PROVIDER = "alpaca";
91
+ declare function routeAllows(ctx: Context, config: Config, market: string): boolean;
92
+ declare function apply(ctx: Context, config: Config): void;
93
+ //#endregion
94
+ export { type AccountBalance, AlpacaCredentials, AlpacaMarketDataService, AlpacaRestClient, AlpacaRestOptions, AlpacaTradeService, Config, CredentialResolverLike, CredentialsContext, INTERVAL_TO_ALPACA, INTERVAL_VOCABULARY, type Interval, type Kline, type Order, OrderGateVerdict, type Orderbook, PlaceOrderArgs, type Position, ROUTER_PROVIDER, ResolvedCredentialRefs, TRADING_US_MARKET_DATA_KEY, TRADING_US_TRADE_KEY, type Ticker, type TradeFill, TradingServiceError, apply, createPlaceOrderTool, credentialRefsFor, evaluateOrderGate, inject, name, normalizeUsSymbol, resolveCredentials, routeAllows };
package/lib/index.js ADDED
@@ -0,0 +1,352 @@
1
+ import { AlpacaRestClient, INTERVAL_TO_ALPACA, INTERVAL_VOCABULARY, TradingServiceError, normalizeUsSymbol } 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-alpaca";
7
+ const Config = Schema.object({
8
+ enabled: Schema.boolean().default(false),
9
+ env: Schema.union(["demo", "live"]).default("demo"),
10
+ dryRun: Schema.boolean().default(true),
11
+ liveTrading: Schema.boolean().default(false),
12
+ apiKeyRef: Schema.string().default("ALPACA_API_KEY"),
13
+ secretRef: Schema.string().default("ALPACA_SECRET_KEY"),
14
+ demoApiKeyRef: Schema.string().default("ALPACA_PAPER_API_KEY"),
15
+ demoSecretRef: Schema.string().default("ALPACA_PAPER_SECRET_KEY")
16
+ });
17
+ const inject = ["tools"];
18
+ const TRADING_US_MARKET_DATA_KEY = "tradingUsMarketData";
19
+ const TRADING_US_TRADE_KEY = "tradingUsTrade";
20
+ const CREDENTIAL_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
21
+ function credentialRefsFor(config, env = config.env) {
22
+ return env === "demo" ? {
23
+ apiKeyRef: config.demoApiKeyRef,
24
+ secretRef: config.demoSecretRef
25
+ } : {
26
+ apiKeyRef: config.apiKeyRef,
27
+ secretRef: config.secretRef
28
+ };
29
+ }
30
+ async function resolveCredentials(ctx, refs, env) {
31
+ const entries = [["apiKey", refs.apiKeyRef], ["secret", refs.secretRef]];
32
+ const routerCreds = (ctx.get("tradingMarketRouter") ?? void 0)?.getCredential?.("alpaca");
33
+ if (routerCreds?.apiKey && (routerCreds?.secretKey || routerCreds?.secret)) return {
34
+ key: routerCreds.apiKey,
35
+ secret: routerCreds.secretKey || routerCreds.secret
36
+ };
37
+ for (const [field, ref] of entries) if (!CREDENTIAL_REF_PATTERN.test(ref)) throw new TradingServiceError("TRADING_CREDENTIALS_MISSING", `Alpaca ${env} credentials invalid: ${field} ref ${JSON.stringify(ref)} must match ^[A-Za-z_][A-Za-z0-9_]*$`);
38
+ const resolver = ctx.get("credentials");
39
+ const resolved = await Promise.all(entries.map(async ([field, ref]) => {
40
+ if (resolver !== void 0) try {
41
+ const res = await resolver.resolve(ref);
42
+ if (res?.value) return {
43
+ field,
44
+ value: res.value
45
+ };
46
+ } catch {}
47
+ const envVal = process.env[ref];
48
+ if (envVal) return {
49
+ field,
50
+ value: envVal
51
+ };
52
+ return {
53
+ field,
54
+ value: void 0
55
+ };
56
+ }));
57
+ if (resolved.filter((r) => !r.value).map((r) => r.field).length > 0) return;
58
+ const [apiKey, secret] = resolved.map((r) => r.value);
59
+ return {
60
+ key: apiKey,
61
+ secret
62
+ };
63
+ }
64
+ var AlpacaMarketDataService = class extends Service {
65
+ client;
66
+ getCredentials;
67
+ constructor(ctx, options = {}, getCredentials = async () => void 0, serviceName = TRADING_US_MARKET_DATA_KEY) {
68
+ super(ctx, serviceName);
69
+ this.client = new AlpacaRestClient(options);
70
+ this.getCredentials = getCredentials;
71
+ }
72
+ async getTicker(symbol) {
73
+ const creds = await this.getCredentials();
74
+ return this.client.getTicker(symbol, creds);
75
+ }
76
+ async getKlines(symbol, interval, limit) {
77
+ const creds = await this.getCredentials();
78
+ return this.client.getKlines(symbol, interval, limit, creds);
79
+ }
80
+ async listInstruments() {
81
+ const creds = await this.getCredentials();
82
+ return this.client.listInstruments(creds);
83
+ }
84
+ async getOrderbook(symbol) {
85
+ const creds = await this.getCredentials();
86
+ return this.client.getOrderbook(symbol, creds);
87
+ }
88
+ subscribeTicker(symbol, cb, options) {
89
+ const ms = Math.max(options?.intervalMs ?? 5e3, 500);
90
+ const tick = () => {
91
+ this.getTicker(symbol).then(cb, () => {});
92
+ };
93
+ tick();
94
+ const timer = setInterval(tick, ms);
95
+ return { dispose: () => clearInterval(timer) };
96
+ }
97
+ };
98
+ var AlpacaTradeService = class extends Service {
99
+ client;
100
+ /** 插件配置(服务缝闸门 P0:dryRun 强制模拟 / liveTrading 总闸门)。 */
101
+ config;
102
+ getCredentials;
103
+ constructor(ctx, options, getCredentials, serviceName = TRADING_US_TRADE_KEY) {
104
+ super(ctx, serviceName);
105
+ this.client = new AlpacaRestClient(options);
106
+ this.config = options.config;
107
+ this.getCredentials = getCredentials;
108
+ }
109
+ async getBalance() {
110
+ const creds = await this.getCredentials();
111
+ return this.client.getBalance(creds);
112
+ }
113
+ async getBalances() {
114
+ const creds = await this.getCredentials();
115
+ return [await this.client.getBalance(creds)];
116
+ }
117
+ async placeOrder(order) {
118
+ const requestedDryRun = order.dryRun ?? true;
119
+ if (!requestedDryRun && !this.config.liveTrading) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", `Alpaca 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
+ const creds = await this.getCredentials();
132
+ return this.client.placeOrder(creds, {
133
+ symbol: order.symbol,
134
+ side: order.side.toUpperCase(),
135
+ type: order.type.toUpperCase(),
136
+ quantity: order.quantity,
137
+ price: order.price
138
+ });
139
+ }
140
+ async cancelOrder(orderId, _symbol) {
141
+ if (!this.config.liveTrading || this.config.dryRun) throw new TradingServiceError("TRADING_LIVE_TRADING_DISABLED", "Alpaca TradeService.cancelOrder rejected at the service seam: cancel is a live action and requires liveTrading=true with dryRun=false.");
142
+ const creds = await this.getCredentials();
143
+ await this.client.cancelOrder(creds, orderId);
144
+ }
145
+ async getOrder(_symbol, id) {
146
+ const creds = await this.getCredentials();
147
+ return this.client.getOrder(creds, id);
148
+ }
149
+ async getPositions() {
150
+ try {
151
+ const creds = await this.getCredentials();
152
+ return await this.client.getPositions(creds);
153
+ } catch {
154
+ return [];
155
+ }
156
+ }
157
+ async listOpenOrders(symbol) {
158
+ try {
159
+ const creds = await this.getCredentials();
160
+ return await this.client.listOpenOrders(creds, symbol);
161
+ } catch {
162
+ return [];
163
+ }
164
+ }
165
+ async listTradeFills(symbol, limit) {
166
+ try {
167
+ const creds = await this.getCredentials();
168
+ return await this.client.listTradeFills(creds, symbol, limit);
169
+ } catch {
170
+ return [];
171
+ }
172
+ }
173
+ };
174
+ function evaluateOrderGate(config, args) {
175
+ const requestedDryRun = args.dryRun ?? true;
176
+ if (!requestedDryRun && !config.liveTrading) return {
177
+ action: "reject",
178
+ code: "TRADING_LIVE_TRADING_DISABLED",
179
+ message: `us_place_order rejected: real execution requested (dryRun=${String(args.dryRun)}) but live trading is disabled (liveTrading=false). Enable liveTrading explicitly or keep dryRun=true.`
180
+ };
181
+ if (requestedDryRun || config.dryRun) return { action: "simulate" };
182
+ return { action: "live" };
183
+ }
184
+ function createPlaceOrderTool(deps) {
185
+ return defineTool({
186
+ name: "us_place_order",
187
+ description: "Place or simulate a US stock order via Alpaca. dryRun defaults to true for simulated execution.",
188
+ parameters: {
189
+ symbol: {
190
+ type: "string",
191
+ required: true,
192
+ description: "US stock symbol, e.g. AAPL"
193
+ },
194
+ side: {
195
+ type: "string",
196
+ enum: ["BUY", "SELL"],
197
+ required: true,
198
+ description: "Order side"
199
+ },
200
+ type: {
201
+ type: "string",
202
+ enum: ["MARKET", "LIMIT"],
203
+ required: true,
204
+ description: "Order type"
205
+ },
206
+ quantity: {
207
+ type: "number",
208
+ required: true,
209
+ description: "Number of shares (> 0)"
210
+ },
211
+ price: {
212
+ type: "number",
213
+ description: "Limit price; required when type=LIMIT"
214
+ },
215
+ dryRun: {
216
+ type: "boolean",
217
+ default: true,
218
+ description: "Simulate order only (default true)"
219
+ }
220
+ },
221
+ output: {
222
+ schema: { type: "string" },
223
+ render: (_args, value) => [{
224
+ type: "text",
225
+ text: value
226
+ }]
227
+ },
228
+ async execute(raw) {
229
+ const args = raw;
230
+ const verdict = evaluateOrderGate(deps.config, args);
231
+ if (verdict.action === "reject") return JSON.stringify({
232
+ status: "rejected",
233
+ code: verdict.code,
234
+ message: verdict.message
235
+ });
236
+ if (verdict.action === "simulate" || !deps.trade) {
237
+ let referencePrice;
238
+ try {
239
+ referencePrice = (await deps.marketData.getTicker(args.symbol)).price;
240
+ } catch {}
241
+ return JSON.stringify({
242
+ status: "filled",
243
+ dryRun: true,
244
+ id: `dry-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
245
+ symbol: args.symbol.toUpperCase(),
246
+ side: args.side.toLowerCase(),
247
+ type: args.type.toLowerCase(),
248
+ quantity: args.quantity,
249
+ ...args.price ? { price: args.price } : {},
250
+ referencePrice,
251
+ timestamp: Date.now()
252
+ });
253
+ }
254
+ const order = await deps.trade.placeOrder({
255
+ symbol: args.symbol,
256
+ side: args.side,
257
+ type: args.type,
258
+ quantity: args.quantity,
259
+ price: args.price
260
+ });
261
+ return JSON.stringify(order);
262
+ }
263
+ });
264
+ }
265
+ const ROUTER_PROVIDER = "alpaca";
266
+ function routeAllows(ctx, config, market) {
267
+ if (!config.enabled) return false;
268
+ const router = ctx.get?.("tradingMarketRouter", false);
269
+ if (router === void 0) return true;
270
+ return router.activeProvider(market) === ROUTER_PROVIDER;
271
+ }
272
+ function apply(ctx, config) {
273
+ if (!config.enabled) return;
274
+ if (!routeAllows(ctx, config, "us")) return;
275
+ const credRefs = credentialRefsFor(config);
276
+ const getCreds = () => resolveCredentials(ctx, credRefs, config.env);
277
+ const requireCreds = async () => {
278
+ const creds = await getCreds();
279
+ if (!creds) throw new TradingServiceError("TRADING_CREDENTIALS_MISSING", `Alpaca credentials missing for ${config.env}. Set ${credRefs.apiKeyRef} and ${credRefs.secretRef}.`);
280
+ return creds;
281
+ };
282
+ const marketData = new AlpacaMarketDataService(ctx, { env: config.env }, getCreds);
283
+ const trade = new AlpacaTradeService(ctx, {
284
+ env: config.env,
285
+ config
286
+ }, requireCreds);
287
+ ctx.inject(["tools"], (ctx) => {
288
+ const tools = ctx.tools;
289
+ const register = (t) => {
290
+ if (tools.get(t.name) === void 0) tools.register(t);
291
+ };
292
+ register(defineTool({
293
+ name: "us_get_ticker",
294
+ description: "Get the latest trade price and quote for a US stock via Alpaca API.",
295
+ parameters: { symbol: {
296
+ type: "string",
297
+ required: true,
298
+ description: "US stock symbol, e.g. AAPL"
299
+ } },
300
+ output: {
301
+ schema: { type: "string" },
302
+ render: (_a, v) => [{
303
+ type: "text",
304
+ text: v
305
+ }]
306
+ },
307
+ async execute(args) {
308
+ return JSON.stringify(await marketData.getTicker(args.symbol));
309
+ }
310
+ }));
311
+ register(defineTool({
312
+ name: "us_get_klines",
313
+ description: "Get recent public klines for a US stock via Alpaca API. Supports 5m/15m/30m/1h/1d/1w/1M.",
314
+ parameters: {
315
+ symbol: {
316
+ type: "string",
317
+ required: true,
318
+ description: "US stock symbol, e.g. AAPL"
319
+ },
320
+ interval: {
321
+ type: "string",
322
+ enum: INTERVAL_VOCABULARY,
323
+ default: "1d",
324
+ description: "Interval"
325
+ },
326
+ limit: {
327
+ type: "integer",
328
+ default: 100,
329
+ description: "Limit"
330
+ }
331
+ },
332
+ output: {
333
+ schema: { type: "string" },
334
+ render: (_a, v) => [{
335
+ type: "text",
336
+ text: v
337
+ }]
338
+ },
339
+ async execute(args) {
340
+ const klines = await marketData.getKlines(args.symbol, args.interval ?? "1d", args.limit);
341
+ return JSON.stringify(klines);
342
+ }
343
+ }));
344
+ register(createPlaceOrderTool({
345
+ marketData,
346
+ trade,
347
+ config
348
+ }));
349
+ });
350
+ }
351
+ //#endregion
352
+ export { AlpacaMarketDataService, AlpacaRestClient, AlpacaTradeService, Config, INTERVAL_TO_ALPACA, INTERVAL_VOCABULARY, ROUTER_PROVIDER, TRADING_US_MARKET_DATA_KEY, TRADING_US_TRADE_KEY, TradingServiceError, apply, createPlaceOrderTool, credentialRefsFor, evaluateOrderGate, inject, name, normalizeUsSymbol, resolveCredentials, routeAllows };
package/lib/rest.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { AccountBalance as AccountBalance$1, Interval as Interval$1, Kline as Kline$1, Order as Order$1, Orderbook as Orderbook$1, Position as Position$1, Ticker as Ticker$1, TradeFill as TradeFill$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
+ interface AlpacaRestOptions {
8
+ dataBaseUrl?: string;
9
+ tradingBaseUrl?: string;
10
+ env?: 'demo' | 'live';
11
+ fetchImpl?: typeof fetch;
12
+ timeoutMs?: number;
13
+ }
14
+ interface AlpacaCredentials {
15
+ readonly key: string;
16
+ readonly secret: string;
17
+ }
18
+ declare const INTERVAL_TO_ALPACA: Record<Interval$1, string>;
19
+ declare const INTERVAL_VOCABULARY: Interval$1[];
20
+ declare function normalizeUsSymbol(raw: string): string;
21
+ declare class AlpacaRestClient {
22
+ private readonly dataBaseUrl;
23
+ private readonly tradingBaseUrl;
24
+ private readonly fetchImpl;
25
+ private readonly timeoutMs;
26
+ constructor(options?: AlpacaRestOptions);
27
+ private buildHeaders;
28
+ private request;
29
+ getTicker(symbol: string, credentials?: AlpacaCredentials): Promise<Ticker$1>;
30
+ getKlines(symbol: string, interval: Interval$1, limit?: number, credentials?: AlpacaCredentials): Promise<Kline$1[]>;
31
+ listInstruments(credentials?: AlpacaCredentials): Promise<Array<{
32
+ symbol: string;
33
+ name?: string;
34
+ }>>;
35
+ getOrderbook(symbol: string, credentials?: AlpacaCredentials): Promise<Orderbook$1>;
36
+ getBalance(credentials: AlpacaCredentials): Promise<AccountBalance$1>;
37
+ getPositions(credentials: AlpacaCredentials): Promise<Position$1[]>;
38
+ listOpenOrders(credentials: AlpacaCredentials, symbol?: string): Promise<Order$1[]>;
39
+ listTradeFills(credentials: AlpacaCredentials, symbol?: string, limit?: number): Promise<TradeFill$1[]>;
40
+ placeOrder(credentials: AlpacaCredentials, req: {
41
+ symbol: string;
42
+ side: 'BUY' | 'SELL';
43
+ type: 'MARKET' | 'LIMIT';
44
+ quantity: number;
45
+ price?: number;
46
+ }): Promise<Order$1>;
47
+ cancelOrder(credentials: AlpacaCredentials, orderId: string): Promise<void>;
48
+ getOrder(credentials: AlpacaCredentials, orderId: string): Promise<Order$1>;
49
+ }
50
+ //#endregion
51
+ export { type AccountBalance$1 as AccountBalance, AlpacaCredentials, AlpacaRestClient, AlpacaRestOptions, INTERVAL_TO_ALPACA, INTERVAL_VOCABULARY, type Interval$1 as Interval, type Kline$1 as Kline, type Order$1 as Order, type Orderbook$1 as Orderbook, type Position$1 as Position, type Ticker$1 as Ticker, type TradeFill$1 as TradeFill, TradingServiceError, normalizeUsSymbol };
package/lib/rest.js ADDED
@@ -0,0 +1,296 @@
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_TO_ALPACA = {
12
+ "1m": "1Min",
13
+ "5m": "5Min",
14
+ "15m": "15Min",
15
+ "30m": "30Min",
16
+ "1h": "1Hour",
17
+ "4h": "4Hour",
18
+ "1d": "1Day",
19
+ "1w": "1Week",
20
+ "1M": "1Month"
21
+ };
22
+ const INTERVAL_MS = {
23
+ "1m": 6e4,
24
+ "5m": 3e5,
25
+ "15m": 9e5,
26
+ "30m": 18e5,
27
+ "1h": 36e5,
28
+ "4h": 144e5,
29
+ "1d": 864e5,
30
+ "1w": 1008e4,
31
+ "1M": 432e5
32
+ };
33
+ const INTERVAL_VOCABULARY = Object.keys(INTERVAL_TO_ALPACA);
34
+ function normalizeUsSymbol(raw) {
35
+ const s = raw.trim().toUpperCase();
36
+ if (!/^[A-Z]{1,10}(\.[A-Z]{1,4})?$/.test(s)) throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", `Alpaca: malformed US symbol ${JSON.stringify(raw)}`);
37
+ return s;
38
+ }
39
+ var AlpacaRestClient = class {
40
+ dataBaseUrl;
41
+ tradingBaseUrl;
42
+ fetchImpl;
43
+ timeoutMs;
44
+ constructor(options = {}) {
45
+ this.dataBaseUrl = (options.dataBaseUrl ?? "https://data.alpaca.markets/v2").replace(/\/+$/, "");
46
+ const defaultTrading = options.env === "live" ? "https://api.alpaca.markets/v2" : "https://paper-api.alpaca.markets/v2";
47
+ this.tradingBaseUrl = (options.tradingBaseUrl ?? defaultTrading).replace(/\/+$/, "");
48
+ this.fetchImpl = options.fetchImpl ?? fetch;
49
+ this.timeoutMs = options.timeoutMs ?? 1e4;
50
+ }
51
+ buildHeaders(credentials) {
52
+ const headers = { accept: "application/json" };
53
+ if (credentials?.key && credentials?.secret) {
54
+ headers["APCA-API-KEY-ID"] = credentials.key;
55
+ headers["APCA-API-SECRET-KEY"] = credentials.secret;
56
+ }
57
+ return headers;
58
+ }
59
+ async request(baseUrl, path, init = {}, credentials) {
60
+ const url = baseUrl + (path.startsWith("/") ? path : "/" + path);
61
+ const headers = {
62
+ ...this.buildHeaders(credentials),
63
+ ...init.headers
64
+ };
65
+ const controller = new AbortController();
66
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`request timed out after ${this.timeoutMs}ms`)), this.timeoutMs);
67
+ try {
68
+ const res = await this.fetchImpl(url, {
69
+ ...init,
70
+ headers,
71
+ signal: controller.signal
72
+ });
73
+ if (!res.ok) {
74
+ let errBody;
75
+ try {
76
+ errBody = await res.json();
77
+ } catch {
78
+ errBody = await res.text().catch(() => "");
79
+ }
80
+ const msg = typeof errBody === "object" && errBody !== null && "message" in errBody ? String(errBody.message) : String(errBody ?? res.statusText);
81
+ if (res.status === 401 || res.status === 403) throw new TradingServiceError("TRADING_AUTH_FAILED", `Alpaca auth failed (${res.status}): ${msg}`);
82
+ if (res.status === 429) throw new TradingServiceError("TRADING_RATE_LIMITED", `Alpaca rate limited (429): ${msg}`);
83
+ if (res.status === 404) throw new TradingServiceError("TRADING_UNSUPPORTED_SYMBOL", `Alpaca not found (404): ${msg}`);
84
+ if (res.status === 422) {
85
+ if (/insufficient|buying power|balance/i.test(msg)) throw new TradingServiceError("TRADING_INSUFFICIENT_BALANCE", `Alpaca balance error (422): ${msg}`);
86
+ throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Alpaca invalid parameters (422): ${msg}`);
87
+ }
88
+ throw new TradingServiceError("TRADING_EXCHANGE_ERROR", `Alpaca HTTP ${res.status}: ${msg}`);
89
+ }
90
+ return await res.json();
91
+ } catch (error) {
92
+ if (error instanceof TradingServiceError) throw error;
93
+ throw new TradingServiceError("TRADING_NETWORK", error instanceof Error ? error.message : String(error), error);
94
+ } finally {
95
+ clearTimeout(timer);
96
+ }
97
+ }
98
+ async getTicker(symbol, credentials) {
99
+ const sym = normalizeUsSymbol(symbol);
100
+ const [tradeRes, quoteRes] = await Promise.allSettled([this.request(this.dataBaseUrl, `/stocks/${sym}/trades/latest?feed=iex`, { method: "GET" }, credentials), this.request(this.dataBaseUrl, `/stocks/${sym}/quotes/latest?feed=iex`, { method: "GET" }, credentials)]);
101
+ if (tradeRes.status === "rejected" && quoteRes.status === "rejected") throw tradeRes.reason;
102
+ let price = 0;
103
+ let timestamp = Date.now();
104
+ if (tradeRes.status === "fulfilled") {
105
+ const data = tradeRes.value;
106
+ if (typeof data?.trade?.p === "number") price = data.trade.p;
107
+ if (typeof data?.trade?.t === "string") timestamp = new Date(data.trade.t).getTime();
108
+ }
109
+ let bid;
110
+ let ask;
111
+ if (quoteRes.status === "fulfilled") {
112
+ const data = quoteRes.value;
113
+ if (typeof data?.quote?.bp === "number" && data.quote.bp > 0) bid = data.quote.bp;
114
+ if (typeof data?.quote?.ap === "number" && data.quote.ap > 0) ask = data.quote.ap;
115
+ if (price === 0 && bid !== void 0 && ask !== void 0) {
116
+ price = (bid + ask) / 2;
117
+ if (typeof data?.quote?.t === "string") timestamp = new Date(data.quote.t).getTime();
118
+ }
119
+ }
120
+ return {
121
+ symbol: sym,
122
+ price,
123
+ timestamp,
124
+ ...bid !== void 0 ? { bid } : {},
125
+ ...ask !== void 0 ? { ask } : {}
126
+ };
127
+ }
128
+ async getKlines(symbol, interval, limit = 100, credentials) {
129
+ const sym = normalizeUsSymbol(symbol);
130
+ const tf = INTERVAL_TO_ALPACA[interval];
131
+ if (!tf) throw new TradingServiceError("TRADING_UNSUPPORTED_INTERVAL", `Alpaca: unsupported interval ${String(interval)}`);
132
+ const path = `/stocks/bars?symbols=${sym}&timeframe=${tf}&limit=${Math.min(Math.max(Number(limit) || 100, 1), 1e3)}&feed=iex&adjustment=split`;
133
+ const rawBars = (await this.request(this.dataBaseUrl, path, { method: "GET" }, credentials))?.bars?.[sym] ?? [];
134
+ const duration = INTERVAL_MS[interval] ?? 864e5;
135
+ return rawBars.map((bar) => {
136
+ const openTime = new Date(bar.t).getTime();
137
+ return {
138
+ openTime,
139
+ open: Number(bar.o),
140
+ high: Number(bar.h),
141
+ low: Number(bar.l),
142
+ close: Number(bar.c),
143
+ volume: Number(bar.v),
144
+ closeTime: openTime + duration - 1
145
+ };
146
+ });
147
+ }
148
+ async listInstruments(credentials) {
149
+ const body = await this.request(this.tradingBaseUrl, "/assets?status=active&asset_class=us_equity", { method: "GET" }, credentials);
150
+ if (!Array.isArray(body)) throw new TradingServiceError("TRADING_EXCHANGE_ERROR", "Alpaca assets: invalid response shape");
151
+ const result = [];
152
+ for (const item of body) if (item && item.tradable && typeof item.symbol === "string" && item.symbol) result.push({
153
+ symbol: item.symbol,
154
+ ...item.name ? { name: String(item.name) } : {}
155
+ });
156
+ return result;
157
+ }
158
+ async getOrderbook(symbol, credentials) {
159
+ const sym = normalizeUsSymbol(symbol);
160
+ const q = (await this.request(this.dataBaseUrl, `/stocks/${sym}/quotes/latest?feed=iex`, { method: "GET" }, credentials))?.quote;
161
+ const bids = [];
162
+ const asks = [];
163
+ if (typeof q?.bp === "number" && q.bp > 0) bids.push({
164
+ price: q.bp,
165
+ amount: Number(q.bs ?? 100)
166
+ });
167
+ if (typeof q?.ap === "number" && q.ap > 0) asks.push({
168
+ price: q.ap,
169
+ amount: Number(q.as ?? 100)
170
+ });
171
+ return {
172
+ symbol: sym,
173
+ bids,
174
+ asks,
175
+ timestamp: q?.t ? new Date(q.t).getTime() : Date.now()
176
+ };
177
+ }
178
+ async getBalance(credentials) {
179
+ const data = await this.request(this.tradingBaseUrl, "/account", { method: "GET" }, credentials);
180
+ const cash = Number(data.cash ?? data.buying_power ?? 0);
181
+ const total = Number(data.portfolio_value ?? cash);
182
+ return {
183
+ asset: String(data.currency ?? "USD"),
184
+ free: cash,
185
+ locked: Math.max(total - cash, 0)
186
+ };
187
+ }
188
+ async getPositions(credentials) {
189
+ const body = await this.request(this.tradingBaseUrl, "/positions", { method: "GET" }, credentials);
190
+ if (!Array.isArray(body)) return [];
191
+ return body.map((item) => {
192
+ const qty = Number(item.qty ?? 0);
193
+ return {
194
+ symbol: normalizeUsSymbol(String(item.symbol ?? "")),
195
+ side: qty >= 0 ? "long" : "short",
196
+ size: Math.abs(qty),
197
+ entryPrice: Number(item.avg_entry_price ?? 0),
198
+ markPrice: Number(item.current_price ?? 0),
199
+ unrealizedPnl: Number(item.unrealized_pl ?? 0),
200
+ timestamp: Date.now()
201
+ };
202
+ });
203
+ }
204
+ async listOpenOrders(credentials, symbol) {
205
+ const symQuery = symbol ? `&symbols=${normalizeUsSymbol(symbol)}` : "";
206
+ const body = await this.request(this.tradingBaseUrl, `/orders?status=open${symQuery}`, { method: "GET" }, credentials);
207
+ if (!Array.isArray(body)) return [];
208
+ return body.map((data) => {
209
+ const status = String(data.status ?? "new").toLowerCase() === "partially_filled" ? "partially_filled" : "new";
210
+ return {
211
+ id: String(data.id ?? ""),
212
+ symbol: normalizeUsSymbol(String(data.symbol ?? "")),
213
+ side: String(data.side ?? "buy").toLowerCase() === "sell" ? "sell" : "buy",
214
+ type: String(data.type ?? "market").toLowerCase() === "limit" ? "limit" : "market",
215
+ status,
216
+ price: data.limit_price !== void 0 ? Number(data.limit_price) : void 0,
217
+ quantity: Number(data.qty ?? 0),
218
+ filledQuantity: Number(data.filled_qty ?? 0),
219
+ dryRun: false,
220
+ timestamp: data.created_at ? new Date(String(data.created_at)).getTime() : Date.now()
221
+ };
222
+ });
223
+ }
224
+ async listTradeFills(credentials, symbol, limit = 50) {
225
+ const body = await this.request(this.tradingBaseUrl, `/account/activities/FILL?page_size=${Math.min(limit, 100)}`, { method: "GET" }, credentials);
226
+ if (!Array.isArray(body)) return [];
227
+ const sym = symbol ? normalizeUsSymbol(symbol) : void 0;
228
+ const fills = [];
229
+ for (const data of body) {
230
+ const itemSym = normalizeUsSymbol(String(data.symbol ?? ""));
231
+ if (sym && itemSym !== sym) continue;
232
+ fills.push({
233
+ id: String(data.id ?? ""),
234
+ symbol: itemSym,
235
+ side: String(data.side ?? "buy").toLowerCase() === "sell" ? "sell" : "buy",
236
+ price: Number(data.price ?? 0),
237
+ amount: Number(data.qty ?? 0),
238
+ timestamp: data.transaction_time ? new Date(String(data.transaction_time)).getTime() : Date.now()
239
+ });
240
+ }
241
+ return fills;
242
+ }
243
+ async placeOrder(credentials, req) {
244
+ const sym = normalizeUsSymbol(req.symbol);
245
+ const body = {
246
+ symbol: sym,
247
+ qty: String(req.quantity),
248
+ side: req.side.toLowerCase(),
249
+ type: req.type.toLowerCase(),
250
+ time_in_force: "gtc"
251
+ };
252
+ if (req.type === "LIMIT" && req.price !== void 0) body.limit_price = String(req.price);
253
+ const data = await this.request(this.tradingBaseUrl, "/orders", {
254
+ method: "POST",
255
+ headers: { "Content-Type": "application/json" },
256
+ body: JSON.stringify(body)
257
+ }, credentials);
258
+ return {
259
+ id: String(data.id ?? `alpaca-${Date.now()}`),
260
+ symbol: sym,
261
+ side: req.side.toLowerCase() === "sell" ? "sell" : "buy",
262
+ type: req.type.toLowerCase() === "limit" ? "limit" : "market",
263
+ quantity: req.quantity,
264
+ price: req.price,
265
+ status: String(data.status ?? "pending"),
266
+ dryRun: false,
267
+ timestamp: Date.now()
268
+ };
269
+ }
270
+ async cancelOrder(credentials, orderId) {
271
+ try {
272
+ await this.request(this.tradingBaseUrl, `/orders/${orderId}`, { method: "DELETE" }, credentials);
273
+ } catch (err) {
274
+ if (err instanceof TradingServiceError && err.code === "TRADING_UNSUPPORTED_SYMBOL") return;
275
+ }
276
+ }
277
+ async getOrder(credentials, orderId) {
278
+ const data = await this.request(this.tradingBaseUrl, `/orders/${orderId}`, { method: "GET" }, credentials);
279
+ const rawStatus = String(data.status ?? "new").toLowerCase();
280
+ const status = rawStatus === "filled" ? "filled" : rawStatus === "canceled" ? "canceled" : rawStatus === "partially_filled" ? "partially_filled" : "new";
281
+ return {
282
+ id: String(data.id ?? orderId),
283
+ symbol: normalizeUsSymbol(String(data.symbol ?? "")),
284
+ side: String(data.side ?? "buy").toLowerCase() === "sell" ? "sell" : "buy",
285
+ type: String(data.type ?? "market").toLowerCase() === "limit" ? "limit" : "market",
286
+ status,
287
+ price: data.limit_price !== void 0 ? Number(data.limit_price) : void 0,
288
+ quantity: Number(data.qty ?? 0),
289
+ filledQuantity: Number(data.filled_qty ?? 0),
290
+ dryRun: false,
291
+ timestamp: data.created_at ? new Date(String(data.created_at)).getTime() : Date.now()
292
+ };
293
+ }
294
+ };
295
+ //#endregion
296
+ export { AlpacaRestClient, INTERVAL_TO_ALPACA, INTERVAL_VOCABULARY, TradingServiceError, normalizeUsSymbol };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dshtrading/connector-alpaca",
3
+ "description": "【模板】交易所连接器插件脚手架:Alpaca(alpaca)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
+ }