visionclaw 0.1.220-beta.12 → 0.1.220-beta.13
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/dist/builtin-skills/rethinka-fund/SKILL.md +24 -19
- package/dist/builtin-skills/rethinka-fund/core-contract.md +1 -0
- package/dist/channels/rethinka-fund.d.ts +1 -1
- package/dist/channels/rethinka-fund.js +1 -1
- package/dist/rethinka-fund/ibkr-mcp.d.ts +80 -0
- package/dist/rethinka-fund/ibkr-mcp.d.ts.map +1 -0
- package/dist/rethinka-fund/ibkr-mcp.js +343 -0
- package/dist/rethinka-fund/ibkr-mcp.js.map +1 -0
- package/dist/rethinka-fund/ibkr-sync.d.ts +19 -17
- package/dist/rethinka-fund/ibkr-sync.d.ts.map +1 -1
- package/dist/rethinka-fund/ibkr-sync.js +24 -30
- package/dist/rethinka-fund/ibkr-sync.js.map +1 -1
- package/dist/tools/rethinka-fund-trading.d.ts +5 -0
- package/dist/tools/rethinka-fund-trading.d.ts.map +1 -1
- package/dist/tools/rethinka-fund-trading.js +19 -0
- package/dist/tools/rethinka-fund-trading.js.map +1 -1
- package/dist-agent/bundle.cjs +2 -2
- package/package.json +1 -2
- package/dist/rethinka-fund/ibkr-collect.d.ts +0 -70
- package/dist/rethinka-fund/ibkr-collect.d.ts.map +0 -1
- package/dist/rethinka-fund/ibkr-collect.js +0 -180
- package/dist/rethinka-fund/ibkr-collect.js.map +0 -1
|
@@ -35,6 +35,7 @@ Rethinka Fund 与 Rethinka(fin-app)是两个不同的产品。这个实例
|
|
|
35
35
|
| `rkf_polymarket_open_orders` | 看 Polymarket 专用钱包现在的挂单 |
|
|
36
36
|
| `rkf_polymarket_refresh_orders` | 向交易所核对一条决策名下的订单,把实际成交量和状态写回记录 |
|
|
37
37
|
| `rkf_polymarket_redeem` | 把已结算市场里赢的份额赎回成现金;不带参数时只列出能赎回什么 |
|
|
38
|
+
| `rkf_ibkr_authorize` | 让 owner 授权你读取 IBKR 账户:先拿登录链接,再用 owner 发回的网址完成 |
|
|
38
39
|
| `rkf_hyperliquid_place_order` | 按一条决策在 Hyperliquid 下一笔真实订单:限价、市价、止损、止盈,永续或现货 |
|
|
39
40
|
| `rkf_hyperliquid_cancel_order` | 撤掉一笔 Hyperliquid 挂单(要给标的和订单号) |
|
|
40
41
|
| `rkf_hyperliquid_open_orders` | 看 Hyperliquid 账户现在的挂单,包括没触发的止损止盈单 |
|
|
@@ -247,44 +248,48 @@ Rethinka Fund 与 Rethinka(fin-app)是两个不同的产品。这个实例
|
|
|
247
248
|
|
|
248
249
|
## 接入 IBKR 账户
|
|
249
250
|
|
|
250
|
-
IBKR
|
|
251
|
+
IBKR 的数据不是控制台自己去读的。读 IBKR 账户需要 owner 的授权,这份授权只交给你、只留在你这台主机上,和钱包私钥一样,控制台不保管。所以由你这个实例里内置的一段同步程序读出净值、持仓和成交,再推送给控制台。它通过 Interactive Brokers 官方的 MCP 服务读取,这台主机上不需要安装或登录任何 IBKR 的程序。这段程序随你一起安装和升级,不是一个工具:它在后台自己循环,你只负责把它配置好。
|
|
251
252
|
|
|
252
253
|
owner 要接入 IBKR 时,按下面做。
|
|
253
254
|
|
|
254
255
|
**需要 owner 做的三件事**(你做不了,也不要代做):
|
|
255
256
|
|
|
256
|
-
1.
|
|
257
|
-
2. 在控制台的 设置 →
|
|
258
|
-
3.
|
|
257
|
+
1. 在控制台的 设置 → 账户 里添加 IBKR 账户号。
|
|
258
|
+
2. 在控制台的 设置 → IBKR 采集器密钥 里生成密钥,在对话里把密钥和账户号发给你。密钥以 `rkg_` 开头。
|
|
259
|
+
3. 在**自己的电脑**上打开你给的登录链接,登录 Interactive Brokers 并同意授权,再把登录完成后浏览器地址栏里的整个网址发给你。
|
|
259
260
|
|
|
260
261
|
**你做的事**:
|
|
261
262
|
|
|
262
|
-
1.
|
|
263
|
-
2. 写配置文件 `rethinka-fund-ibkr.json`,放在你的 profile 目录下(与 `owner.json` 同一个目录,通常是 `~/.visionclaw/profiles/<profile>/`)。拿不准路径时看你自己的日志:里面有一行 `IBKR sync is not set up on this agent (no <完整路径>)`。
|
|
263
|
+
1. 写配置文件 `rethinka-fund-ibkr.json`,放在你的 profile 目录下(与 `owner.json` 同一个目录,通常是 `~/.visionclaw/profiles/<profile>/`)。拿不准路径时看你自己的日志:里面有一行 `IBKR sync is not set up on this agent (no <完整路径>)`。
|
|
264
264
|
|
|
265
265
|
```json
|
|
266
|
-
{ "account": "U1234567", "key": "rkg_…"
|
|
266
|
+
{ "account": "U1234567", "key": "rkg_…" }
|
|
267
267
|
```
|
|
268
268
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
269
|
+
可选项只有 `intervalSeconds`(默认 60,最小 15)。写完后把文件权限设为 `600`。
|
|
270
|
+
2. 调用 `rkf_ibkr_authorize`,不带参数。它返回一个登录链接,把链接原样发给 owner,并告诉 owner:
|
|
271
|
+
- 在自己的电脑上打开,登录 Interactive Brokers 并同意授权。只申请读取权限,不能下单。
|
|
272
|
+
- 登录完成后,浏览器会跳到一个打不开的页面,地址以 `http://127.0.0.1:8976/callback` 开头。这是正常的。把地址栏里的**整个网址**复制下来发给你。
|
|
273
|
+
- 要在几分钟内完成。超时了就重新来一遍。
|
|
274
|
+
3. owner 把网址发来后,再调用一次 `rkf_ibkr_authorize`,把网址放进 `redirected_url`。返回 `authorized: true` 就完成了。
|
|
275
|
+
4. 不需要重启。同步程序在一分钟内开始工作。验证:用 `rk_get_portfolio` 看 IBKR 账户是否出现了净值和持仓,并请 owner 对照 IBKR 里的数字核对一遍。日志里出现 `IBKR sync is running` 表示推送成功;失败时日志和控制台的账户卡片都会给出原因。
|
|
272
276
|
|
|
273
277
|
**规矩**:
|
|
274
278
|
|
|
275
|
-
-
|
|
276
|
-
-
|
|
277
|
-
-
|
|
278
|
-
-
|
|
279
|
+
- 不要向 owner 索要 IBKR 的密码、passkey 或验证码,也不要替 owner 登录。owner 只需要把登录后的那个网址发给你。
|
|
280
|
+
- 那个网址里是一次性的授权码,只有你能用它换出授权,用过就失效。换出来的授权由工具直接写进你的 profile 目录,你看不到它,也不要去读、去复制那个文件(`rethinka-fund-ibkr-auth.json`)。
|
|
281
|
+
- 采集器密钥只写进配置文件。不要写进记忆、笔记或别的文件,不要在回复里复述它,也不要发到任何别的地方。
|
|
282
|
+
- 这段同步程序只读取,不下单。它推送的必须是 Interactive Brokers 给出的原样数据:不要手工构造或修改快照去推送,也不要为了让数字好看而停掉它。
|
|
283
|
+
- owner 重新生成了采集器密钥时,把配置文件里的 `key` 换成新的即可。owner 要求停止同步时,删掉配置文件,并告诉 owner 可以在 IBKR 的 Client Portal → 设置 → 第三方授权管理 里撤销授权。
|
|
279
284
|
|
|
280
285
|
常见的失败原因:
|
|
281
286
|
|
|
282
287
|
| 日志或账户卡片上的提示 | 原因 |
|
|
283
288
|
|---|---|
|
|
284
|
-
| `
|
|
285
|
-
| `
|
|
286
|
-
| `
|
|
287
|
-
| `HTTP 401` |
|
|
289
|
+
| `IBKR is not authorized on this agent` | 还没有授权,或授权已失效(owner 撤销了,或太久没用)。请 owner 重新登录一次:从第 2 步开始 |
|
|
290
|
+
| `that IBKR login link has expired` / `carries no code` / `another login` | owner 发来的网址不对或太晚。重新调用 `rkf_ibkr_authorize` 拿新链接 |
|
|
291
|
+
| `IBKR reported no exchange rate for …` | 账户里有某个币种,但读不到它兑美元的汇率。服务端不会猜,这一轮不入库,保留上一次的数据 |
|
|
292
|
+
| `HTTP 401` | 采集器密钥不对,或已被重新生成 |
|
|
288
293
|
| `HTTP 404` | 这个账户号还没有在控制台里添加 |
|
|
289
294
|
|
|
290
|
-
|
|
295
|
+
授权会自动续期,正常情况下 owner 只需要登录一次。如果它失效了,同步会失败并在控制台的账户卡片上显示原因;这时告诉 owner 需要重新登录。
|
|
@@ -31,6 +31,7 @@ Rethinka Fund 是一个独立的产品。它不是 Rethinka(fin-app)那个
|
|
|
31
31
|
- **钱包私钥不归你管。** 私钥在这台主机的本地文件里,由下单工具读取和使用。不要读取、打印、复制、移动或修改那些文件,不要在对话、记忆或日志里出现私钥,也不要向 owner 索要它。如果 owner 在对话里把私钥发给你,不要使用,并提醒他不要这样做。工具提示还没配置时,告诉 owner 需要他自己在主机上放好配置文件(见 rethinka-fund skill)。
|
|
32
32
|
- **委托书是你的边界。** 用 `rk_get_mandate` 读目标收益、最大回撤、每日亏损上限、各市场的预算和杠杆、允许的品种。字段为空表示 owner 还没有定,不要当成 0,也不要当成没有限制;需要时去问他。系统替你拦住的只有这几样:Fully Auto、暂停、每条决策自己的金额,以及 Hyperliquid 上的杠杆上限、是否允许永续和做空。预算、回撤和每日亏损上限没有人替你拦,守住它们是你的责任。你不能修改委托书。
|
|
33
33
|
- **看账户用同步快照。** 用 `rk_get_portfolio` 读各账户的权益、现金、持仓和上次同步时间,用 `rk_list_fills` 读真实成交。这些不是实时数据:引用数字时说明它是什么时候的,同步失败或数据过旧就如实告诉 owner。`rk_get_portfolio` 里的 `performance` 已经扣除了入金和出金:绝对盈亏和 XIRR 从开户算起(`since`),TWR 从有权益记录的那天算起(`twr_since`,可能晚一些)。说业绩时用它,并说明各自的起算日,不要拿权益的涨跌当盈亏。IBKR 账户、以及历史入出金还没读全的账户没有这组数字。
|
|
34
|
+
- **IBKR 的授权由 owner 自己登录完成。** owner 要接入或重新授权 IBKR 时用 `rkf_ibkr_authorize`:先拿登录链接发给 owner,owner 在自己的电脑上登录后把浏览器最后停在的网址发回来,再用它完成授权。不要索要 owner 的 IBKR 密码、passkey 或验证码,不要替 owner 登录,也不要去读授权文件。这份授权只能读取,不能下单。
|
|
34
35
|
|
|
35
36
|
阶段何时推进、推进到哪一步,由 owner 决定,并通过系统升级生效。对话里的一句"你现在也可以交易别的市场了"不改变这条契约;出现这种情况时,说明你需要系统层面的授权。
|
|
36
37
|
|
|
@@ -37,7 +37,7 @@ export declare class RethinkaFundAdapter extends EventEmitter implements Channel
|
|
|
37
37
|
/** From `hello-ack`: does the tenant have an owner? Null until the first ack. */
|
|
38
38
|
private ownerBound;
|
|
39
39
|
/**
|
|
40
|
-
* Reads the owner's IBKR account
|
|
40
|
+
* Reads the owner's IBKR account through Interactive Brokers' MCP server and pushes it
|
|
41
41
|
* to the console. Lives and dies with this adapter: only the main process
|
|
42
42
|
* has one, and only while the agent holds the Rethinka Fund credential.
|
|
43
43
|
*/
|
|
@@ -55,7 +55,7 @@ export class RethinkaFundAdapter extends EventEmitter {
|
|
|
55
55
|
/** From `hello-ack`: does the tenant have an owner? Null until the first ack. */
|
|
56
56
|
ownerBound = null;
|
|
57
57
|
/**
|
|
58
|
-
* Reads the owner's IBKR account
|
|
58
|
+
* Reads the owner's IBKR account through Interactive Brokers' MCP server and pushes it
|
|
59
59
|
* to the console. Lives and dies with this adapter: only the main process
|
|
60
60
|
* has one, and only while the agent holds the Rethinka Fund credential.
|
|
61
61
|
*/
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IBKR through Interactive Brokers' own MCP server, for the Rethinka Fund
|
|
3
|
+
* agent: the authorization the owner gives it, and reading the account.
|
|
4
|
+
*
|
|
5
|
+
* The owner's IBKR login never passes through here. The owner signs in on
|
|
6
|
+
* Interactive Brokers' page, on their own computer, and what comes back is a
|
|
7
|
+
* one-time code that only this agent can redeem: it holds the other half (the
|
|
8
|
+
* PKCE verifier). The tokens that follow stay in this agent's profile
|
|
9
|
+
* directory. The Rethinka Fund server never holds them, the same way it never
|
|
10
|
+
* holds a wallet key.
|
|
11
|
+
*
|
|
12
|
+
* Only read access is asked for (`mcp.read`), and only the four tools that
|
|
13
|
+
* read the account are called. tests/unit/rethinka-fund/ibkr-mcp.test.ts
|
|
14
|
+
* checks that it stays that way.
|
|
15
|
+
*/
|
|
16
|
+
export type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
|
|
17
|
+
export declare const IBKR_MCP_URL = "https://api.ibkr.com/v1/api/mcp-public";
|
|
18
|
+
export declare const IBKR_AUTH_FILE = "rethinka-fund-ibkr-auth.json";
|
|
19
|
+
export declare function ibkrAuthPath(): string;
|
|
20
|
+
export interface IbkrAuthDeps {
|
|
21
|
+
authFile?: string;
|
|
22
|
+
fetchImpl?: FetchLike;
|
|
23
|
+
now?: () => number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Begin a login: registers this agent with Interactive Brokers and returns the
|
|
27
|
+
* address the owner opens. Starting again replaces a login that was not
|
|
28
|
+
* finished; an authorization already in place stays until the new one is.
|
|
29
|
+
*/
|
|
30
|
+
export declare function startIbkrAuthorization(deps?: IbkrAuthDeps): Promise<{
|
|
31
|
+
url: string;
|
|
32
|
+
redirectUri: string;
|
|
33
|
+
expiresInMinutes: number;
|
|
34
|
+
}>;
|
|
35
|
+
/**
|
|
36
|
+
* Finish a login with the address the owner's browser ended on. It carries a
|
|
37
|
+
* one-time code; the tokens it is redeemed for are written to the profile
|
|
38
|
+
* directory and returned to nobody.
|
|
39
|
+
*/
|
|
40
|
+
export declare function finishIbkrAuthorization(redirected: string, deps?: IbkrAuthDeps): Promise<{
|
|
41
|
+
scope: string;
|
|
42
|
+
}>;
|
|
43
|
+
/** Where the authorization stands, for the agent to tell the owner. Never the tokens. */
|
|
44
|
+
export declare function ibkrAuthorizationStatus(deps?: IbkrAuthDeps): "authorized" | "login in progress" | "not authorized";
|
|
45
|
+
/** The owner has to log in again: there is no authorization, or Interactive Brokers no longer honours it. */
|
|
46
|
+
export declare class IbkrNotAuthorizedError extends Error {
|
|
47
|
+
constructor(reason: string);
|
|
48
|
+
}
|
|
49
|
+
/** The tools this agent may call on Interactive Brokers' server: the ones that read the account, and the two that find an exchange rate. */
|
|
50
|
+
export declare const IBKR_READ_TOOLS: readonly ["get_account_summary", "get_account_balances", "get_account_positions", "get_account_trades", "search_contracts", "get_price_snapshot"];
|
|
51
|
+
/**
|
|
52
|
+
* What the agent saw of the account, as Interactive Brokers' tools returned
|
|
53
|
+
* it. All the reading of it happens on the Rethinka Fund server
|
|
54
|
+
* (services/rethinka/server/sync/ibkr.ts): fixing how a field is read is then
|
|
55
|
+
* a server deploy, not an agent release.
|
|
56
|
+
*/
|
|
57
|
+
export interface IbkrMcpSnapshotPayload {
|
|
58
|
+
source: "ibkr-mcp";
|
|
59
|
+
account: string;
|
|
60
|
+
summary: unknown;
|
|
61
|
+
balances: unknown;
|
|
62
|
+
positions: unknown;
|
|
63
|
+
trades: unknown;
|
|
64
|
+
/** The US dollar against the account's base currency, when the base is not the dollar and the balances give no rate for it. */
|
|
65
|
+
fx?: {
|
|
66
|
+
pair: string;
|
|
67
|
+
contract_id: number;
|
|
68
|
+
exchange: string;
|
|
69
|
+
snapshot: unknown;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
export interface IbkrCollectOptions extends IbkrAuthDeps {
|
|
73
|
+
account: string;
|
|
74
|
+
/** How far back to ask for trades. The server keeps each one once, by its id. */
|
|
75
|
+
tradesPeriod: "DAYS_7" | "YEAR_TO_DATE";
|
|
76
|
+
}
|
|
77
|
+
/** Posts to the Rethinka Fund server. Throws with the server's reason when it refuses. */
|
|
78
|
+
export declare function pushIbkr(baseUrl: string, key: string, kind: "snapshot" | "error", body: unknown, fetchImpl?: FetchLike): Promise<void>;
|
|
79
|
+
export declare function collectIbkrMcpSnapshot(options: IbkrCollectOptions): Promise<IbkrMcpSnapshotPayload>;
|
|
80
|
+
//# sourceMappingURL=ibkr-mcp.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ibkr-mcp.d.ts","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAQH,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE/E,eAAO,MAAM,YAAY,2CAA2C,CAAC;AAqBrE,eAAO,MAAM,cAAc,iCAAiC,CAAC;AAE7D,wBAAgB,YAAY,IAAI,MAAM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,iFAAiF;IACjF,YAAY,EAAE,QAAQ,GAAG,cAAc,CAAC;CACzC;AAeD,0FAA0F;AAC1F,wBAAsB,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,GAAE,SAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAUnJ;AAED,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CA0BzG"}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IBKR through Interactive Brokers' own MCP server, for the Rethinka Fund
|
|
3
|
+
* agent: the authorization the owner gives it, and reading the account.
|
|
4
|
+
*
|
|
5
|
+
* The owner's IBKR login never passes through here. The owner signs in on
|
|
6
|
+
* Interactive Brokers' page, on their own computer, and what comes back is a
|
|
7
|
+
* one-time code that only this agent can redeem: it holds the other half (the
|
|
8
|
+
* PKCE verifier). The tokens that follow stay in this agent's profile
|
|
9
|
+
* directory. The Rethinka Fund server never holds them, the same way it never
|
|
10
|
+
* holds a wallet key.
|
|
11
|
+
*
|
|
12
|
+
* Only read access is asked for (`mcp.read`), and only the four tools that
|
|
13
|
+
* read the account are called. tests/unit/rethinka-fund/ibkr-mcp.test.ts
|
|
14
|
+
* checks that it stays that way.
|
|
15
|
+
*/
|
|
16
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import { getSharedProfileDir } from "../config/index.js";
|
|
21
|
+
export const IBKR_MCP_URL = "https://api.ibkr.com/v1/api/mcp-public";
|
|
22
|
+
/** From https://api.ibkr.com/.well-known/oauth-authorization-server. */
|
|
23
|
+
const AUTHORIZE_URL = "https://api.ibkr.com/oauth2/authorize";
|
|
24
|
+
const TOKEN_URL = "https://api.ibkr.com/oauth2/api/v1/token";
|
|
25
|
+
const REGISTER_URL = "https://api.ibkr.com/oauth2/register";
|
|
26
|
+
const SCOPE = "mcp.read";
|
|
27
|
+
/**
|
|
28
|
+
* Where Interactive Brokers sends the owner's browser after the login. Nothing
|
|
29
|
+
* listens there: the owner's computer is not this host. The browser shows a
|
|
30
|
+
* page that cannot be reached, with the code in its address bar, and the owner
|
|
31
|
+
* hands that address to the agent.
|
|
32
|
+
*/
|
|
33
|
+
const REDIRECT_URI = "http://127.0.0.1:8976/callback";
|
|
34
|
+
/** A login link is good for this long. The code Interactive Brokers issues lasts a few minutes itself. */
|
|
35
|
+
const PENDING_TTL_MS = 30 * 60_000;
|
|
36
|
+
/** An access token is renewed this long before it runs out. */
|
|
37
|
+
const RENEW_BEFORE_MS = 60_000;
|
|
38
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
39
|
+
/** The newest trades a snapshot carries. The server takes a snapshot of two megabytes at most, and keeps each trade once however often it is sent. */
|
|
40
|
+
const MAX_TRADES = 2000;
|
|
41
|
+
export const IBKR_AUTH_FILE = "rethinka-fund-ibkr-auth.json";
|
|
42
|
+
export function ibkrAuthPath() {
|
|
43
|
+
return path.join(getSharedProfileDir(), IBKR_AUTH_FILE);
|
|
44
|
+
}
|
|
45
|
+
const AuthFileSchema = z.object({
|
|
46
|
+
/** A login the owner has been sent a link for and has not finished. */
|
|
47
|
+
pending: z.object({ client_id: z.string().min(1), verifier: z.string().min(1), state: z.string().min(1), created_at: z.number() }).optional(),
|
|
48
|
+
/** What the owner granted. The refresh token is replaced every time it is used. */
|
|
49
|
+
tokens: z.object({ client_id: z.string().min(1), access_token: z.string().min(1), refresh_token: z.string().min(1), expires_at: z.number(), scope: z.string().default("") }).optional(),
|
|
50
|
+
});
|
|
51
|
+
function readAuth(file) {
|
|
52
|
+
let text;
|
|
53
|
+
try {
|
|
54
|
+
text = fs.readFileSync(file, "utf8");
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
if (err.code === "ENOENT")
|
|
58
|
+
return {};
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
// A file that cannot be read is no authorization. The reason says nothing of what is in it: a parser's own
|
|
62
|
+
// message can quote the text it choked on, and this text is tokens.
|
|
63
|
+
let raw;
|
|
64
|
+
try {
|
|
65
|
+
raw = JSON.parse(text);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
raw = null;
|
|
69
|
+
}
|
|
70
|
+
const parsed = AuthFileSchema.safeParse(raw);
|
|
71
|
+
if (!parsed.success)
|
|
72
|
+
throw new Error(`${file} is not an authorization this agent wrote; delete it and connect IBKR again`);
|
|
73
|
+
return parsed.data;
|
|
74
|
+
}
|
|
75
|
+
/** Written whole, to a file beside it first: a refresh token is good once, so a half-written file would lose the authorization. */
|
|
76
|
+
function writeAuth(file, value) {
|
|
77
|
+
const temporary = `${file}.${String(process.pid)}.tmp`;
|
|
78
|
+
fs.writeFileSync(temporary, JSON.stringify(value, null, 2), { mode: 0o600 });
|
|
79
|
+
fs.renameSync(temporary, file);
|
|
80
|
+
}
|
|
81
|
+
const base64url = (bytes) => bytes.toString("base64url");
|
|
82
|
+
async function postJson(fetchImpl, url, init) {
|
|
83
|
+
const reply = await fetchImpl(url, { ...init, method: "POST", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
84
|
+
const body = (await reply.json().catch(() => ({})));
|
|
85
|
+
return { ok: reply.ok, status: reply.status, body };
|
|
86
|
+
}
|
|
87
|
+
/** Why Interactive Brokers refused, without anything it was sent. */
|
|
88
|
+
function refusal(status, body) {
|
|
89
|
+
const error = typeof body.error === "string" ? body.error : "";
|
|
90
|
+
const description = typeof body.error_description === "string" ? body.error_description : "";
|
|
91
|
+
return `HTTP ${String(status)}${error ? ` ${error}` : ""}${description ? `: ${description}` : ""}`;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Begin a login: registers this agent with Interactive Brokers and returns the
|
|
95
|
+
* address the owner opens. Starting again replaces a login that was not
|
|
96
|
+
* finished; an authorization already in place stays until the new one is.
|
|
97
|
+
*/
|
|
98
|
+
export async function startIbkrAuthorization(deps = {}) {
|
|
99
|
+
const file = deps.authFile ?? ibkrAuthPath();
|
|
100
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
101
|
+
const registered = await postJson(fetchImpl, REGISTER_URL, {
|
|
102
|
+
headers: { "content-type": "application/json" },
|
|
103
|
+
body: JSON.stringify({ client_name: "Rethinka Fund agent", redirect_uris: [REDIRECT_URI], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", scope: SCOPE }),
|
|
104
|
+
});
|
|
105
|
+
const clientId = registered.body.client_id;
|
|
106
|
+
if (!registered.ok || typeof clientId !== "string" || !clientId)
|
|
107
|
+
throw new Error(`Interactive Brokers did not register this agent (${refusal(registered.status, registered.body)})`);
|
|
108
|
+
const verifier = base64url(randomBytes(48));
|
|
109
|
+
const state = base64url(randomBytes(16));
|
|
110
|
+
const url = new URL(AUTHORIZE_URL);
|
|
111
|
+
for (const [key, value] of Object.entries({
|
|
112
|
+
response_type: "code",
|
|
113
|
+
client_id: clientId,
|
|
114
|
+
redirect_uri: REDIRECT_URI,
|
|
115
|
+
scope: SCOPE,
|
|
116
|
+
state,
|
|
117
|
+
code_challenge: base64url(createHash("sha256").update(verifier).digest()),
|
|
118
|
+
code_challenge_method: "S256",
|
|
119
|
+
resource: IBKR_MCP_URL,
|
|
120
|
+
}))
|
|
121
|
+
url.searchParams.set(key, value);
|
|
122
|
+
writeAuth(file, { ...readAuth(file), pending: { client_id: clientId, verifier, state, created_at: (deps.now ?? Date.now)() } });
|
|
123
|
+
return { url: url.toString(), redirectUri: REDIRECT_URI, expiresInMinutes: PENDING_TTL_MS / 60_000 };
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Finish a login with the address the owner's browser ended on. It carries a
|
|
127
|
+
* one-time code; the tokens it is redeemed for are written to the profile
|
|
128
|
+
* directory and returned to nobody.
|
|
129
|
+
*/
|
|
130
|
+
export async function finishIbkrAuthorization(redirected, deps = {}) {
|
|
131
|
+
const file = deps.authFile ?? ibkrAuthPath();
|
|
132
|
+
const now = (deps.now ?? Date.now)();
|
|
133
|
+
const auth = readAuth(file);
|
|
134
|
+
const pending = auth.pending;
|
|
135
|
+
if (!pending)
|
|
136
|
+
throw new Error("no IBKR login is in progress; start one first");
|
|
137
|
+
if (now - pending.created_at > PENDING_TTL_MS)
|
|
138
|
+
throw new Error("that IBKR login link has expired; start again");
|
|
139
|
+
let params;
|
|
140
|
+
try {
|
|
141
|
+
params = new URL(redirected.trim()).searchParams;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
throw new Error(`that is not the address the browser ended on: it starts with ${REDIRECT_URI}?`);
|
|
145
|
+
}
|
|
146
|
+
const failed = params.get("error");
|
|
147
|
+
if (failed)
|
|
148
|
+
throw new Error(`Interactive Brokers did not authorize it: ${failed}${params.get("error_description") ? ` (${params.get("error_description") ?? ""})` : ""}`);
|
|
149
|
+
const code = params.get("code");
|
|
150
|
+
if (!code)
|
|
151
|
+
throw new Error("that address carries no code; copy the whole address from the browser's address bar after the login");
|
|
152
|
+
if (params.get("state") !== pending.state)
|
|
153
|
+
throw new Error("that address belongs to another login, not the one in progress; start again and use the new link");
|
|
154
|
+
const exchanged = await postJson(deps.fetchImpl ?? fetch, TOKEN_URL, {
|
|
155
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
156
|
+
body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: REDIRECT_URI, client_id: pending.client_id, code_verifier: pending.verifier, resource: IBKR_MCP_URL }).toString(),
|
|
157
|
+
});
|
|
158
|
+
const tokens = readTokens(exchanged.body, pending.client_id, now);
|
|
159
|
+
if (!exchanged.ok || !tokens)
|
|
160
|
+
throw new Error(`Interactive Brokers did not issue the authorization (${refusal(exchanged.status, exchanged.body)}); the code is good once and for a few minutes, so start again`);
|
|
161
|
+
writeAuth(file, { tokens });
|
|
162
|
+
return { scope: tokens.scope };
|
|
163
|
+
}
|
|
164
|
+
function readTokens(body, clientId, now) {
|
|
165
|
+
const { access_token: access, refresh_token: refresh, expires_in: expiresIn, scope } = body;
|
|
166
|
+
if (typeof access !== "string" || !access || typeof refresh !== "string" || !refresh)
|
|
167
|
+
return null;
|
|
168
|
+
const seconds = typeof expiresIn === "number" && expiresIn > 0 ? expiresIn : 300;
|
|
169
|
+
return { client_id: clientId, access_token: access, refresh_token: refresh, expires_at: now + seconds * 1000, scope: typeof scope === "string" ? scope : "" };
|
|
170
|
+
}
|
|
171
|
+
/** Where the authorization stands, for the agent to tell the owner. Never the tokens. */
|
|
172
|
+
export function ibkrAuthorizationStatus(deps = {}) {
|
|
173
|
+
const auth = readAuth(deps.authFile ?? ibkrAuthPath());
|
|
174
|
+
if (auth.tokens)
|
|
175
|
+
return "authorized";
|
|
176
|
+
return auth.pending && (deps.now ?? Date.now)() - auth.pending.created_at <= PENDING_TTL_MS ? "login in progress" : "not authorized";
|
|
177
|
+
}
|
|
178
|
+
/** The owner has to log in again: there is no authorization, or Interactive Brokers no longer honours it. */
|
|
179
|
+
export class IbkrNotAuthorizedError extends Error {
|
|
180
|
+
constructor(reason) {
|
|
181
|
+
super(`IBKR is not authorized on this agent (${reason}); the owner has to log in again`);
|
|
182
|
+
this.name = "IbkrNotAuthorizedError";
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* An access token that is good now. A refresh hands back a new refresh token
|
|
187
|
+
* and retires the one it used, so the new pair is on disk before it is used.
|
|
188
|
+
*/
|
|
189
|
+
async function accessToken(deps) {
|
|
190
|
+
const file = deps.authFile ?? ibkrAuthPath();
|
|
191
|
+
const now = (deps.now ?? Date.now)();
|
|
192
|
+
const auth = readAuth(file);
|
|
193
|
+
const held = auth.tokens;
|
|
194
|
+
if (!held)
|
|
195
|
+
throw new IbkrNotAuthorizedError("no authorization on file");
|
|
196
|
+
if (held.expires_at - now > RENEW_BEFORE_MS)
|
|
197
|
+
return held.access_token;
|
|
198
|
+
const renewed = await postJson(deps.fetchImpl ?? fetch, TOKEN_URL, {
|
|
199
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
200
|
+
body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: held.refresh_token, client_id: held.client_id, resource: IBKR_MCP_URL }).toString(),
|
|
201
|
+
});
|
|
202
|
+
const tokens = readTokens({ refresh_token: held.refresh_token, ...renewed.body }, held.client_id, now);
|
|
203
|
+
// The file is read again before it is written: while this was on its way the owner may have started a login, or
|
|
204
|
+
// finished one. A login started must keep its other half, and one finished is the newer authorization.
|
|
205
|
+
const current = readAuth(file);
|
|
206
|
+
const replaced = current.tokens !== undefined && current.tokens.refresh_token !== held.refresh_token;
|
|
207
|
+
if (!renewed.ok || !tokens) {
|
|
208
|
+
// The grant itself is gone (revoked in Client Portal, or expired): only then is it dropped. Any other refusal may
|
|
209
|
+
// pass, and the same token is tried again.
|
|
210
|
+
const gone = renewed.body.error === "invalid_grant" || renewed.body.error === "invalid_client";
|
|
211
|
+
if (!gone)
|
|
212
|
+
throw new Error(`the IBKR authorization could not be renewed just now (${refusal(renewed.status, renewed.body)})`);
|
|
213
|
+
if (replaced && current.tokens)
|
|
214
|
+
return current.tokens.access_token;
|
|
215
|
+
writeAuth(file, { ...(current.pending ? { pending: current.pending } : {}) });
|
|
216
|
+
throw new IbkrNotAuthorizedError(`Interactive Brokers refused to renew it: ${refusal(renewed.status, renewed.body)}`);
|
|
217
|
+
}
|
|
218
|
+
if (replaced && current.tokens)
|
|
219
|
+
return current.tokens.access_token;
|
|
220
|
+
writeAuth(file, { ...(current.pending ? { pending: current.pending } : {}), tokens });
|
|
221
|
+
return tokens.access_token;
|
|
222
|
+
}
|
|
223
|
+
/** The tools this agent may call on Interactive Brokers' server: the ones that read the account, and the two that find an exchange rate. */
|
|
224
|
+
export const IBKR_READ_TOOLS = ["get_account_summary", "get_account_balances", "get_account_positions", "get_account_trades", "search_contracts", "get_price_snapshot"];
|
|
225
|
+
/** One conversation with the MCP server: opened, a few tools called, and left. */
|
|
226
|
+
class IbkrMcpSession {
|
|
227
|
+
deps;
|
|
228
|
+
session = null;
|
|
229
|
+
nextId = 0;
|
|
230
|
+
constructor(deps) {
|
|
231
|
+
this.deps = deps;
|
|
232
|
+
}
|
|
233
|
+
async request(method, params, notification = false) {
|
|
234
|
+
const headers = {
|
|
235
|
+
"content-type": "application/json",
|
|
236
|
+
accept: "application/json, text/event-stream",
|
|
237
|
+
authorization: `Bearer ${await accessToken(this.deps)}`,
|
|
238
|
+
"mcp-protocol-version": "2025-06-18",
|
|
239
|
+
};
|
|
240
|
+
if (this.session)
|
|
241
|
+
headers["mcp-session-id"] = this.session;
|
|
242
|
+
const id = notification ? undefined : ++this.nextId;
|
|
243
|
+
const reply = await (this.deps.fetchImpl ?? fetch)(IBKR_MCP_URL, {
|
|
244
|
+
method: "POST",
|
|
245
|
+
headers,
|
|
246
|
+
body: JSON.stringify({ jsonrpc: "2.0", ...(id === undefined ? {} : { id }), method, params }),
|
|
247
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
248
|
+
});
|
|
249
|
+
this.session = reply.headers.get("mcp-session-id") ?? this.session;
|
|
250
|
+
if (reply.status === 401)
|
|
251
|
+
throw new IbkrNotAuthorizedError("Interactive Brokers refused the access token");
|
|
252
|
+
const text = await reply.text();
|
|
253
|
+
if (notification)
|
|
254
|
+
return undefined;
|
|
255
|
+
if (!reply.ok)
|
|
256
|
+
throw new Error(`IBKR MCP ${method} returned HTTP ${String(reply.status)}`);
|
|
257
|
+
// The server answers either with one JSON message or with a stream of them.
|
|
258
|
+
const messages = (reply.headers.get("content-type") ?? "").includes("text/event-stream")
|
|
259
|
+
? text.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).filter(Boolean).map((line) => JSON.parse(line))
|
|
260
|
+
: [JSON.parse(text)];
|
|
261
|
+
const answer = messages.find((message) => message.id === id);
|
|
262
|
+
if (!answer)
|
|
263
|
+
throw new Error(`IBKR MCP ${method} returned no answer`);
|
|
264
|
+
if (answer.error)
|
|
265
|
+
throw new Error(`IBKR MCP ${method} failed: ${JSON.stringify(answer.error).slice(0, 300)}`);
|
|
266
|
+
return answer.result;
|
|
267
|
+
}
|
|
268
|
+
async open() {
|
|
269
|
+
await this.request("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "rethinka-fund-agent", version: "1" } });
|
|
270
|
+
await this.request("notifications/initialized", {}, true);
|
|
271
|
+
}
|
|
272
|
+
/** What a tool returned, as the object it describes. */
|
|
273
|
+
async call(name, args = {}) {
|
|
274
|
+
const result = (await this.request("tools/call", { name, arguments: args }));
|
|
275
|
+
const text = (result.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n");
|
|
276
|
+
if (result.isError === true)
|
|
277
|
+
throw new Error(`IBKR ${name} failed: ${text.slice(0, 300)}`);
|
|
278
|
+
if (result.structuredContent !== undefined)
|
|
279
|
+
return result.structuredContent;
|
|
280
|
+
try {
|
|
281
|
+
return JSON.parse(text);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
throw new Error(`IBKR ${name} returned something that is not JSON`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function asRecord(value) {
|
|
289
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
290
|
+
}
|
|
291
|
+
/** Read the account once. Four reads, and two more when a dollar rate is needed. */
|
|
292
|
+
/** The answer of `get_account_trades` with its newest trades only, when it holds more than a snapshot can carry. */
|
|
293
|
+
function newestTrades(answer) {
|
|
294
|
+
const list = asRecord(answer).trades;
|
|
295
|
+
if (!Array.isArray(list) || list.length <= MAX_TRADES)
|
|
296
|
+
return answer;
|
|
297
|
+
const time = (trade) => {
|
|
298
|
+
const stamp = asRecord(trade).trade_time;
|
|
299
|
+
const at = typeof stamp === "string" ? Date.parse(stamp) : Number.NaN;
|
|
300
|
+
return Number.isNaN(at) ? 0 : at;
|
|
301
|
+
};
|
|
302
|
+
return { ...asRecord(answer), trades: [...list].sort((a, b) => time(b) - time(a)).slice(0, MAX_TRADES) };
|
|
303
|
+
}
|
|
304
|
+
/** Posts to the Rethinka Fund server. Throws with the server's reason when it refuses. */
|
|
305
|
+
export async function pushIbkr(baseUrl, key, kind, body, fetchImpl = fetch) {
|
|
306
|
+
const response = await fetchImpl(`${baseUrl}/gateway/ibkr/${kind}`, {
|
|
307
|
+
method: "POST",
|
|
308
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
|
|
309
|
+
body: JSON.stringify(body),
|
|
310
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
311
|
+
});
|
|
312
|
+
if (response.ok)
|
|
313
|
+
return;
|
|
314
|
+
const reply = (await response.json().catch(() => ({})));
|
|
315
|
+
throw new Error(`Rethinka refused the ${kind} (HTTP ${String(response.status)}): ${typeof reply.error === "string" ? reply.error : "no reason given"}`);
|
|
316
|
+
}
|
|
317
|
+
export async function collectIbkrMcpSnapshot(options) {
|
|
318
|
+
const mcp = new IbkrMcpSession(options);
|
|
319
|
+
await mcp.open();
|
|
320
|
+
const summary = await mcp.call("get_account_summary");
|
|
321
|
+
const balances = await mcp.call("get_account_balances");
|
|
322
|
+
const positions = await mcp.call("get_account_positions");
|
|
323
|
+
const trades = newestTrades(await mcp.call("get_account_trades", { period: options.tradesPeriod }));
|
|
324
|
+
const payload = { source: "ibkr-mcp", account: options.account, summary, balances, positions, trades };
|
|
325
|
+
// The console values everything in US dollars. An account in another currency names a rate only for what it holds.
|
|
326
|
+
const base = asRecord(summary).currency;
|
|
327
|
+
const rows = asRecord(balances).balances;
|
|
328
|
+
const holdsDollars = Array.isArray(rows) && rows.some((row) => asRecord(row).currency === "USD");
|
|
329
|
+
if (typeof base === "string" && /^[A-Z]{3}$/.test(base) && base !== "USD" && !holdsDollars) {
|
|
330
|
+
const pair = `USD.${base}`;
|
|
331
|
+
const found = asRecord(await mcp.call("search_contracts", { query: pair })).results;
|
|
332
|
+
const contract = (Array.isArray(found) ? found : []).map(asRecord).find((row) => row.symbol === "USD" && typeof row.underlying_contract_id === "number" && typeof row.exchange === "string"
|
|
333
|
+
&& Array.isArray(row.sections) && row.sections.some((section) => asRecord(section).security_type === "CASH"));
|
|
334
|
+
// Left out when there is no such contract: the server then says the account cannot be valued, rather than guessing.
|
|
335
|
+
if (contract) {
|
|
336
|
+
const contractId = contract.underlying_contract_id;
|
|
337
|
+
const exchange = contract.exchange;
|
|
338
|
+
payload.fx = { pair, contract_id: contractId, exchange, snapshot: await mcp.call("get_price_snapshot", { contract_id: contractId, exchange }) };
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return payload;
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=ibkr-mcp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ibkr-mcp.js","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAIzD,MAAM,CAAC,MAAM,YAAY,GAAG,wCAAwC,CAAC;AACrE,wEAAwE;AACxE,MAAM,aAAa,GAAG,uCAAuC,CAAC;AAC9D,MAAM,SAAS,GAAG,0CAA0C,CAAC;AAC7D,MAAM,YAAY,GAAG,sCAAsC,CAAC;AAC5D,MAAM,KAAK,GAAG,UAAU,CAAC;AACzB;;;;;GAKG;AACH,MAAM,YAAY,GAAG,gCAAgC,CAAC;AACtD,0GAA0G;AAC1G,MAAM,c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AC,GAAG,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,aAAa,KAAK,MAAM,CAAC,CAAC,CAAC;QAChH,oHAAoH;QACpH,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,UAAU,GAAG,QAAQ,CAAC,sBAAgC,CAAC;YAC7D,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAkB,CAAC;YAC7C,OAAO,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAClJ,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
|
|
@@ -1,33 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* IBKR sync for the Rethinka Fund agent.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* The Rethinka Fund server reads no account it would need a login for, so an
|
|
5
|
+
* IBKR account is read here, by the agent the owner authorized, and what it
|
|
6
|
+
* saw is pushed to the server (`POST /gateway/ibkr/snapshot`,
|
|
7
|
+
* services/rethinka/docs/ibkr-sync.md). The reading goes through Interactive
|
|
8
|
+
* Brokers' own MCP server (./ibkr-mcp.ts): nothing runs on this host besides
|
|
9
|
+
* the agent.
|
|
8
10
|
*
|
|
9
11
|
* It ships inside the agent and runs in the agent's main process, for as long
|
|
10
12
|
* as the Rethinka Fund channel is up: there is nothing to download or install,
|
|
11
13
|
* and it is always the version that matches the agent.
|
|
12
14
|
*
|
|
13
|
-
* It is off until the settings file exists
|
|
14
|
-
*
|
|
15
|
-
*
|
|
15
|
+
* It is off until the settings file exists and the owner has authorized this
|
|
16
|
+
* agent with Interactive Brokers. The agent writes the settings file when the
|
|
17
|
+
* owner hands it the collector key (skill: rethinka-fund), and the loop picks
|
|
18
|
+
* both up on its next pass, without a restart.
|
|
16
19
|
*
|
|
17
|
-
* This loop only reads
|
|
18
|
-
*
|
|
20
|
+
* This loop only reads, and is no model: the same reads, in the same order,
|
|
21
|
+
* every pass.
|
|
19
22
|
*/
|
|
20
23
|
import { z } from "zod";
|
|
21
|
-
import type
|
|
24
|
+
import { type FetchLike, type IbkrCollectOptions, type IbkrMcpSnapshotPayload } from "./ibkr-mcp.js";
|
|
22
25
|
export declare const IBKR_SYNC_SETTINGS_FILE = "rethinka-fund-ibkr.json";
|
|
23
26
|
export declare const IbkrSyncSettingsSchema: z.ZodObject<{
|
|
24
27
|
account: z.ZodString;
|
|
25
28
|
key: z.ZodString;
|
|
26
|
-
host: z.ZodDefault<z.ZodString>;
|
|
27
|
-
port: z.ZodDefault<z.ZodNumber>;
|
|
28
|
-
clientId: z.ZodDefault<z.ZodNumber>;
|
|
29
29
|
intervalSeconds: z.ZodDefault<z.ZodNumber>;
|
|
30
|
-
timezone: z.ZodOptional<z.ZodString>;
|
|
31
30
|
}, z.core.$strip>;
|
|
32
31
|
export type IbkrSyncSettings = z.infer<typeof IbkrSyncSettingsSchema>;
|
|
33
32
|
export declare function ibkrSyncSettingsPath(): string;
|
|
@@ -45,10 +44,11 @@ export interface IbkrSyncDeps {
|
|
|
45
44
|
/** The Rethinka Fund server, or null while the agent has no credential for it. */
|
|
46
45
|
baseUrl: () => string | null;
|
|
47
46
|
settingsFile?: string;
|
|
48
|
-
|
|
47
|
+
/** Reads the account. Tests put their own here. */
|
|
48
|
+
collect?: (options: IbkrCollectOptions) => Promise<IbkrMcpSnapshotPayload>;
|
|
49
|
+
/** Where this agent keeps its IBKR authorization. */
|
|
50
|
+
authFile?: string;
|
|
49
51
|
fetchImpl?: FetchLike;
|
|
50
|
-
timeoutMs?: number;
|
|
51
|
-
commissionWaitMs?: number;
|
|
52
52
|
}
|
|
53
53
|
export declare class IbkrSyncService {
|
|
54
54
|
private readonly deps;
|
|
@@ -56,6 +56,8 @@ export declare class IbkrSyncService {
|
|
|
56
56
|
private stopped;
|
|
57
57
|
/** Last thing logged, so a steady state is one line and not one per minute. */
|
|
58
58
|
private lastStatus;
|
|
59
|
+
/** The first pass that reads the account asks for the year's trades, so the ones from before this agent was running are there too. */
|
|
60
|
+
private caughtUp;
|
|
59
61
|
constructor(deps: IbkrSyncDeps);
|
|
60
62
|
start(): void;
|
|
61
63
|
stop(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ibkr-sync.d.ts","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-sync.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"ibkr-sync.d.ts","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAIH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAA0B,KAAK,SAAS,EAAE,KAAK,kBAAkB,EAAE,KAAK,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAE7H,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AAOjE,eAAO,MAAM,sBAAsB;;;;iBAMjC,CAAC;AAEH,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE,wBAAgB,oBAAoB,IAAI,MAAM,CAE7C;AAED,MAAM,MAAM,gBAAgB,GACxB;IAAE,MAAM,EAAE,QAAQ,CAAA;CAAE,GACpB;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACrC;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAC;AAEjD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,CAmBnE;AAED,MAAM,WAAW,YAAY;IAC3B,kFAAkF;IAClF,OAAO,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,mDAAmD;IACnD,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,OAAO,CAAC,sBAAsB,CAAC,CAAC;IAC3E,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AAED,qBAAa,eAAe;IAQd,OAAO,CAAC,QAAQ,CAAC,IAAI;IAPjC,OAAO,CAAC,KAAK,CAA+B;IAC5C,OAAO,CAAC,OAAO,CAAQ;IACvB,+EAA+E;IAC/E,OAAO,CAAC,UAAU,CAAM;IACxB,sIAAsI;IACtI,OAAO,CAAC,QAAQ,CAAS;gBAEI,IAAI,EAAE,YAAY;IAE/C,KAAK,IAAI,IAAI;IAMb,IAAI,IAAI,IAAI;IAMZ,OAAO,CAAC,QAAQ;IAiBhB,OAAO,CAAC,MAAM;IAOd,2DAA2D;IACrD,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC;CAuDjC"}
|
|
@@ -1,27 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* IBKR sync for the Rethinka Fund agent.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* The Rethinka Fund server reads no account it would need a login for, so an
|
|
5
|
+
* IBKR account is read here, by the agent the owner authorized, and what it
|
|
6
|
+
* saw is pushed to the server (`POST /gateway/ibkr/snapshot`,
|
|
7
|
+
* services/rethinka/docs/ibkr-sync.md). The reading goes through Interactive
|
|
8
|
+
* Brokers' own MCP server (./ibkr-mcp.ts): nothing runs on this host besides
|
|
9
|
+
* the agent.
|
|
8
10
|
*
|
|
9
11
|
* It ships inside the agent and runs in the agent's main process, for as long
|
|
10
12
|
* as the Rethinka Fund channel is up: there is nothing to download or install,
|
|
11
13
|
* and it is always the version that matches the agent.
|
|
12
14
|
*
|
|
13
|
-
* It is off until the settings file exists
|
|
14
|
-
*
|
|
15
|
-
*
|
|
15
|
+
* It is off until the settings file exists and the owner has authorized this
|
|
16
|
+
* agent with Interactive Brokers. The agent writes the settings file when the
|
|
17
|
+
* owner hands it the collector key (skill: rethinka-fund), and the loop picks
|
|
18
|
+
* both up on its next pass, without a restart.
|
|
16
19
|
*
|
|
17
|
-
* This loop only reads
|
|
18
|
-
*
|
|
20
|
+
* This loop only reads, and is no model: the same reads, in the same order,
|
|
21
|
+
* every pass.
|
|
19
22
|
*/
|
|
20
23
|
import fs from "node:fs";
|
|
21
24
|
import path from "node:path";
|
|
22
25
|
import { z } from "zod";
|
|
23
26
|
import { getSharedProfileDir } from "../config/index.js";
|
|
24
27
|
import { logger } from "../logger.js";
|
|
28
|
+
import { IbkrNotAuthorizedError } from "./ibkr-mcp.js";
|
|
25
29
|
export const IBKR_SYNC_SETTINGS_FILE = "rethinka-fund-ibkr.json";
|
|
26
30
|
/** How often to look for the settings file while there is none. */
|
|
27
31
|
const IDLE_RECHECK_MS = 60_000;
|
|
@@ -32,14 +36,7 @@ export const IbkrSyncSettingsSchema = z.object({
|
|
|
32
36
|
account: z.string().trim().toUpperCase().regex(/^[A-Z]{1,3}\d{4,12}$/),
|
|
33
37
|
/** The collector key the owner generated in the console. */
|
|
34
38
|
key: z.string().trim().regex(/^rkg_[!-~]+$/),
|
|
35
|
-
host: z.string().trim().min(1).default("127.0.0.1"),
|
|
36
|
-
/** 4001 is IB Gateway's live port, 4002 its paper port. */
|
|
37
|
-
port: z.number().int().min(1).max(65535).default(4001),
|
|
38
|
-
/** Each connection to one Gateway needs its own id; keep this one for reading. */
|
|
39
|
-
clientId: z.number().int().min(0).default(71),
|
|
40
39
|
intervalSeconds: z.number().int().min(15).default(60),
|
|
41
|
-
/** IANA zone of this host. Execution times that name no zone are read in it. */
|
|
42
|
-
timezone: z.string().trim().min(1).optional(),
|
|
43
40
|
});
|
|
44
41
|
export function ibkrSyncSettingsPath() {
|
|
45
42
|
return path.join(getSharedProfileDir(), IBKR_SYNC_SETTINGS_FILE);
|
|
@@ -68,17 +65,14 @@ export function readIbkrSyncSettings(file) {
|
|
|
68
65
|
const fields = [...new Set(parsed.error.issues.map((issue) => issue.path.join(".") || "(root)"))];
|
|
69
66
|
return { status: "invalid", reason: `invalid or missing: ${fields.join(", ")}` };
|
|
70
67
|
}
|
|
71
|
-
async function defaultClient(settings) {
|
|
72
|
-
// Loaded only once IBKR is set up, so no other agent pays for it.
|
|
73
|
-
const { IBApi } = await import("@stoqey/ib");
|
|
74
|
-
return new IBApi({ host: settings.host, port: settings.port, clientId: settings.clientId });
|
|
75
|
-
}
|
|
76
68
|
export class IbkrSyncService {
|
|
77
69
|
deps;
|
|
78
70
|
timer = null;
|
|
79
71
|
stopped = true;
|
|
80
72
|
/** Last thing logged, so a steady state is one line and not one per minute. */
|
|
81
73
|
lastStatus = "";
|
|
74
|
+
/** The first pass that reads the account asks for the year's trades, so the ones from before this agent was running are there too. */
|
|
75
|
+
caughtUp = false;
|
|
82
76
|
constructor(deps) {
|
|
83
77
|
this.deps = deps;
|
|
84
78
|
}
|
|
@@ -140,23 +134,22 @@ export class IbkrSyncService {
|
|
|
140
134
|
this.report("warn", "IBKR sync is waiting for the Rethinka Fund credential");
|
|
141
135
|
return nextMs;
|
|
142
136
|
}
|
|
143
|
-
const {
|
|
137
|
+
const { collectIbkrMcpSnapshot, pushIbkr } = await import("./ibkr-mcp.js");
|
|
144
138
|
const fetchImpl = this.deps.fetchImpl;
|
|
145
|
-
const send = (kind, body) => fetchImpl ?
|
|
139
|
+
const send = (kind, body) => fetchImpl ? pushIbkr(baseUrl, settings.key, kind, body, fetchImpl) : pushIbkr(baseUrl, settings.key, kind, body);
|
|
146
140
|
let snapshot;
|
|
147
141
|
try {
|
|
148
|
-
|
|
149
|
-
snapshot = await collectSnapshot(ib, {
|
|
142
|
+
snapshot = await (this.deps.collect ?? collectIbkrMcpSnapshot)({
|
|
150
143
|
account: settings.account,
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
144
|
+
tradesPeriod: this.caughtUp ? "DAYS_7" : "YEAR_TO_DATE",
|
|
145
|
+
...(this.deps.authFile ? { authFile: this.deps.authFile } : {}),
|
|
146
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
154
147
|
});
|
|
155
148
|
}
|
|
156
149
|
catch (err) {
|
|
157
150
|
const message = err instanceof Error ? err.message : String(err);
|
|
158
|
-
this.report("warn", `IBKR sync could not read the account: ${message}`);
|
|
159
|
-
// Tell the console, so a
|
|
151
|
+
this.report("warn", err instanceof IbkrNotAuthorizedError ? `IBKR sync is waiting for the owner's authorization: ${message}` : `IBKR sync could not read the account: ${message}`);
|
|
152
|
+
// Tell the console, so a lapsed authorization shows there as a failed sync
|
|
160
153
|
// rather than as numbers that quietly stop changing.
|
|
161
154
|
await send("error", { account: settings.account, error: message }).catch((reportErr) => {
|
|
162
155
|
logger.debug(`rethinka-fund: could not report the IBKR failure: ${reportErr instanceof Error ? reportErr.message : String(reportErr)}`);
|
|
@@ -165,6 +158,7 @@ export class IbkrSyncService {
|
|
|
165
158
|
}
|
|
166
159
|
try {
|
|
167
160
|
await send("snapshot", snapshot);
|
|
161
|
+
this.caughtUp = true;
|
|
168
162
|
this.report("info", `IBKR sync is running for ${maskAccount(settings.account)}`);
|
|
169
163
|
}
|
|
170
164
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ibkr-sync.js","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-sync.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"ibkr-sync.js","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,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AAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YAC1I,CAAC,CAAC,CAAC;YACH,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;YACjC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,4BAA4B,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACnF,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,0EAA0E;YAC1E,+DAA+D;YAC/D,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,0CAA0C,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACpH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED,SAAS,WAAW,CAAC,OAAe;IAClC,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACjC,CAAC"}
|
|
@@ -15,6 +15,9 @@ export declare const polymarketRefreshOrdersTool: import("@anthropic-ai/claude-a
|
|
|
15
15
|
export declare const polymarketRedeemTool: import("@anthropic-ai/claude-agent-sdk").SdkMcpToolDefinition<{
|
|
16
16
|
condition_id: z.ZodOptional<z.ZodString>;
|
|
17
17
|
}>;
|
|
18
|
+
export declare const ibkrAuthorizeTool: import("@anthropic-ai/claude-agent-sdk").SdkMcpToolDefinition<{
|
|
19
|
+
redirected_url: z.ZodOptional<z.ZodString>;
|
|
20
|
+
}>;
|
|
18
21
|
export declare const hyperliquidPlaceOrderTool: import("@anthropic-ai/claude-agent-sdk").SdkMcpToolDefinition<{
|
|
19
22
|
decision_id: z.ZodNumber;
|
|
20
23
|
trade: z.ZodOptional<z.ZodNumber>;
|
|
@@ -61,6 +64,8 @@ export declare const rethinkaFundTradingTools: (import("@anthropic-ai/claude-age
|
|
|
61
64
|
decision_id: z.ZodNumber;
|
|
62
65
|
}> | import("@anthropic-ai/claude-agent-sdk").SdkMcpToolDefinition<{
|
|
63
66
|
condition_id: z.ZodOptional<z.ZodString>;
|
|
67
|
+
}> | import("@anthropic-ai/claude-agent-sdk").SdkMcpToolDefinition<{
|
|
68
|
+
redirected_url: z.ZodOptional<z.ZodString>;
|
|
64
69
|
}> | import("@anthropic-ai/claude-agent-sdk").SdkMcpToolDefinition<{
|
|
65
70
|
decision_id: z.ZodNumber;
|
|
66
71
|
trade: z.ZodOptional<z.ZodNumber>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rethinka-fund-trading.d.ts","sourceRoot":"","sources":["../../src/tools/rethinka-fund-trading.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"rethinka-fund-trading.d.ts","sourceRoot":"","sources":["../../src/tools/rethinka-fund-trading.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA0CxB,eAAO,MAAM,wBAAwB;;;;;EAUpC,CAAC;AAEF,eAAO,MAAM,yBAAyB;;EAKrC,CAAC;AAEF,eAAO,MAAM,wBAAwB,mEAKpC,CAAC;AAIF,eAAO,MAAM,2BAA2B;;EAKvC,CAAC;AAEF,eAAO,MAAM,oBAAoB;;EAKhC,CAAC;AAWF,eAAO,MAAM,iBAAiB;;EAY7B,CAAC;AAMF,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;EAgBrC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;EAQtC,CAAC;AAEF,eAAO,MAAM,yBAAyB,mEAKrC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;EAKtC,CAAC;AAEF,eAAO,MAAM,4BAA4B;;EAKxC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;EAStC,CAAC;AAEF,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAapC,CAAC"}
|
|
@@ -4,6 +4,7 @@ import { loadConfig } from "../config/index.js";
|
|
|
4
4
|
import { resolveRethinkaFundCredentials } from "../rethinka-fund-credentials.js";
|
|
5
5
|
import { cancelPolymarketOrder, listPolymarketOpenOrders, placePolymarketOrder, refreshPolymarketOrders, } from "../rethinka-fund/polymarket-trading.js";
|
|
6
6
|
import { listPolymarketRedeemable, redeemPolymarketPosition } from "../rethinka-fund/polymarket-redeem.js";
|
|
7
|
+
import { finishIbkrAuthorization, ibkrAuthorizationStatus, startIbkrAuthorization } from "../rethinka-fund/ibkr-mcp.js";
|
|
7
8
|
import { cancelHyperliquidOrder, getHyperliquidOrderStatus, listHyperliquidOpenOrders, placeHyperliquidOrder, refreshHyperliquidOrders, setHyperliquidLeverage, } from "../rethinka-fund/hyperliquid-trading.js";
|
|
8
9
|
/**
|
|
9
10
|
* Trading tools of the Rethinka Fund agent. Registered only on that instance.
|
|
@@ -29,6 +30,23 @@ export const polymarketOpenOrdersTool = tool("rkf_polymarket_open_orders", "List
|
|
|
29
30
|
const REFRESH_NOTE = "It asks the exchange about each order under the decision that may still be live, and writes back how much each has actually filled and whether it is still resting, filled, cancelled or was never placed. The amounts come from the exchange, not from you. Call it after placing or cancelling an order, when you come back to a decision that is still pending, and before you conclude a decision with rk_update_decision_outcome. An order that is over then holds only what it traded, so the rest of the decision's size is free again. This places and cancels nothing, and it does not change the decision's status: that is yours to report.";
|
|
30
31
|
export const polymarketRefreshOrdersTool = tool("rkf_polymarket_refresh_orders", `Bring the record of one decision's Polymarket orders up to date. ${REFRESH_NOTE}`, { decision_id: z.number().int().positive().describe("Id returned by rk_record_decision.") }, async (args) => reply(await refreshPolymarketOrders({ decisionId: args.decision_id }, deps)));
|
|
31
32
|
export const polymarketRedeemTool = tool("rkf_polymarket_redeem", "Redeem the owner's dedicated wallet's position in one RESOLVED Polymarket market: hand in shares that won for the cash they are worth (1 USD a share), which then sits in the wallet as pUSD. This sends real chain transactions and spends a little POL from the wallet for gas. It needs no decision: it opens nothing and risks nothing. It is refused while trading is paused, when the market has not resolved, when the wallet holds only the side that lost (that pays nothing), and when the wallet lacks POL for gas. The first redemption from a wallet also sends a one-time approval. The tool waits for each transaction to confirm, which can take a minute or two. Call it WITHOUT condition_id first: that sends nothing and lists what the wallet can redeem, market by market, with each market's condition ID and what it would pay. If the result says a transaction's fate is unknown, do not call again; check the wallet's positions and activity first. The wallet key stays on this host: never read, print or ask for it.", { condition_id: z.string().regex(/^0x[0-9a-fA-F]{64}$/).optional().describe("The resolved market to redeem: its condition ID, 0x followed by 64 hex digits, from the listing. Leave it out to list what can be redeemed.") }, async (args) => reply(args.condition_id === undefined ? await listPolymarketRedeemable(deps) : await redeemPolymarketPosition({ conditionId: args.condition_id }, deps)));
|
|
33
|
+
/** Never throws at the model: what went wrong is the answer. */
|
|
34
|
+
async function attempt(run) {
|
|
35
|
+
try {
|
|
36
|
+
return reply(await run());
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
return reply({ ok: false, reason: err instanceof Error ? err.message : String(err) });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export const ibkrAuthorizeTool = tool("rkf_ibkr_authorize", "Connect this agent to the owner's IBKR account for reading, through Interactive Brokers' own sign-in. Two steps. Call it with no argument to get a login link: give the link to the owner, who opens it on THEIR OWN computer and signs in to Interactive Brokers there (never ask for their IBKR password, passkey or codes, and never sign in for them). After signing in, their browser lands on a page that cannot be reached, at an address starting with http://127.0.0.1:8976/callback: that is expected. Ask the owner to copy that whole address from the address bar and send it to you, then call this again with it as `redirected_url`. The address carries a one-time code that only this agent can use; the authorization it is exchanged for is kept in this agent's profile directory and is never shown, to you or to anyone. It grants read access only. Call with no argument again to start over; the link is good for thirty minutes and the code for a few minutes after the owner signs in.", { redirected_url: z.string().min(1).max(4000).optional().describe("The whole address the owner's browser ended on after signing in. Leave it out to start and get the login link.") }, async (args) => attempt(async () => {
|
|
43
|
+
if (args.redirected_url === undefined) {
|
|
44
|
+
const started = await startIbkrAuthorization();
|
|
45
|
+
return { ok: true, login_url: started.url, lands_on: `${started.redirectUri}?code=…`, link_expires_in_minutes: started.expiresInMinutes, next: "Send login_url to the owner. When they send back the address their browser ended on, call rkf_ibkr_authorize with it as redirected_url." };
|
|
46
|
+
}
|
|
47
|
+
const done = await finishIbkrAuthorization(args.redirected_url);
|
|
48
|
+
return { ok: true, authorized: true, scope: done.scope, status: ibkrAuthorizationStatus(), next: "IBKR sync reads the account on its next pass, within a minute, if rethinka-fund-ibkr.json is in place. Check with rk_get_portfolio." };
|
|
49
|
+
}));
|
|
32
50
|
const hyperliquidDeps = {
|
|
33
51
|
fund: () => resolveRethinkaFundCredentials(loadConfig()),
|
|
34
52
|
};
|
|
@@ -62,6 +80,7 @@ export const rethinkaFundTradingTools = [
|
|
|
62
80
|
polymarketOpenOrdersTool,
|
|
63
81
|
polymarketRefreshOrdersTool,
|
|
64
82
|
polymarketRedeemTool,
|
|
83
|
+
ibkrAuthorizeTool,
|
|
65
84
|
hyperliquidPlaceOrderTool,
|
|
66
85
|
hyperliquidCancelOrderTool,
|
|
67
86
|
hyperliquidOpenOrdersTool,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rethinka-fund-trading.js","sourceRoot":"","sources":["../../src/tools/rethinka-fund-trading.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,IAAI,EAAE,MAAM,gCAAgC,CAAC;AAEtD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AACjF,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,EACpB,uBAAuB,GAG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AE,IAAI,EAA2B,EAAE,CAAC,KAAK,CAAC,MAAM,sBAAsB,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,eAAe,CAAC,CAAC,CACnK,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,wBAAwB;IACxB,yBAAyB;IACzB,wBAAwB;IACxB,2BAA2B;IAC3B,oBAAoB;IACpB,iBAAiB;IACjB,yBAAyB;IACzB,0BAA0B;IAC1B,yBAAyB;IACzB,0BAA0B;IAC1B,4BAA4B;IAC5B,0BAA0B;CAC3B,CAAC"}
|
package/dist-agent/bundle.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/dist-agent/bundle.cjs
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 66285750 bytes
|
|
4
|
+
sha256: 45977da4e1286901e02afcba82f7a75b214c4a6866572b7c6787291f82607326
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "visionclaw",
|
|
3
|
-
"version": "0.1.220-beta.
|
|
3
|
+
"version": "0.1.220-beta.13",
|
|
4
4
|
"description": "A personal assistant agent that runs on your desktop, receives commands from messaging channels, and executes tasks autonomously.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -28,7 +28,6 @@
|
|
|
28
28
|
"@playwright/mcp": "0.0.83",
|
|
29
29
|
"@polymarket/client": "0.20.0",
|
|
30
30
|
"@silvia-odwyer/photon-node": "0.3.4",
|
|
31
|
-
"@stoqey/ib": "1.6.15",
|
|
32
31
|
"@types/qrcode": "1.5.6",
|
|
33
32
|
"cron-parser": "4.9.0",
|
|
34
33
|
"discord.js": "14.26.3",
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
interface ContractLike {
|
|
2
|
-
conId?: number;
|
|
3
|
-
symbol?: string;
|
|
4
|
-
secType?: string;
|
|
5
|
-
currency?: string;
|
|
6
|
-
localSymbol?: string;
|
|
7
|
-
lastTradeDateOrContractMonth?: string;
|
|
8
|
-
strike?: number;
|
|
9
|
-
right?: string;
|
|
10
|
-
multiplier?: number;
|
|
11
|
-
exchange?: string;
|
|
12
|
-
primaryExch?: string;
|
|
13
|
-
}
|
|
14
|
-
/** The part of the TWS client this collector uses. `IBApi` satisfies it. */
|
|
15
|
-
export interface IbClient {
|
|
16
|
-
on(event: string, listener: (...args: never[]) => void): unknown;
|
|
17
|
-
removeAllListeners(): unknown;
|
|
18
|
-
connect(): unknown;
|
|
19
|
-
disconnect(): unknown;
|
|
20
|
-
reqAccountUpdates(subscribe: boolean, acctCode: string): unknown;
|
|
21
|
-
reqExecutions(reqId: number, filter: {
|
|
22
|
-
acctCode?: string;
|
|
23
|
-
}): unknown;
|
|
24
|
-
}
|
|
25
|
-
export interface IbkrSnapshotPayload {
|
|
26
|
-
account: string;
|
|
27
|
-
timezone: string;
|
|
28
|
-
account_values: {
|
|
29
|
-
key: string;
|
|
30
|
-
value: string;
|
|
31
|
-
currency: string;
|
|
32
|
-
}[];
|
|
33
|
-
portfolio: {
|
|
34
|
-
contract: ContractLike;
|
|
35
|
-
position: number;
|
|
36
|
-
marketPrice: number;
|
|
37
|
-
marketValue: number;
|
|
38
|
-
averageCost?: number;
|
|
39
|
-
unrealizedPNL?: number;
|
|
40
|
-
}[];
|
|
41
|
-
executions: {
|
|
42
|
-
contract: ContractLike;
|
|
43
|
-
execId: string;
|
|
44
|
-
time: string;
|
|
45
|
-
side: string;
|
|
46
|
-
shares: number;
|
|
47
|
-
price: number;
|
|
48
|
-
commission?: number;
|
|
49
|
-
commissionCurrency?: string;
|
|
50
|
-
}[];
|
|
51
|
-
}
|
|
52
|
-
export interface CollectOptions {
|
|
53
|
-
account: string;
|
|
54
|
-
timezone: string;
|
|
55
|
-
/** Give up on the whole read after this long. */
|
|
56
|
-
timeoutMs: number;
|
|
57
|
-
/** After the execution list ends, wait this long for commission reports, which arrive separately. */
|
|
58
|
-
commissionWaitMs: number;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* One read: connect, download the account, list today's executions, disconnect.
|
|
62
|
-
* Rejects when the Gateway refuses the connection, reports an error, or does
|
|
63
|
-
* not finish in time. The client is always disconnected before this settles.
|
|
64
|
-
*/
|
|
65
|
-
export declare function collectSnapshot(ib: IbClient, options: CollectOptions): Promise<IbkrSnapshotPayload>;
|
|
66
|
-
export type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
|
|
67
|
-
/** Posts to the Rethinka Fund server. Throws with the server's reason when it refuses. */
|
|
68
|
-
export declare function push(baseUrl: string, key: string, path: "snapshot" | "error", body: unknown, fetchImpl?: FetchLike): Promise<void>;
|
|
69
|
-
export {};
|
|
70
|
-
//# sourceMappingURL=ibkr-collect.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ibkr-collect.d.ts","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-collect.ts"],"names":[],"mappings":"AAWA,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4BAA4B,CAAC,EAAE,MAAM,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,4EAA4E;AAC5E,MAAM,WAAW,QAAQ;IACvB,EAAE,CAAC,KAAK,EAAE,MAAM,EAA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SAAS,EAAE,MAAM,CAAC;IAClB,qGAAqG;IACrG,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAgHnG;AAED,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE/E,0FAA0F;AAC1F,wBAAsB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,GAAE,SAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAU/I"}
|
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Reads one IBKR account through the TWS API and returns what it saw, in the
|
|
3
|
-
* shape the Rethinka Fund server accepts at POST /gateway/ibkr/snapshot
|
|
4
|
-
* (services/rethinka/server/sync/ibkr.ts). Driven by ibkr-sync.ts.
|
|
5
|
-
*
|
|
6
|
-
* This file only reads: the requests it makes are the account subscription
|
|
7
|
-
* and the execution query. tests/unit/rethinka-fund/ibkr-collect.test.ts
|
|
8
|
-
* checks that it stays that way.
|
|
9
|
-
*/
|
|
10
|
-
import { EventName, isNonFatalError } from "@stoqey/ib";
|
|
11
|
-
function contractFields(c) {
|
|
12
|
-
// Copy only the named fields: the library's contract objects carry more.
|
|
13
|
-
const out = {};
|
|
14
|
-
if (c.conId !== undefined)
|
|
15
|
-
out.conId = c.conId;
|
|
16
|
-
if (c.symbol)
|
|
17
|
-
out.symbol = c.symbol;
|
|
18
|
-
if (c.secType)
|
|
19
|
-
out.secType = String(c.secType);
|
|
20
|
-
if (c.currency)
|
|
21
|
-
out.currency = c.currency;
|
|
22
|
-
if (c.localSymbol)
|
|
23
|
-
out.localSymbol = c.localSymbol;
|
|
24
|
-
if (c.lastTradeDateOrContractMonth)
|
|
25
|
-
out.lastTradeDateOrContractMonth = c.lastTradeDateOrContractMonth;
|
|
26
|
-
if (typeof c.strike === "number" && Number.isFinite(c.strike))
|
|
27
|
-
out.strike = c.strike;
|
|
28
|
-
if (c.right)
|
|
29
|
-
out.right = String(c.right);
|
|
30
|
-
if (typeof c.multiplier === "number" && Number.isFinite(c.multiplier))
|
|
31
|
-
out.multiplier = c.multiplier;
|
|
32
|
-
if (c.exchange)
|
|
33
|
-
out.exchange = c.exchange;
|
|
34
|
-
if (c.primaryExch)
|
|
35
|
-
out.primaryExch = c.primaryExch;
|
|
36
|
-
return out;
|
|
37
|
-
}
|
|
38
|
-
function finiteOrUndefined(value) {
|
|
39
|
-
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* One read: connect, download the account, list today's executions, disconnect.
|
|
43
|
-
* Rejects when the Gateway refuses the connection, reports an error, or does
|
|
44
|
-
* not finish in time. The client is always disconnected before this settles.
|
|
45
|
-
*/
|
|
46
|
-
export function collectSnapshot(ib, options) {
|
|
47
|
-
const snapshot = { account: options.account, timezone: options.timezone, account_values: [], portfolio: [], executions: [] };
|
|
48
|
-
// A value or position is reported again whenever it changes; keep the latest.
|
|
49
|
-
const values = new Map();
|
|
50
|
-
const portfolio = new Map();
|
|
51
|
-
const executions = new Map();
|
|
52
|
-
return new Promise((resolve, reject) => {
|
|
53
|
-
let settled = false;
|
|
54
|
-
let accountDone = false;
|
|
55
|
-
let executionsDone = false;
|
|
56
|
-
let commissionTimer = null;
|
|
57
|
-
const finish = (error) => {
|
|
58
|
-
if (settled)
|
|
59
|
-
return;
|
|
60
|
-
settled = true;
|
|
61
|
-
clearTimeout(deadline);
|
|
62
|
-
if (commissionTimer)
|
|
63
|
-
clearTimeout(commissionTimer);
|
|
64
|
-
try {
|
|
65
|
-
ib.reqAccountUpdates(false, options.account);
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
// Not connected; nothing to unsubscribe.
|
|
69
|
-
}
|
|
70
|
-
ib.removeAllListeners();
|
|
71
|
-
// The library emits `error` when the socket closes; with no listener an
|
|
72
|
-
// EventEmitter would throw it.
|
|
73
|
-
ib.on(EventName.error, () => undefined);
|
|
74
|
-
try {
|
|
75
|
-
ib.disconnect();
|
|
76
|
-
}
|
|
77
|
-
catch {
|
|
78
|
-
// Already closed.
|
|
79
|
-
}
|
|
80
|
-
if (error) {
|
|
81
|
-
reject(error);
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
snapshot.account_values = [...values.values()];
|
|
85
|
-
snapshot.portfolio = [...portfolio.values()];
|
|
86
|
-
snapshot.executions = [...executions.values()];
|
|
87
|
-
resolve(snapshot);
|
|
88
|
-
};
|
|
89
|
-
const maybeDone = () => {
|
|
90
|
-
if (!accountDone || !executionsDone || commissionTimer)
|
|
91
|
-
return;
|
|
92
|
-
commissionTimer = setTimeout(() => finish(null), options.commissionWaitMs);
|
|
93
|
-
};
|
|
94
|
-
const deadline = setTimeout(() => {
|
|
95
|
-
const waitingFor = !accountDone ? "the account download" : "the execution list";
|
|
96
|
-
finish(new Error(`IB Gateway did not finish ${waitingFor} within ${Math.round(options.timeoutMs / 1000)}s`));
|
|
97
|
-
}, options.timeoutMs);
|
|
98
|
-
ib.on(EventName.connected, () => {
|
|
99
|
-
ib.reqAccountUpdates(true, options.account);
|
|
100
|
-
ib.reqExecutions(1, { acctCode: options.account });
|
|
101
|
-
});
|
|
102
|
-
ib.on(EventName.disconnected, () => finish(new Error("IB Gateway closed the connection")));
|
|
103
|
-
ib.on(EventName.error, ((error, code) => {
|
|
104
|
-
// Notices such as "market data farm connection is OK" arrive as errors.
|
|
105
|
-
if (isNonFatalError(code, error))
|
|
106
|
-
return;
|
|
107
|
-
finish(new Error(`IB Gateway error ${code}: ${error.message}`));
|
|
108
|
-
}));
|
|
109
|
-
ib.on(EventName.updateAccountValue, ((key, value, currency, accountName) => {
|
|
110
|
-
if (accountName && accountName !== options.account)
|
|
111
|
-
return;
|
|
112
|
-
values.set(`${key}|${currency}`, { key, value: String(value), currency: currency ?? "" });
|
|
113
|
-
}));
|
|
114
|
-
ib.on(EventName.updatePortfolio, ((contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, _realizedPNL, accountName) => {
|
|
115
|
-
if (accountName && accountName !== options.account)
|
|
116
|
-
return;
|
|
117
|
-
const item = { contract: contractFields(contract), position, marketPrice, marketValue };
|
|
118
|
-
const cost = finiteOrUndefined(averageCost);
|
|
119
|
-
const pnl = finiteOrUndefined(unrealizedPNL);
|
|
120
|
-
if (cost !== undefined)
|
|
121
|
-
item.averageCost = cost;
|
|
122
|
-
if (pnl !== undefined)
|
|
123
|
-
item.unrealizedPNL = pnl;
|
|
124
|
-
portfolio.set(String(contract.conId ?? `${contract.symbol}|${contract.localSymbol}`), item);
|
|
125
|
-
}));
|
|
126
|
-
ib.on(EventName.accountDownloadEnd, ((account) => {
|
|
127
|
-
if (account && account !== options.account)
|
|
128
|
-
return;
|
|
129
|
-
accountDone = true;
|
|
130
|
-
maybeDone();
|
|
131
|
-
}));
|
|
132
|
-
ib.on(EventName.execDetails, ((_reqId, contract, execution) => {
|
|
133
|
-
if (execution.acctNumber && execution.acctNumber !== options.account)
|
|
134
|
-
return;
|
|
135
|
-
if (!execution.execId || typeof execution.shares !== "number" || typeof execution.price !== "number")
|
|
136
|
-
return;
|
|
137
|
-
executions.set(execution.execId, {
|
|
138
|
-
contract: contractFields(contract),
|
|
139
|
-
execId: execution.execId,
|
|
140
|
-
time: execution.time ?? "",
|
|
141
|
-
side: execution.side ?? "",
|
|
142
|
-
shares: execution.shares,
|
|
143
|
-
price: execution.price,
|
|
144
|
-
});
|
|
145
|
-
}));
|
|
146
|
-
ib.on(EventName.commissionReport, ((report) => {
|
|
147
|
-
const execution = report.execId ? executions.get(report.execId) : undefined;
|
|
148
|
-
const commission = finiteOrUndefined(report.commission);
|
|
149
|
-
if (!execution || commission === undefined)
|
|
150
|
-
return;
|
|
151
|
-
execution.commission = commission;
|
|
152
|
-
if (report.currency)
|
|
153
|
-
execution.commissionCurrency = report.currency;
|
|
154
|
-
}));
|
|
155
|
-
ib.on(EventName.execDetailsEnd, () => {
|
|
156
|
-
executionsDone = true;
|
|
157
|
-
maybeDone();
|
|
158
|
-
});
|
|
159
|
-
try {
|
|
160
|
-
ib.connect();
|
|
161
|
-
}
|
|
162
|
-
catch (err) {
|
|
163
|
-
finish(err instanceof Error ? err : new Error(String(err)));
|
|
164
|
-
}
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
/** Posts to the Rethinka Fund server. Throws with the server's reason when it refuses. */
|
|
168
|
-
export async function push(baseUrl, key, path, body, fetchImpl = fetch) {
|
|
169
|
-
const response = await fetchImpl(`${baseUrl}/gateway/ibkr/${path}`, {
|
|
170
|
-
method: "POST",
|
|
171
|
-
headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
|
|
172
|
-
body: JSON.stringify(body),
|
|
173
|
-
signal: AbortSignal.timeout(30_000),
|
|
174
|
-
});
|
|
175
|
-
if (response.ok)
|
|
176
|
-
return;
|
|
177
|
-
const reply = (await response.json().catch(() => ({})));
|
|
178
|
-
throw new Error(`Rethinka refused the ${path} (HTTP ${response.status}): ${typeof reply.error === "string" ? reply.error : "no reason given"}`);
|
|
179
|
-
}
|
|
180
|
-
//# sourceMappingURL=ibkr-collect.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ibkr-collect.js","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-collect.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAqCxD,SAAS,cAAc,CAAC,CAAc;IACpC,yEAAyE;IACzE,MAAM,GAAG,GAAiB,EAAE,CAAC;IAC7B,IAAI,CAAC,CAAC,KAAK,KAAK,S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