visionclaw 0.1.220-beta.2 → 0.1.220-beta.21

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.
Files changed (239) hide show
  1. package/README.md +2 -2
  2. package/dist/agent/activity-tracker.d.ts +8 -17
  3. package/dist/agent/activity-tracker.d.ts.map +1 -1
  4. package/dist/agent/activity-tracker.js +11 -25
  5. package/dist/agent/activity-tracker.js.map +1 -1
  6. package/dist/agent/command-handlers.js +1 -1
  7. package/dist/agent/command-handlers.js.map +1 -1
  8. package/dist/agent/context.d.ts +0 -22
  9. package/dist/agent/context.d.ts.map +1 -1
  10. package/dist/agent/context.js +0 -79
  11. package/dist/agent/context.js.map +1 -1
  12. package/dist/agent/engine-switch-handler.d.ts +2 -2
  13. package/dist/agent/engine-switch-handler.js +3 -3
  14. package/dist/agent/engine-switch-handler.js.map +1 -1
  15. package/dist/agent/engine-switch-target.d.ts.map +1 -1
  16. package/dist/agent/engine-switch-target.js +5 -1
  17. package/dist/agent/engine-switch-target.js.map +1 -1
  18. package/dist/agent/engine-switch.d.ts +4 -4
  19. package/dist/agent/engine-switch.d.ts.map +1 -1
  20. package/dist/agent/engine-switch.js +9 -3
  21. package/dist/agent/engine-switch.js.map +1 -1
  22. package/dist/agent/engines/claude/session.d.ts +2 -1
  23. package/dist/agent/engines/claude/session.d.ts.map +1 -1
  24. package/dist/agent/engines/claude/session.js +5 -4
  25. package/dist/agent/engines/claude/session.js.map +1 -1
  26. package/dist/agent/engines/pi/tools.d.ts.map +1 -1
  27. package/dist/agent/engines/pi/tools.js +3 -1
  28. package/dist/agent/engines/pi/tools.js.map +1 -1
  29. package/dist/agent/engines/pi-coding/mcp-config.d.ts +10 -1
  30. package/dist/agent/engines/pi-coding/mcp-config.d.ts.map +1 -1
  31. package/dist/agent/engines/pi-coding/mcp-config.js +4 -7
  32. package/dist/agent/engines/pi-coding/mcp-config.js.map +1 -1
  33. package/dist/agent/engines/pi-coding/session.d.ts +1 -1
  34. package/dist/agent/engines/pi-coding/session.d.ts.map +1 -1
  35. package/dist/agent/engines/pi-coding/session.js +17 -22
  36. package/dist/agent/engines/pi-coding/session.js.map +1 -1
  37. package/dist/agent/engines/session-types.d.ts +2 -0
  38. package/dist/agent/engines/session-types.d.ts.map +1 -1
  39. package/dist/agent/fast-response-eligibility.d.ts +2 -2
  40. package/dist/agent/fast-response-eligibility.d.ts.map +1 -1
  41. package/dist/agent/fast-response-eligibility.js +10 -2
  42. package/dist/agent/fast-response-eligibility.js.map +1 -1
  43. package/dist/agent/interrupt-handler.d.ts +2 -2
  44. package/dist/agent/interrupt-handler.js +4 -4
  45. package/dist/agent/interrupt-handler.js.map +1 -1
  46. package/dist/agent/llm-engine-capabilities.d.ts.map +1 -1
  47. package/dist/agent/llm-engine-capabilities.js +4 -1
  48. package/dist/agent/llm-engine-capabilities.js.map +1 -1
  49. package/dist/agent/loop.d.ts +0 -2
  50. package/dist/agent/loop.d.ts.map +1 -1
  51. package/dist/agent/loop.js +12 -4
  52. package/dist/agent/loop.js.map +1 -1
  53. package/dist/agent/model-provider.d.ts +1 -7
  54. package/dist/agent/model-provider.d.ts.map +1 -1
  55. package/dist/agent/model-provider.js +2 -10
  56. package/dist/agent/model-provider.js.map +1 -1
  57. package/dist/agent/owner-initiated-eligibility.d.ts +2 -0
  58. package/dist/agent/owner-initiated-eligibility.d.ts.map +1 -1
  59. package/dist/agent/owner-initiated-eligibility.js +5 -15
  60. package/dist/agent/owner-initiated-eligibility.js.map +1 -1
  61. package/dist/agent/reply-watchdog.d.ts +1 -1
  62. package/dist/agent/reply-watchdog.js +2 -2
  63. package/dist/agent/reply-watchdog.js.map +1 -1
  64. package/dist/agent/runtime-surface.d.ts +2 -0
  65. package/dist/agent/runtime-surface.d.ts.map +1 -1
  66. package/dist/agent/runtime-surface.js +12 -2
  67. package/dist/agent/runtime-surface.js.map +1 -1
  68. package/dist/agent/status.js +1 -1
  69. package/dist/agent/status.js.map +1 -1
  70. package/dist/agent/stream-handler.d.ts.map +1 -1
  71. package/dist/agent/stream-handler.js +48 -22
  72. package/dist/agent/stream-handler.js.map +1 -1
  73. package/dist/agent/system-prompt.d.ts.map +1 -1
  74. package/dist/agent/system-prompt.js +10 -4
  75. package/dist/agent/system-prompt.js.map +1 -1
  76. package/dist/agent/wake-cycle-runner.d.ts +1 -1
  77. package/dist/agent/wake-cycle-runner.d.ts.map +1 -1
  78. package/dist/agent/wake-cycle-runner.js +2 -3
  79. package/dist/agent/wake-cycle-runner.js.map +1 -1
  80. package/dist/builtin-skills/rethinka-fund/SKILL.md +287 -28
  81. package/dist/builtin-skills/rethinka-fund/core-contract.md +30 -14
  82. package/dist/channels/interface.d.ts +0 -34
  83. package/dist/channels/interface.d.ts.map +1 -1
  84. package/dist/channels/manager.d.ts.map +1 -1
  85. package/dist/channels/manager.js +4 -0
  86. package/dist/channels/manager.js.map +1 -1
  87. package/dist/channels/qq.js +1 -1
  88. package/dist/channels/qq.js.map +1 -1
  89. package/dist/channels/rethinka-fund.d.ts +16 -3
  90. package/dist/channels/rethinka-fund.d.ts.map +1 -1
  91. package/dist/channels/rethinka-fund.js +180 -16
  92. package/dist/channels/rethinka-fund.js.map +1 -1
  93. package/dist/channels/telegram.js +1 -1
  94. package/dist/channels/telegram.js.map +1 -1
  95. package/dist/channels/tui-commands.js +1 -1
  96. package/dist/channels/tui-commands.js.map +1 -1
  97. package/dist/config/types.d.ts +4 -2
  98. package/dist/config/types.d.ts.map +1 -1
  99. package/dist/config/types.js +1 -1
  100. package/dist/config/types.js.map +1 -1
  101. package/dist/index.js.map +1 -1
  102. package/dist/obs/mini-app/status.d.ts.map +1 -1
  103. package/dist/obs/mini-app/status.js +63 -0
  104. package/dist/obs/mini-app/status.js.map +1 -1
  105. package/dist/obs/mini-app/telegram-auth.d.ts +23 -0
  106. package/dist/obs/mini-app/telegram-auth.d.ts.map +1 -0
  107. package/dist/obs/mini-app/telegram-auth.js +55 -0
  108. package/dist/obs/mini-app/telegram-auth.js.map +1 -0
  109. package/dist/obs/rdp/linux-x11-backend.d.ts +9 -0
  110. package/dist/obs/rdp/linux-x11-backend.d.ts.map +1 -1
  111. package/dist/obs/rdp/linux-x11-backend.js +69 -33
  112. package/dist/obs/rdp/linux-x11-backend.js.map +1 -1
  113. package/dist/obs/server.d.ts.map +1 -1
  114. package/dist/obs/server.js +29 -0
  115. package/dist/obs/server.js.map +1 -1
  116. package/dist/reconfigure.d.ts.map +1 -1
  117. package/dist/reconfigure.js +7 -1
  118. package/dist/reconfigure.js.map +1 -1
  119. package/dist/rethinka-fund/hyperliquid-signing.d.ts +56 -0
  120. package/dist/rethinka-fund/hyperliquid-signing.d.ts.map +1 -0
  121. package/dist/rethinka-fund/hyperliquid-signing.js +159 -0
  122. package/dist/rethinka-fund/hyperliquid-signing.js.map +1 -0
  123. package/dist/rethinka-fund/hyperliquid-trading.d.ts +154 -0
  124. package/dist/rethinka-fund/hyperliquid-trading.d.ts.map +1 -0
  125. package/dist/rethinka-fund/hyperliquid-trading.js +673 -0
  126. package/dist/rethinka-fund/hyperliquid-trading.js.map +1 -0
  127. package/dist/rethinka-fund/ibkr-flex.d.ts +49 -0
  128. package/dist/rethinka-fund/ibkr-flex.d.ts.map +1 -0
  129. package/dist/rethinka-fund/ibkr-flex.js +182 -0
  130. package/dist/rethinka-fund/ibkr-flex.js.map +1 -0
  131. package/dist/rethinka-fund/ibkr-mcp.d.ts +119 -0
  132. package/dist/rethinka-fund/ibkr-mcp.d.ts.map +1 -0
  133. package/dist/rethinka-fund/ibkr-mcp.js +418 -0
  134. package/dist/rethinka-fund/ibkr-mcp.js.map +1 -0
  135. package/dist/rethinka-fund/ibkr-sync.d.ts +30 -17
  136. package/dist/rethinka-fund/ibkr-sync.d.ts.map +1 -1
  137. package/dist/rethinka-fund/ibkr-sync.js +66 -31
  138. package/dist/rethinka-fund/ibkr-sync.js.map +1 -1
  139. package/dist/rethinka-fund/ibkr-trading.d.ts +102 -0
  140. package/dist/rethinka-fund/ibkr-trading.d.ts.map +1 -0
  141. package/dist/rethinka-fund/ibkr-trading.js +594 -0
  142. package/dist/rethinka-fund/ibkr-trading.js.map +1 -0
  143. package/dist/rethinka-fund/order-refresh.d.ts +66 -0
  144. package/dist/rethinka-fund/order-refresh.d.ts.map +1 -0
  145. package/dist/rethinka-fund/order-refresh.js +195 -0
  146. package/dist/rethinka-fund/order-refresh.js.map +1 -0
  147. package/dist/rethinka-fund/polymarket-redeem.d.ts +82 -0
  148. package/dist/rethinka-fund/polymarket-redeem.d.ts.map +1 -0
  149. package/dist/rethinka-fund/polymarket-redeem.js +353 -0
  150. package/dist/rethinka-fund/polymarket-redeem.js.map +1 -0
  151. package/dist/rethinka-fund/polymarket-trading.d.ts +61 -30
  152. package/dist/rethinka-fund/polymarket-trading.d.ts.map +1 -1
  153. package/dist/rethinka-fund/polymarket-trading.js +183 -71
  154. package/dist/rethinka-fund/polymarket-trading.js.map +1 -1
  155. package/dist/rethinka-fund/trading-common.d.ts +157 -0
  156. package/dist/rethinka-fund/trading-common.d.ts.map +1 -0
  157. package/dist/rethinka-fund/trading-common.js +237 -0
  158. package/dist/rethinka-fund/trading-common.js.map +1 -0
  159. package/dist/rethinka-fund-credentials.d.ts +2 -0
  160. package/dist/rethinka-fund-credentials.d.ts.map +1 -1
  161. package/dist/rethinka-fund-credentials.js +2 -0
  162. package/dist/rethinka-fund-credentials.js.map +1 -1
  163. package/dist/sites/manager.d.ts +50 -0
  164. package/dist/sites/manager.d.ts.map +1 -0
  165. package/dist/sites/manager.js +353 -0
  166. package/dist/sites/manager.js.map +1 -0
  167. package/dist/sites/pm2-injected-env.d.ts +49 -0
  168. package/dist/sites/pm2-injected-env.d.ts.map +1 -0
  169. package/dist/sites/pm2-injected-env.js +160 -0
  170. package/dist/sites/pm2-injected-env.js.map +1 -0
  171. package/dist/sites/process.d.ts +20 -0
  172. package/dist/sites/process.d.ts.map +1 -0
  173. package/dist/sites/process.js +122 -0
  174. package/dist/sites/process.js.map +1 -0
  175. package/dist/sites/registry.d.ts +79 -0
  176. package/dist/sites/registry.d.ts.map +1 -0
  177. package/dist/sites/registry.js +147 -0
  178. package/dist/sites/registry.js.map +1 -0
  179. package/dist/threads/execution-snapshot.d.ts +1 -0
  180. package/dist/threads/execution-snapshot.d.ts.map +1 -1
  181. package/dist/threads/foreground-task.d.ts +16 -3
  182. package/dist/threads/foreground-task.d.ts.map +1 -1
  183. package/dist/threads/foreground-task.js +57 -7
  184. package/dist/threads/foreground-task.js.map +1 -1
  185. package/dist/threads/foreman-execution.d.ts +14 -2
  186. package/dist/threads/foreman-execution.d.ts.map +1 -1
  187. package/dist/threads/foreman-execution.js +15 -3
  188. package/dist/threads/foreman-execution.js.map +1 -1
  189. package/dist/threads/foreman-host.d.ts +1 -0
  190. package/dist/threads/foreman-host.d.ts.map +1 -1
  191. package/dist/threads/foreman-host.js +27 -5
  192. package/dist/threads/foreman-host.js.map +1 -1
  193. package/dist/threads/foreman-protocol.d.ts +1 -0
  194. package/dist/threads/foreman-protocol.d.ts.map +1 -1
  195. package/dist/threads/foreman-protocol.js +2 -2
  196. package/dist/threads/foreman-protocol.js.map +1 -1
  197. package/dist/threads/foreman-write-contract.d.ts +1 -1
  198. package/dist/threads/foreman-write-contract.d.ts.map +1 -1
  199. package/dist/threads/foreman-write-contract.js +1 -1
  200. package/dist/threads/foreman-write-contract.js.map +1 -1
  201. package/dist/threads/supervisor.d.ts +2 -1
  202. package/dist/threads/supervisor.d.ts.map +1 -1
  203. package/dist/threads/supervisor.js +4 -1
  204. package/dist/threads/supervisor.js.map +1 -1
  205. package/dist/threads/thread-meta.d.ts +1 -0
  206. package/dist/threads/thread-meta.d.ts.map +1 -1
  207. package/dist/tools/delegation.d.ts.map +1 -1
  208. package/dist/tools/delegation.js +4 -1
  209. package/dist/tools/delegation.js.map +1 -1
  210. package/dist/tools/email.d.ts +1 -1
  211. package/dist/tools/event-trigger.d.ts +2 -2
  212. package/dist/tools/finish.d.ts.map +1 -1
  213. package/dist/tools/finish.js +5 -1
  214. package/dist/tools/finish.js.map +1 -1
  215. package/dist/tools/index.d.ts.map +1 -1
  216. package/dist/tools/index.js +4 -0
  217. package/dist/tools/index.js.map +1 -1
  218. package/dist/tools/rethinka-fund-trading.d.ts +137 -1
  219. package/dist/tools/rethinka-fund-trading.d.ts.map +1 -1
  220. package/dist/tools/rethinka-fund-trading.js +102 -5
  221. package/dist/tools/rethinka-fund-trading.js.map +1 -1
  222. package/dist/tools/sites.d.ts +24 -0
  223. package/dist/tools/sites.d.ts.map +1 -0
  224. package/dist/tools/sites.js +61 -0
  225. package/dist/tools/sites.js.map +1 -0
  226. package/dist/tui/index.js +1 -1
  227. package/dist-agent/bundle.cjs +2 -2
  228. package/dist-agent/image-resize-worker.js +1 -0
  229. package/dist-agent/image-resize-worker.mjs +375 -0
  230. package/dist-agent/mcp-script-worker.mjs +6 -2
  231. package/package.json +8 -8
  232. package/dist/agent/fast-responder.d.ts +0 -52
  233. package/dist/agent/fast-responder.d.ts.map +0 -1
  234. package/dist/agent/fast-responder.js +0 -213
  235. package/dist/agent/fast-responder.js.map +0 -1
  236. package/dist/rethinka-fund/ibkr-collect.d.ts +0 -70
  237. package/dist/rethinka-fund/ibkr-collect.d.ts.map +0 -1
  238. package/dist/rethinka-fund/ibkr-collect.js +0 -180
  239. package/dist/rethinka-fund/ibkr-collect.js.map +0 -1
@@ -0,0 +1,594 @@
1
+ /**
2
+ * IBKR trading for the Rethinka Fund agent: stocks and equity options, in
3
+ * Hong Kong and the US, through Interactive Brokers' own MCP server.
4
+ *
5
+ * An option's contract size is not the same everywhere: 100 shares for US
6
+ * options and some Hong Kong ones, but 20 for MiniMax and 500 for Alibaba in
7
+ * Hong Kong. Interactive Brokers names it in the option's description, in
8
+ * brackets, when it is not 100 ("100 (MNX) DEC 30 '26 95 Call (20) @SEHK"), and
9
+ * leaves it out when it is ("700 (TCH) DEC 30 '26 600 Call @SEHK"). The chain
10
+ * tool reads it there and writes it into the symbol the decision records
11
+ * (`opt:937933330@SEHK*20`), so every amount is worked out with it.
12
+ *
13
+ * The agent does not place orders on IBKR. It creates an order instruction,
14
+ * which is not an order: the owner opens it in Interactive Brokers' app and
15
+ * submits it there, or it never trades. So an order is approved twice: the
16
+ * decision it belongs to, in the Rethinka Fund console, and the order itself,
17
+ * in Interactive Brokers.
18
+ *
19
+ * Interactive Brokers does not say which order an instruction became. An
20
+ * instruction disappears when it is submitted (or deleted, or expires after a
21
+ * week), and an order appears with nothing that names the instruction; a
22
+ * submission Interactive Brokers rejects leaves the instruction in place, with
23
+ * a rejected order beside it. The order is found by what both say: the
24
+ * contract, the side, the quantity and the limit, and that it came after the
25
+ * instruction. An order names its contract in its description: a stock by its
26
+ * code ("Sell 500 7709"), an option as the chain describes it ("Buy 1 100 (MNX)
27
+ * DEC 30 '26 100 Call (20) @SEHK"). The instruction names only the stock's
28
+ * code, for an option too, so an option's order is matched by the decision's
29
+ * title, which is the chain's description. When the owner changed the price or
30
+ * the quantity (not both) before submitting, the order is taken if it is the
31
+ * only one that could be it, and the record says it was changed; anything less
32
+ * clear is asked about.
33
+ *
34
+ * Every tool here checks the decision with the Rethinka Fund server first, as
35
+ * the other venues' tools do, and writes each instruction and order back to it.
36
+ */
37
+ import { randomUUID } from "node:crypto";
38
+ import { ibkrMayStageOrders, IbkrMcpSession, IbkrToolError } from "./ibkr-mcp.js";
39
+ import { errorText, fundCall, fullyFilled, readDecision, refreshDecisionOrders, reportOrder, tradeName, tradeRoute } from "./trading-common.js";
40
+ /** Where each exchange trades in, for the exchanges this tool trades on. */
41
+ const STOCK_CURRENCY = {
42
+ SEHK: "HKD",
43
+ NASDAQ: "USD", NYSE: "USD", ARCA: "USD", AMEX: "USD", BATS: "USD", IEX: "USD", NYSEAMERICAN: "USD", SMART: "USD",
44
+ };
45
+ /** Where each option exchange trades in: the US ones, and Hong Kong's. */
46
+ const OPTION_CURRENCY = {
47
+ SEHK: "HKD",
48
+ ...Object.fromEntries(["SMART", "CBOE", "C2", "AMEX", "ISE", "PHLX", "BOX", "NASDAQOM", "MIAX", "PEARL", "GEMINI", "MERCURY", "EDGX", "BATS", "EMERALD", "MEMX", "IBUSOPT"].map((exchange) => [exchange, "USD"])),
49
+ };
50
+ /** An option's contract size when Interactive Brokers' description names none. */
51
+ const DEFAULT_OPTION_MULTIPLIER = 100;
52
+ /** How many contracts are quoted at once: Interactive Brokers allows 100 data points a request, and two fields are asked for. */
53
+ const QUOTE_BATCH = 50;
54
+ const INSTRUCTION = "instruction:";
55
+ function asRecord(value) {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
57
+ }
58
+ function asList(value) {
59
+ return Array.isArray(value) ? value.map(asRecord) : [];
60
+ }
61
+ /** A field as text: empty when it is not a string or a number. */
62
+ function text(value) {
63
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
64
+ }
65
+ function numberOf(value) {
66
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : Number.NaN;
67
+ return Number.isFinite(n) ? n : null;
68
+ }
69
+ /** The contract a decision names, or why this tool cannot trade it. */
70
+ export function readIbkrSymbol(symbol) {
71
+ const option = /^opt:(\d{1,12})@([A-Z0-9._-]{1,20})\*([1-9]\d{0,5})$/.exec(symbol);
72
+ if (option) {
73
+ const [, conid, exchange, size] = option;
74
+ const currency = OPTION_CURRENCY[exchange];
75
+ if (!currency)
76
+ return { reason: `options are traded here in Hong Kong (SEHK) and the US only, and ${exchange} is neither` };
77
+ return { kind: "opt", conid, exchange, currency, multiplier: Number(size) };
78
+ }
79
+ const stock = /^stk:(\d{1,12})@([A-Z0-9._-]{1,20})$/.exec(symbol);
80
+ if (!stock)
81
+ return { reason: `"${symbol}" is not an IBKR contract as rkf_ibkr_find_contract or rkf_ibkr_option_chain names it (stk:<id>@<exchange>, or opt:<id>@<exchange>*<contract size>)` };
82
+ const [, conid, exchange] = stock;
83
+ const currency = STOCK_CURRENCY[exchange];
84
+ if (!currency)
85
+ return { reason: `stocks are traded here in Hong Kong (SEHK) and the US only, and ${exchange} is neither` };
86
+ return { kind: "stk", conid, exchange, currency, multiplier: 1 };
87
+ }
88
+ /**
89
+ * An option's contract size, from Interactive Brokers' description of it: the
90
+ * number in brackets ("... Call (20) @SEHK"), or 100 when there is none. Null
91
+ * when the brackets hold something that is not a size.
92
+ */
93
+ export function optionMultiplier(description) {
94
+ const bracketed = [...description.matchAll(/\(([^)]*)\)/g)].map((m) => m[1]);
95
+ // The trading class is bracketed too ("100 (MNX) ..."): it is letters, a contract size is a whole number.
96
+ const sizes = bracketed.filter((inside) => /^\d+$/.test(inside));
97
+ if (sizes.length > 1)
98
+ return null;
99
+ if (sizes.length === 0)
100
+ return bracketed.every((inside) => /^[A-Z][A-Z0-9.]*$/.test(inside)) ? DEFAULT_OPTION_MULTIPLIER : null;
101
+ const size = Number(sizes[0]);
102
+ return size > 0 ? size : null;
103
+ }
104
+ /** The contract as create_order_instruction takes it: a stock by its id alone, an option by `id@exchange`. */
105
+ function instructionContract(contract) {
106
+ return contract.kind === "stk" ? contract.conid : `${contract.conid}@${contract.exchange}`;
107
+ }
108
+ function session(deps) {
109
+ const auth = { ...(deps.authFile ? { authFile: deps.authFile } : {}), ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}), ...(deps.now ? { now: deps.now } : {}) };
110
+ return new IbkrMcpSession(auth);
111
+ }
112
+ async function opened(deps) {
113
+ const mcp = session(deps);
114
+ await mcp.open();
115
+ return mcp;
116
+ }
117
+ /** Bid and ask of a quote snapshot, whatever the tool called them. */
118
+ function quoteOf(snapshot) {
119
+ const data = asRecord(typeof snapshot === "string" ? (() => { try {
120
+ return JSON.parse(snapshot);
121
+ }
122
+ catch {
123
+ return null;
124
+ } })() : snapshot);
125
+ const quote = asRecord(data["bid-ask"] ?? data.bid_ask);
126
+ return { bid: numberOf(quote.bid), ask: numberOf(quote.ask), last: numberOf(asRecord(data.last).price) };
127
+ }
128
+ /** Quotes for several contracts, keyed by `id@exchange`. A contract that could not be quoted is left out. */
129
+ async function quotes(mcp, ids) {
130
+ const found = new Map();
131
+ for (let i = 0; i < ids.length; i += QUOTE_BATCH) {
132
+ const batch = ids.slice(i, i + QUOTE_BATCH);
133
+ const answer = asRecord(await mcp.call("get_price_snapshot", { contract_id_exs: batch, market_data_names: ["bid_ask", "last"] }));
134
+ for (const id of batch)
135
+ if (answer[id] !== undefined && answer[id] !== null)
136
+ found.set(id, quoteOf(answer[id]));
137
+ }
138
+ return found;
139
+ }
140
+ /** One US dollar in a currency, from Interactive Brokers' own quote. */
141
+ async function dollarRate(mcp, currency) {
142
+ if (currency === "USD")
143
+ return 1;
144
+ const found = asList(asRecord(await mcp.call("search_contracts", { query: `USD.${currency}` })).results);
145
+ const pair = found.find((row) => row.symbol === "USD" && typeof row.underlying_contract_id === "number" && typeof row.exchange === "string" && asList(row.sections).some((section) => section.security_type === "CASH"));
146
+ if (!pair)
147
+ throw new Error(`Interactive Brokers has no quote for the US dollar in ${currency}`);
148
+ const quote = quoteOf(await mcp.call("get_price_snapshot", { contract_id: pair.underlying_contract_id, exchange: pair.exchange }));
149
+ const rate = quote.bid !== null && quote.ask !== null ? (quote.bid + quote.ask) / 2 : quote.last;
150
+ if (rate === null || rate <= 0)
151
+ throw new Error(`Interactive Brokers gave no price for the US dollar in ${currency}`);
152
+ return rate;
153
+ }
154
+ /** The read-only result of a tool, or why it failed. Never throws. */
155
+ async function attempt(run) {
156
+ try {
157
+ return await run();
158
+ }
159
+ catch (err) {
160
+ return { ok: false, reason: errorText(err) };
161
+ }
162
+ }
163
+ /** Stocks that match a code or a name, with the contract to record in a decision and a quote. */
164
+ export async function findIbkrContract(input, deps) {
165
+ return await attempt(async () => {
166
+ const mcp = await opened(deps);
167
+ const results = asList(asRecord(await mcp.call("search_contracts", { query: input.query })).results);
168
+ const stocks = results
169
+ .filter((row) => typeof row.underlying_contract_id === "number" && typeof row.exchange === "string" && asList(row.sections).some((section) => section.security_type === "STK"))
170
+ .slice(0, 10)
171
+ .map((row) => {
172
+ const exchange = row.exchange;
173
+ const id = String(row.underlying_contract_id);
174
+ const symbol = `stk:${id}@${exchange}`;
175
+ const usable = readIbkrSymbol(symbol);
176
+ return { id, exchange, symbol, ticker: row.symbol, description: row.description, has_options: asList(row.sections).some((section) => section.security_type === "OPT"), ...("reason" in usable ? { tradable_here: false, why_not: usable.reason } : { tradable_here: true, currency: usable.currency }) };
177
+ });
178
+ const quoted = await quotes(mcp, stocks.filter((s) => s.tradable_here).map((s) => `${s.id}@${s.exchange}`));
179
+ return {
180
+ ok: true,
181
+ stocks: stocks.map(({ id, exchange, ...stock }) => ({ ...stock, underlying_contract_id: Number(id), ...(quoted.has(`${id}@${exchange}`) ? { quote: quoted.get(`${id}@${exchange}`) } : {}) })),
182
+ note: "Record a decision's IBKR trade with `symbol` exactly as given, and the stock's name as `title`. Prices are in the stock's own currency. For an option, call rkf_ibkr_option_chain with the stock's underlying_contract_id.",
183
+ };
184
+ });
185
+ }
186
+ /** A stock's option expirations, or the chain of one expiration with quotes. */
187
+ export async function ibkrOptionChain(input, deps) {
188
+ return await attempt(async () => {
189
+ const mcp = await opened(deps);
190
+ const params = asRecord(await mcp.call("get_option_parameters", { underlying_contract_id: input.underlyingContractId }));
191
+ const expirations = asList(params.expirations);
192
+ if (input.expiration === undefined) {
193
+ return { ok: true, expirations: expirations.map((e) => ({ date: e.date, monthly: e.regular === true, trading_class: e.trading_class })), note: "Call again with one `expiration` (YYYYMMDD) and a strike range for the chain." };
194
+ }
195
+ const sameDay = expirations.filter((e) => e.date === input.expiration);
196
+ // One date can carry several classes of contract: the standard one is the one named after the stock.
197
+ const chosen = sameDay.find((e) => e.regular === true) ?? sameDay.at(0);
198
+ if (!chosen || typeof chosen.id !== "string")
199
+ return { ok: false, reason: `There are no options on ${input.expiration}. Call without an expiration to list the dates.` };
200
+ const chain = asRecord(await mcp.call("get_option_data", { expiration_id: chosen.id, ...(input.minStrike !== undefined ? { min_strike: input.minStrike } : {}), ...(input.maxStrike !== undefined ? { max_strike: input.maxStrike } : {}) }));
201
+ const rows = asList(chain.contracts);
202
+ if (rows.length > 25)
203
+ return { ok: false, reason: `That range holds ${String(rows.length)} strikes; narrow min_strike and max_strike to 25 or fewer.` };
204
+ const quoted = await quotes(mcp, rows.flatMap((row) => [row.call_contract_id_ex, row.put_contract_id_ex]).filter((id) => typeof id === "string"));
205
+ const leg = (id, description) => {
206
+ if (typeof id !== "string")
207
+ return null;
208
+ const quote = quoted.has(id) ? { quote: quoted.get(id) } : {};
209
+ const multiplier = optionMultiplier(text(description));
210
+ if (multiplier === null)
211
+ return { title: description, tradable_here: false, why_not: "Interactive Brokers' description does not say how many shares one contract is", ...quote };
212
+ const symbol = `opt:${id}*${String(multiplier)}`;
213
+ const usable = readIbkrSymbol(symbol);
214
+ return { symbol, title: description, multiplier, ...("reason" in usable ? { tradable_here: false, why_not: usable.reason } : {}), ...quote };
215
+ };
216
+ return {
217
+ ok: true,
218
+ expiration: input.expiration,
219
+ trading_class: chosen.trading_class,
220
+ currency: chain.currency,
221
+ strikes: rows.map((row) => ({ strike: numberOf(row.strike), call: leg(row.call_contract_id_ex, row.call_description), put: leg(row.put_contract_id_ex, row.put_description) })),
222
+ note: "Record a decision's option trade with `symbol` and `title` exactly as given: the symbol carries the contract size. Its limit_price is the premium per share as quoted, in the chain's currency; one contract is `multiplier` shares, so a contract costs premium × multiplier (at 1.20 with 100 shares, 120; with 20 shares, 24), and size_usd must allow for that in US dollars.",
223
+ };
224
+ });
225
+ }
226
+ /** Whether an IBKR order status is final. PendingCancel is not: the order can still fill until the cancel goes through. */
227
+ function orderOver(status) {
228
+ const s = status.toUpperCase();
229
+ if (s.includes("PENDING"))
230
+ return false;
231
+ return s === "FILLED" || s === "REJECTED" || s === "EXPIRED" || s === "DONE_FOR_THE_DAY" || s.includes("CANCEL");
232
+ }
233
+ /**
234
+ * What the account holds of a contract (positive long, negative short), and
235
+ * what is waiting to change it: instructions not yet submitted, and orders
236
+ * still open. A position is checked against both, so two instructions that
237
+ * each sell what is held cannot together sell short.
238
+ */
239
+ async function exposure(mcp, contract, title) {
240
+ const positions = asList(asRecord(await mcp.call("get_account_positions")).positions).filter((p) => String(p.contract_id) === contract.conid);
241
+ const held = positions.reduce((sum, p) => sum + (numberOf(p.position) ?? 0), 0);
242
+ const signed = (side, quantity) => (side === "SELL" ? -quantity : quantity);
243
+ const waiting = asList(asRecord(await mcp.call("get_order_instructions")).instructions).filter((row) => String(row.contract_id) === contract.conid);
244
+ // An order names its contract only in words: a stock by the code its position carries, an option as the chain describes it.
245
+ const named = contract.kind === "stk" ? positions.map((p) => text(p.contract_description)).find(Boolean) : title.trim();
246
+ const open = named
247
+ ? asList(asRecord(await mcp.call("get_account_orders", { show_completed: false })).orders).filter((row) => !orderOver(text(row.order_status)) && orderContract(row) === named)
248
+ : [];
249
+ const pending = waiting.reduce((sum, row) => sum + signed(row.side, numberOf(row.quantity) ?? 0), 0)
250
+ + open.reduce((sum, row) => sum + signed(row.side, numberOf(row.remaining_shares_qty) ?? Math.max(0, (numberOf(row.total_shares_qty) ?? 0) - (numberOf(row.cum_shares_qty) ?? 0))), 0);
251
+ return { held, pending, waiting };
252
+ }
253
+ async function readMandate(deps) {
254
+ const reply = await fundCall(deps, "GET", "/agent/mandate");
255
+ if (reply.status !== 200)
256
+ throw new Error(`the Rethinka Fund server answered HTTP ${String(reply.status)} for the mandate`);
257
+ const instruments = asRecord(reply.body.instruments);
258
+ return { shortSelling: instruments.short_selling !== false, optionsBuy: instruments.options_buy !== false, optionsSell: instruments.options_sell !== false };
259
+ }
260
+ function noteInstruction(note) {
261
+ // The code is quoted: some have a space ("BRK B").
262
+ return `instruction ${note.id} created ${note.createdAt} for "${note.ibSymbol}"; waiting for the owner to submit it in IBKR`;
263
+ }
264
+ function readInstruction(order) {
265
+ if (!order.venue_order_id?.startsWith(INSTRUCTION))
266
+ return null;
267
+ // Quoted since codes with a space; unquoted as the first records were written.
268
+ const match = /instruction (\S+) created (\S+) for (?:"([^"]*)"|([^\s;]+))/.exec(order.detail ?? "");
269
+ if (!match)
270
+ return null;
271
+ const [, id, createdAt, quoted, bare] = match;
272
+ return { id, createdAt, ibSymbol: (quoted ?? bare ?? "").trim() };
273
+ }
274
+ /**
275
+ * Create an order instruction under a recorded decision. Never throws: every
276
+ * outcome is a result the model can read, with the reason when nothing was
277
+ * created.
278
+ */
279
+ export async function placeIbkrOrder(input, deps) {
280
+ return await attempt(async () => {
281
+ if (!ibkrMayStageOrders(deps.authFile ? { authFile: deps.authFile } : {})) {
282
+ return { ok: false, reason: "This agent's IBKR authorization only reads the account. Ask the owner to authorize it again with rkf_ibkr_authorize, which now asks for order instructions as well. Nothing was created." };
283
+ }
284
+ const trade = input.trade ?? 1;
285
+ const read = await readDecision(deps, input.decisionId, "ibkr", trade);
286
+ if ("reason" in read)
287
+ return { ok: false, reason: read.reason, ...read.extra };
288
+ const { permission } = read;
289
+ const { decision } = permission;
290
+ const contract = readIbkrSymbol(decision.symbol);
291
+ if ("reason" in contract)
292
+ return { ok: false, reason: `${tradeName(decision.id, trade)} cannot be traded: ${contract.reason}. Nothing was created.` };
293
+ if (!Number.isInteger(input.quantity) || input.quantity <= 0)
294
+ return { ok: false, reason: `The quantity is a whole number of ${contract.kind === "opt" ? "contracts" : "shares"}.` };
295
+ if (!(input.limitPrice > 0))
296
+ return { ok: false, reason: "The limit price must be positive." };
297
+ const limit = Number(decision.limit_price);
298
+ const side = decision.action === "sell" ? "SELL" : "BUY";
299
+ if (!Number.isFinite(limit) || limit <= 0)
300
+ return { ok: false, reason: `${tradeName(decision.id, trade)} has no limit price.` };
301
+ if (side === "BUY" ? input.limitPrice > limit : input.limitPrice < limit) {
302
+ return { ok: false, reason: `Price ${String(input.limitPrice)} is worse than the decision's limit of ${String(limit)} ${contract.currency} for a ${decision.action}. Record a new decision if the plan changed.` };
303
+ }
304
+ const mcp = await opened(deps);
305
+ const mandate = await readMandate(deps);
306
+ const account = await exposure(mcp, contract, decision.title);
307
+ // Two instructions of one contract and side waiting together could not be told apart once submitted.
308
+ const twin = account.waiting.find((row) => row.side === side);
309
+ if (twin)
310
+ return { ok: false, reason: `Instruction ${text(twin.id)} (${side === "SELL" ? "sell" : "buy"} ${text(twin.quantity)} of this contract) is already waiting for the owner. Wait until they have submitted or deleted it, or delete it with rkf_ibkr_delete_instruction if it is this decision's and no longer wanted. Nothing was created.` };
311
+ // What the account would hold once everything waiting and this order went through.
312
+ const position = account.held + account.pending;
313
+ const holds = account.pending === 0 ? `holds ${String(account.held)}` : `holds ${String(account.held)}, ${String(position)} once its open orders and instructions go through`;
314
+ // What the order would leave the account holding.
315
+ const after = position + (side === "BUY" ? input.quantity : -input.quantity);
316
+ // Reducing: the order takes the position toward nothing, and never past it.
317
+ const reduces = position !== 0 && Math.abs(after) < Math.abs(position) && (after === 0 || Math.sign(after) === Math.sign(position));
318
+ if (decision.reduce_only === true && !reduces) {
319
+ return { ok: false, reason: `${tradeName(decision.id, trade)} only reduces a position, and the account ${holds}: ${side === "BUY" ? "buying" : "selling"} ${String(input.quantity)} would not just reduce it.` };
320
+ }
321
+ if (contract.kind === "stk" && after < 0 && after < position && !mandate.shortSelling) {
322
+ return { ok: false, reason: `The account ${holds}; selling ${String(input.quantity)} would sell short, and the mandate does not allow short selling.` };
323
+ }
324
+ if (contract.kind === "opt" && side === "BUY" && after > 0 && after > position && !mandate.optionsBuy) {
325
+ return { ok: false, reason: "The mandate does not allow buying options." };
326
+ }
327
+ if (contract.kind === "opt" && side === "SELL" && after < 0 && !mandate.optionsSell) {
328
+ return { ok: false, reason: `The account ${holds} of this option; selling ${String(input.quantity)} would write options, and the mandate does not allow selling options.` };
329
+ }
330
+ const rate = await dollarRate(mcp, contract.currency);
331
+ const notional = Number(((input.limitPrice * input.quantity * contract.multiplier) / rate).toFixed(6));
332
+ if (notional > permission.remaining_usd + 1e-9) {
333
+ return { ok: false, reason: `This instruction is $${String(notional)} (${String(input.quantity)} × ${String(input.limitPrice)} ${contract.currency}${contract.multiplier > 1 ? ` × ${String(contract.multiplier)}` : ""}), but only $${String(permission.remaining_usd)} of ${tradeName(decision.id, trade)}'s size is left.` };
334
+ }
335
+ const clientId = (deps.newId ?? randomUUID)();
336
+ const report = (status, detail, venueOrderId) => reportOrder(deps, decision.id, { client_id: clientId, venue_order_id: venueOrderId, side: side === "SELL" ? "sell" : "buy", price: input.limitPrice, size: input.quantity, notional_usd: notional, status, detail }, trade);
337
+ // On record before Interactive Brokers is asked: if this process dies on the way, it still counts against the decision.
338
+ const preReport = await report("unknown", "creating an IBKR order instruction", null);
339
+ if (preReport !== null)
340
+ return { ok: false, reason: `The Rethinka Fund server did not take this order (${preReport}), so no instruction was created.` };
341
+ let created;
342
+ try {
343
+ created = asRecord(await mcp.call("create_order_instruction", { contract_id_ex: instructionContract(contract), side, quantity: input.quantity, order_type: "LIMIT", limit_price: input.limitPrice, time_in_force: input.timeInForce ?? "DAY" }));
344
+ }
345
+ catch (err) {
346
+ // Refused by Interactive Brokers: no instruction. Anything else (a timeout, a dropped connection) may have created one.
347
+ if (err instanceof IbkrToolError) {
348
+ await report("rejected", `the instruction was not created: ${errorText(err)}`, null);
349
+ return { ok: false, reason: `Interactive Brokers did not create the instruction: ${errorText(err)}` };
350
+ }
351
+ await report("unknown", `creating the instruction failed on the way, and it may exist: ${errorText(err)}`, null);
352
+ return { ok: false, unknown: true, reason: `Creating the instruction failed on the way (${errorText(err)}), so it may or may not exist. Its amount stays held. Ask the owner to look at their instructions in Interactive Brokers, and do not create it again until they have.` };
353
+ }
354
+ const id = typeof created.id === "string" || typeof created.id === "number" ? String(created.id) : null;
355
+ if (!id) {
356
+ await report("unknown", `Interactive Brokers answered without an instruction id: ${JSON.stringify(created).slice(0, 200)}`, null);
357
+ return { ok: false, reason: "Interactive Brokers answered without saying which instruction it created. Check rkf_ibkr_refresh_orders and tell the owner.", unknown: true };
358
+ }
359
+ // What the instruction is called there, and when it was made: the order it becomes is matched by them.
360
+ // A listing that fails now must not leave the instruction off the record: what is known is written regardless.
361
+ const listed = asList(asRecord(await mcp.call("get_order_instructions").catch(() => ({}))).instructions).find((row) => String(row.id) === id);
362
+ const note = {
363
+ id,
364
+ createdAt: typeof listed?.creation_time === "string" ? listed.creation_time : new Date((deps.now ?? Date.now)()).toISOString(),
365
+ // Unknown when the listing failed: the order is then not looked for by guesswork, the owner is asked.
366
+ ibSymbol: typeof listed?.symbol === "string" ? listed.symbol.trim() : "",
367
+ };
368
+ const reportError = await report("awaiting_owner", noteInstruction(note), `${INSTRUCTION}${id}`);
369
+ return {
370
+ ok: true,
371
+ instruction_id: id,
372
+ owner_link: typeof created.url === "string" ? created.url : null,
373
+ decision_id: decision.id,
374
+ trade,
375
+ side: decision.action,
376
+ quantity: input.quantity,
377
+ limit_price: input.limitPrice,
378
+ currency: contract.currency,
379
+ notional_usd: notional,
380
+ note: "This is an instruction, not an order: nothing trades until the owner submits it in Interactive Brokers. Send the owner owner_link and say what the instruction is (side, quantity, contract, limit, how long it is good for). It disappears unsubmitted after a week. Once the owner has submitted it, call rkf_ibkr_refresh_orders to find the order and what it filled. Do not create the same instruction again while this one waits."
381
+ + (reportError ? ` The instruction could not be written back to the Rethinka Fund server (${reportError}); tell the owner.` : ""),
382
+ };
383
+ });
384
+ }
385
+ /** An IBKR order status, as the record holds statuses. */
386
+ function orderStatus(status, filled, total) {
387
+ const s = status.toUpperCase();
388
+ const working = filled > 0 && !fullyFilled(total, filled) ? "partially_filled" : "submitted";
389
+ if (s === "FILLED")
390
+ return "filled";
391
+ // PendingCancel, PendingSubmit: the order can still trade.
392
+ if (s.includes("PENDING"))
393
+ return working;
394
+ // Over with part of it filled: the record keeps what filled beside a cancelled order.
395
+ if (s.includes("CANCEL") || s === "DONE_FOR_THE_DAY")
396
+ return "cancelled";
397
+ if (s === "EXPIRED")
398
+ return filled > 0 ? "cancelled" : "expired";
399
+ if (s === "REJECTED")
400
+ return filled > 0 ? "cancelled" : "rejected";
401
+ // Inactive and anything else: Interactive Brokers holds the order and may work it again.
402
+ return working;
403
+ }
404
+ /** `Sell 500 7709` → what the order says about itself. */
405
+ function described(row) {
406
+ return typeof row.primary_description === "string" ? row.primary_description : "";
407
+ }
408
+ /** The contract an order's description names: `Sell 500 7709` → `7709`, `Buy 1 100 (MNX) ... Call (20) @SEHK` → `100 (MNX) ... Call (20) @SEHK`. */
409
+ function orderContract(row) {
410
+ return /^(?:buy|sell)\s+[\d.,]+\s+(.+)$/i.exec(described(row).trim())?.[1]?.trim() ?? "";
411
+ }
412
+ /** Whether an order's description names an option on a stock: `100 (MNX) DEC 30 '26 100 Call (20) @SEHK` on `100`. */
413
+ function optionOn(row, stockCode) {
414
+ const named = orderContract(row);
415
+ return named.startsWith(`${stockCode} `) && /\b(Call|Put)\b/.test(named);
416
+ }
417
+ /**
418
+ * Bring the orders under one decision up to date with Interactive Brokers:
419
+ * which order each instruction became, and what it has filled.
420
+ */
421
+ export async function refreshIbkrOrders(input, deps) {
422
+ let mcp = null;
423
+ let instructions = null;
424
+ let orders = null;
425
+ let trades = null;
426
+ const rates = new Map();
427
+ const connect = async () => (mcp ??= await opened(deps));
428
+ const readInstructions = async () => await (instructions ??= connect().then(async (m) => asList(asRecord(await m.call("get_order_instructions")).instructions)));
429
+ const readOrders = async () => await (orders ??= connect().then(async (m) => asList(asRecord(await m.call("get_account_orders", { show_completed: true })).orders)));
430
+ const readTrades = async () => await (trades ??= connect().then(async (m) => asList(asRecord(await m.call("get_account_trades", { period: "DAYS_7" })).trades)));
431
+ const rate = async (currency) => {
432
+ let found = rates.get(currency);
433
+ if (!found) {
434
+ found = connect().then((m) => dollarRate(m, currency));
435
+ rates.set(currency, found);
436
+ }
437
+ return await found;
438
+ };
439
+ // Orders already taken by this decision's other instructions, so two are never matched to one order.
440
+ const claimed = new Set();
441
+ if (!ibkrMayStageOrders(deps.authFile ? { authFile: deps.authFile } : {})) {
442
+ return { ok: false, reason: "This agent's IBKR authorization only reads the account, and order instructions cannot be matched without reading them. Ask the owner to authorize it again with rkf_ibkr_authorize." };
443
+ }
444
+ return await refreshDecisionOrders(deps, input.decisionId, "ibkr", deps.now ?? Date.now, async (order, decision) => {
445
+ const contract = readIbkrSymbol(decision.symbol);
446
+ if ("reason" in contract)
447
+ return { skipped: contract.reason };
448
+ const side = order.side === "sell" ? "SELL" : "BUY";
449
+ const secType = contract.kind === "opt" ? "OPT" : "STK";
450
+ /** Whether an order is of this decision's contract and of this order's side. */
451
+ const ofThis = (row, ibSymbol) => row.side === side && (contract.kind === "stk" ? orderContract(row) === ibSymbol : orderContract(row) === decision.title.trim());
452
+ /** Whether an order or a trade is of this side and of the stock (for an option, of any option on it). */
453
+ const onStock = (row, ibSymbol) => row.side === side && (contract.kind === "stk" ? orderContract(row) === ibSymbol : optionOn(row, ibSymbol));
454
+ const tradeOf = (row, ibSymbol) => row.side === side && row.symbol === ibSymbol && (row.sec_type === undefined || row.sec_type === secType);
455
+ /** Whether something happened after a time. A time that cannot be read counts as after: it is looked at, not passed over. */
456
+ const after = (time, since) => !(Date.parse(text(time)) < since - 1000);
457
+ for (const other of decision.orders ?? [])
458
+ if (other.venue_order_id && !other.venue_order_id.startsWith(INSTRUCTION))
459
+ claimed.add(other.venue_order_id);
460
+ let orderId = order.venue_order_id && !order.venue_order_id.startsWith(INSTRUCTION) ? order.venue_order_id : null;
461
+ let changed = "";
462
+ if (orderId === null) {
463
+ const instruction = readInstruction(order);
464
+ if (!instruction)
465
+ return { skipped: "no IBKR instruction or order id is on record for it; tell the owner" };
466
+ if ((await readInstructions()).some((row) => String(row.id) === instruction.id)) {
467
+ // A submission Interactive Brokers refused leaves the instruction where it was, and a rejected order beside it.
468
+ const since = Date.parse(instruction.createdAt);
469
+ const refused = (await readOrders()).filter((row) => text(row.order_status).toUpperCase() === "REJECTED" && after(row.order_time, since) && ofThis(row, instruction.ibSymbol));
470
+ const why = refused.map((row) => text(row.reject_reason)).filter(Boolean).at(-1);
471
+ if (refused.length > 0)
472
+ return { skipped: `the owner submitted instruction ${instruction.id} and Interactive Brokers rejected it${why ? ` (${why})` : ""}; it is still waiting. Tell the owner why, and delete it with rkf_ibkr_delete_instruction if it will not be submitted again` };
473
+ return { skipped: `instruction ${instruction.id} is still waiting for the owner to submit it in IBKR` };
474
+ }
475
+ // The instruction is gone: submitted, deleted or expired. The owner has said which order it became, or it is looked for.
476
+ if (input.confirm?.instructionId === instruction.id) {
477
+ if (input.confirm.orderId === "none")
478
+ return { status: "not_executed", filled_size: 0, filled_notional_usd: 0, detail: `instruction ${instruction.id} became no order, as the owner said: deleted or expired` };
479
+ // What the owner said is checked: an order of this stock and side, not already another's under this decision.
480
+ const confirmed = input.confirm.orderId;
481
+ const itsRow = (await readOrders()).find((row) => String(row.order_id) === confirmed);
482
+ const itsTrades = (await readTrades()).filter((row) => String(row.order_id) === confirmed);
483
+ const fitsStock = itsRow ? onStock(itsRow, instruction.ibSymbol) : itsTrades.length > 0 && itsTrades.every((row) => tradeOf(row, instruction.ibSymbol));
484
+ if (claimed.has(confirmed))
485
+ return { skipped: `order ${confirmed} is already recorded under this decision for another instruction; check the id with the owner` };
486
+ if (!instruction.ibSymbol || !fitsStock)
487
+ return { skipped: `order ${confirmed} is not among today's orders or this week's trades as a ${side === "SELL" ? "sale" : "purchase"} of this ${contract.kind === "opt" ? "stock's options" : "stock"}; check the id with the owner` };
488
+ orderId = confirmed;
489
+ changed = "; the owner said this order is the instruction";
490
+ }
491
+ }
492
+ if (orderId === null) {
493
+ const instruction = readInstruction(order);
494
+ if (!instruction)
495
+ return { skipped: "no IBKR instruction is on record for it" };
496
+ const since = Date.parse(instruction.createdAt);
497
+ const ask = (what) => ({ skipped: `instruction ${instruction.id} is gone, and ${what}. Ask the owner which order it became, then call again with confirm: { instruction_id: "${instruction.id}", order_id: <that order's id, or "none" if they deleted it> }. Until then the decision is not up to date` });
498
+ // Without the code Interactive Brokers gave the instruction, no order can be told to be it, nor that none is.
499
+ if (!instruction.ibSymbol)
500
+ return ask("what Interactive Brokers called its contract was not recorded when it was created");
501
+ const recent = (await readOrders()).filter((row) => row.side === side && !claimed.has(String(row.order_id)) && after(row.order_time, since));
502
+ const candidates = recent.filter((row) => ofThis(row, instruction.ibSymbol));
503
+ const sameSize = (row) => numberOf(row.total_shares_qty) === order.size;
504
+ const sameLimit = (row) => numberOf(row.limit_price) === order.price;
505
+ const listed = (rows) => rows.map((row) => `${String(row.order_id)} (${described(row)}, ${text(row.secondary_description)})`).join("; ");
506
+ const exact = candidates.filter((row) => sameSize(row) && sameLimit(row));
507
+ // Changed before submitting: the owner kept the quantity or the price. An order that shares neither may be one the
508
+ // owner placed by hand after deleting the instruction, and is not taken without asking.
509
+ const changedOne = candidates.filter((row) => sameSize(row) || sameLimit(row));
510
+ if (exact.length > 1)
511
+ return ask(`more than one order could be it: ${listed(exact)}`);
512
+ const match = exact.length === 1 ? exact[0] : changedOne.length === 1 ? changedOne[0] : null;
513
+ if (match) {
514
+ orderId = String(match.order_id);
515
+ if (exact.length === 0)
516
+ changed = `; the owner changed it before submitting (now ${described(match)}, ${text(match.secondary_description)})`;
517
+ }
518
+ else if (candidates.length > 0) {
519
+ return ask(`${changedOne.length > 1 ? "more than one order could be it" : "no order matches its quantity or its price, though these are of the same contract and side"}: ${listed(changedOne.length > 1 ? changedOne : candidates)}`);
520
+ }
521
+ else if (contract.kind === "opt" && recent.some((row) => optionOn(row, instruction.ibSymbol))) {
522
+ // An option order on the same stock whose description is not the decision's title: perhaps the same contract, named otherwise.
523
+ return ask(`no order names "${decision.title}", though these are options on the same stock: ${listed(recent.filter((row) => optionOn(row, instruction.ibSymbol)))}`);
524
+ }
525
+ else {
526
+ // Not among today's orders: one that has traded since shows in the trades. It is taken when what it traded fits the
527
+ // instruction (no more than its quantity, and at its price or better); anything else is asked about.
528
+ const traded = (await readTrades()).filter((row) => tradeOf(row, instruction.ibSymbol) && after(row.trade_time, since) && !claimed.has(String(row.order_id)));
529
+ const ids = [...new Set(traded.map((row) => String(row.order_id)))];
530
+ if (ids.length === 0)
531
+ return { status: "not_executed", filled_size: 0, filled_notional_usd: 0, detail: `instruction ${instruction.id} is gone and no order or trade came of it: the owner deleted it, or it expired` };
532
+ // An option's trades name only the stock, not which option: every option on it looks the same there.
533
+ if (contract.kind === "opt")
534
+ return ask(`option trades on the same stock came since (orders ${ids.join(", ")}), and the trades do not say which option`);
535
+ const fits = (id) => {
536
+ const its = traded.filter((row) => String(row.order_id) === id);
537
+ const size = its.reduce((sum, row) => sum + Math.abs(numberOf(row.size) ?? 0), 0);
538
+ const atLimit = its.every((row) => { const price = numberOf(row.price) ?? Number.NaN; return side === "SELL" ? price >= order.price - 1e-9 : price <= order.price + 1e-9; });
539
+ return size <= order.size + 1e-9 && atLimit;
540
+ };
541
+ const fitting = ids.filter(fits);
542
+ if (fitting.length !== 1)
543
+ return ask(`trades of ${ids.length > 1 ? "more than one order" : "an order that does not fit it"} came since (${ids.join(", ")})`);
544
+ orderId = fitting[0] ?? null;
545
+ }
546
+ }
547
+ claimed.add(orderId);
548
+ // The order's state today, and what it has traded by its own id.
549
+ const row = (await readOrders()).find((r) => String(r.order_id) === orderId);
550
+ const fills = (await readTrades()).filter((t) => String(t.order_id) === orderId);
551
+ const tradedSize = fills.reduce((sum, t) => sum + Math.abs(numberOf(t.size) ?? 0), 0);
552
+ const tradedAmount = fills.reduce((sum, t) => sum + Math.abs(numberOf(t.net_amount) ?? (numberOf(t.size) ?? 0) * (numberOf(t.price) ?? 0) * contract.multiplier), 0);
553
+ const total = numberOf(row?.total_shares_qty) ?? order.size;
554
+ // What filled never shrinks: an order gone from today's list, whose trades have aged out of the week, still filled what it filled.
555
+ const recorded = order.venue_order_id === orderId ? order.filled_size ?? 0 : 0;
556
+ const filled = Math.max(numberOf(row?.cum_shares_qty) ?? 0, tradedSize, recorded);
557
+ // The trades may lag the order: what they do not cover yet is valued at the order's limit.
558
+ const amount = tradedAmount + Math.max(0, filled - tradedSize) * (numberOf(row?.limit_price) ?? order.price) * contract.multiplier;
559
+ const notionalUsd = Math.max(amount / (await rate(contract.currency)), order.venue_order_id === orderId ? order.filled_notional_usd ?? 0 : 0);
560
+ // An order not among today's is over: what traded of it is in the trades.
561
+ const status = row ? orderStatus(text(row.order_status), filled, total) : fullyFilled(total, filled) ? "filled" : "cancelled";
562
+ return {
563
+ venue_order_id: orderId,
564
+ status,
565
+ filled_size: filled,
566
+ filled_notional_usd: notionalUsd,
567
+ detail: `IBKR order ${orderId}${row ? `: ${text(row.order_status)}, ${described(row)}, ${text(row.secondary_description)}` : ": no longer among today's orders"}${filled > 0 ? `, filled ${String(filled)}` : ""}${changed}`,
568
+ };
569
+ });
570
+ }
571
+ /** Delete an instruction the owner has not submitted yet, and record it as cancelled. */
572
+ export async function deleteIbkrInstruction(input, deps) {
573
+ return await attempt(async () => {
574
+ const trade = input.trade ?? 1;
575
+ const reply = await fundCall(deps, "GET", tradeRoute(input.decisionId, trade));
576
+ if (reply.status !== 200)
577
+ return { ok: false, reason: `${tradeName(input.decisionId, trade)} could not be read (HTTP ${String(reply.status)}).` };
578
+ const decision = reply.body.decision;
579
+ const order = (decision.orders ?? []).find((o) => o.venue_order_id === `${INSTRUCTION}${input.instructionId}`);
580
+ if (!order)
581
+ return { ok: false, reason: `${tradeName(input.decisionId, trade)} has no instruction ${input.instructionId} waiting. Read it with rk_get_decision.` };
582
+ const mcp = await opened(deps);
583
+ if (!asList(asRecord(await mcp.call("get_order_instructions")).instructions).some((row) => String(row.id) === input.instructionId)) {
584
+ return { ok: false, reason: `Instruction ${input.instructionId} is no longer waiting: the owner submitted or deleted it, or it expired. Call rkf_ibkr_refresh_orders to find out which; an order the owner submitted can only be cancelled by them, in Interactive Brokers.` };
585
+ }
586
+ await mcp.call("delete_order_instruction", { id: input.instructionId });
587
+ const failed = await reportOrder(deps, input.decisionId, {
588
+ client_id: order.client_id, venue_order_id: order.venue_order_id, side: order.side, price: order.price, size: order.size, notional_usd: order.notional_usd,
589
+ status: "cancelled", filled_size: 0, filled_notional_usd: 0, detail: `instruction ${input.instructionId} deleted before the owner submitted it`,
590
+ }, trade);
591
+ return { ok: true, deleted: input.instructionId, ...(failed ? { not_recorded: `the Rethinka Fund server did not take the update (${failed}); tell the owner` } : {}) };
592
+ });
593
+ }
594
+ //# sourceMappingURL=ibkr-trading.js.map