opentradex 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.env.example +8 -0
  2. package/CLAUDE.md +98 -0
  3. package/README.md +246 -0
  4. package/SOUL.md +79 -0
  5. package/SPEC.md +317 -0
  6. package/SUBMISSION.md +30 -0
  7. package/architecture.excalidraw +170 -0
  8. package/architecture.png +0 -0
  9. package/bin/opentradex.mjs +4 -0
  10. package/data/.gitkeep +0 -0
  11. package/data/strategy_notes.md +158 -0
  12. package/gossip/__init__.py +0 -0
  13. package/gossip/dashboard.py +150 -0
  14. package/gossip/db.py +358 -0
  15. package/gossip/kalshi.py +492 -0
  16. package/gossip/news.py +235 -0
  17. package/gossip/trader.py +646 -0
  18. package/main.py +287 -0
  19. package/package.json +47 -0
  20. package/requirements.txt +7 -0
  21. package/src/cli.mjs +124 -0
  22. package/src/index.mjs +420 -0
  23. package/web/AGENTS.md +5 -0
  24. package/web/CLAUDE.md +1 -0
  25. package/web/README.md +36 -0
  26. package/web/components.json +25 -0
  27. package/web/eslint.config.mjs +18 -0
  28. package/web/next.config.ts +7 -0
  29. package/web/package-lock.json +11626 -0
  30. package/web/package.json +37 -0
  31. package/web/postcss.config.mjs +7 -0
  32. package/web/public/file.svg +1 -0
  33. package/web/public/globe.svg +1 -0
  34. package/web/public/next.svg +1 -0
  35. package/web/public/vercel.svg +1 -0
  36. package/web/public/window.svg +1 -0
  37. package/web/src/app/api/agent/route.ts +77 -0
  38. package/web/src/app/api/agent/stream/route.ts +87 -0
  39. package/web/src/app/api/markets/route.ts +15 -0
  40. package/web/src/app/api/news/live/route.ts +77 -0
  41. package/web/src/app/api/news/reddit/route.ts +118 -0
  42. package/web/src/app/api/news/route.ts +10 -0
  43. package/web/src/app/api/news/tiktok/route.ts +115 -0
  44. package/web/src/app/api/news/truthsocial/route.ts +116 -0
  45. package/web/src/app/api/news/twitter/route.ts +186 -0
  46. package/web/src/app/api/portfolio/route.ts +50 -0
  47. package/web/src/app/api/prices/route.ts +18 -0
  48. package/web/src/app/api/trades/route.ts +10 -0
  49. package/web/src/app/favicon.ico +0 -0
  50. package/web/src/app/globals.css +170 -0
  51. package/web/src/app/layout.tsx +36 -0
  52. package/web/src/app/page.tsx +366 -0
  53. package/web/src/components/AgentLog.tsx +71 -0
  54. package/web/src/components/LiveStream.tsx +394 -0
  55. package/web/src/components/MarketScanner.tsx +111 -0
  56. package/web/src/components/NewsFeed.tsx +561 -0
  57. package/web/src/components/PortfolioStrip.tsx +139 -0
  58. package/web/src/components/PositionsPanel.tsx +219 -0
  59. package/web/src/components/TopBar.tsx +127 -0
  60. package/web/src/components/ui/badge.tsx +52 -0
  61. package/web/src/components/ui/button.tsx +60 -0
  62. package/web/src/components/ui/card.tsx +103 -0
  63. package/web/src/components/ui/scroll-area.tsx +55 -0
  64. package/web/src/components/ui/separator.tsx +25 -0
  65. package/web/src/components/ui/tabs.tsx +82 -0
  66. package/web/src/components/ui/tooltip.tsx +66 -0
  67. package/web/src/lib/db.ts +81 -0
  68. package/web/src/lib/types.ts +130 -0
  69. package/web/src/lib/utils.ts +6 -0
  70. package/web/tsconfig.json +34 -0
package/src/index.mjs ADDED
@@ -0,0 +1,420 @@
1
+ import { cpSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import process from "node:process";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
10
+ const CONFIG_DIR = path.join(homedir(), ".opentradex");
11
+ const CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
12
+ const DEFAULT_WORKSPACE = path.join(homedir(), "opentradex");
13
+
14
+ const PROJECT_TEMPLATE_ENTRIES = [
15
+ ".env.example",
16
+ ".gitignore",
17
+ "README.md",
18
+ "CLAUDE.md",
19
+ "SOUL.md",
20
+ "SPEC.md",
21
+ "SUBMISSION.md",
22
+ "architecture.excalidraw",
23
+ "architecture.png",
24
+ "main.py",
25
+ "requirements.txt",
26
+ "gossip",
27
+ "data",
28
+ "web"
29
+ ];
30
+
31
+ const DEFAULT_ENV = {
32
+ KALSHI_API_KEY_ID: "",
33
+ KALSHI_PRIVATE_KEY_PATH: "",
34
+ KALSHI_USE_DEMO: "true",
35
+ APIFY_API_TOKEN: "",
36
+ BANKROLL: "30.00",
37
+ MIN_EDGE: "0.10",
38
+ MAX_POSITION_PCT: "0.30",
39
+ CYCLE_INTERVAL: "900",
40
+ LIVE_TRADING: "false"
41
+ };
42
+
43
+ export function getPackageRoot() {
44
+ return PACKAGE_ROOT;
45
+ }
46
+
47
+ export function getDefaultWorkspace() {
48
+ return DEFAULT_WORKSPACE;
49
+ }
50
+
51
+ export function readTradexConfig() {
52
+ return readJson(CONFIG_PATH, {});
53
+ }
54
+
55
+ export function writeTradexConfig(config) {
56
+ ensureDir(path.dirname(CONFIG_PATH));
57
+ writeFileSync(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`, "utf8");
58
+ }
59
+
60
+ export function resolveWorkspace(workspace) {
61
+ const savedWorkspace = readTradexConfig().workspace;
62
+ return path.resolve(workspace || savedWorkspace || DEFAULT_WORKSPACE);
63
+ }
64
+
65
+ export function parseEnv(text) {
66
+ const values = {};
67
+
68
+ for (const rawLine of text.split(/\r?\n/)) {
69
+ const line = rawLine.trim();
70
+ if (!line || line.startsWith("#")) {
71
+ continue;
72
+ }
73
+
74
+ const separatorIndex = line.indexOf("=");
75
+ if (separatorIndex === -1) {
76
+ continue;
77
+ }
78
+
79
+ const key = line.slice(0, separatorIndex).trim();
80
+ const value = line.slice(separatorIndex + 1).trim();
81
+ values[key] = value.replace(/^"(.*)"$/, "$1");
82
+ }
83
+
84
+ return values;
85
+ }
86
+
87
+ export function buildEnv(overrides = {}) {
88
+ const env = { ...DEFAULT_ENV };
89
+
90
+ for (const [key, value] of Object.entries(overrides)) {
91
+ if (value === undefined || value === null) {
92
+ continue;
93
+ }
94
+ env[key] = String(value);
95
+ }
96
+
97
+ return env;
98
+ }
99
+
100
+ export function writeEnvFile(workspace, overrides = {}) {
101
+ const envPath = path.join(workspace, ".env");
102
+ const current = existsSync(envPath) ? parseEnv(readFileSync(envPath, "utf8")) : {};
103
+ const env = buildEnv({ ...current, ...overrides });
104
+
105
+ const lines = [
106
+ "# Generated by opentradex onboard",
107
+ "# Run `opentradex doctor` to verify your setup.",
108
+ "",
109
+ ...Object.entries(env).map(([key, value]) => `${key}=${value}`)
110
+ ];
111
+
112
+ writeFileSync(envPath, `${lines.join("\n")}\n`, "utf8");
113
+ return env;
114
+ }
115
+
116
+ export function ensureWorkspaceFiles(workspace, options = {}) {
117
+ ensureDir(workspace);
118
+
119
+ for (const entry of PROJECT_TEMPLATE_ENTRIES) {
120
+ const src = path.join(PACKAGE_ROOT, entry);
121
+ const dest = path.join(workspace, entry);
122
+
123
+ if (!existsSync(src)) {
124
+ continue;
125
+ }
126
+
127
+ if (statSync(src).isDirectory()) {
128
+ cpSync(src, dest, { recursive: true, force: Boolean(options.force) });
129
+ continue;
130
+ }
131
+
132
+ if (!existsSync(dest) || options.force) {
133
+ ensureDir(path.dirname(dest));
134
+ copyFileSync(src, dest);
135
+ }
136
+ }
137
+
138
+ ensureDir(path.join(workspace, "data"));
139
+ }
140
+
141
+ export function collectDoctor(workspaceArg) {
142
+ const workspace = resolveWorkspace(workspaceArg);
143
+ const envPath = path.join(workspace, ".env");
144
+ const env = existsSync(envPath) ? parseEnv(readFileSync(envPath, "utf8")) : {};
145
+ const config = readTradexConfig();
146
+ const liveTrading = String(env.LIVE_TRADING || "").toLowerCase() === "true";
147
+
148
+ return {
149
+ workspace,
150
+ checks: [
151
+ check("Node.js", commandWorks("node", ["-v"]), "Install Node.js 22+."),
152
+ check("npm", commandWorks("npm", ["-v"]), "Install npm or use the Node.js installer."),
153
+ check("Python", commandWorks("python", ["--version"]), "Install Python 3.11+."),
154
+ check("Claude CLI", commandWorks("claude", ["--version"]), "Install and sign in to Claude Code."),
155
+ check("Workspace", existsSync(path.join(workspace, "main.py")), "Run `opentradex onboard` to create a workspace."),
156
+ check(".env", existsSync(envPath), "Run `opentradex onboard` to generate `.env`."),
157
+ check("APIFY_API_TOKEN", Boolean(env.APIFY_API_TOKEN), "Add your Apify token for news scraping."),
158
+ check(
159
+ "Kalshi creds",
160
+ !liveTrading || (Boolean(env.KALSHI_API_KEY_ID) && Boolean(env.KALSHI_PRIVATE_KEY_PATH)),
161
+ "Set KALSHI_API_KEY_ID and KALSHI_PRIVATE_KEY_PATH for live trading."
162
+ ),
163
+ check("Saved workspace", Boolean(config.workspace), "Run `opentradex onboard` once so the CLI remembers your workspace.")
164
+ ]
165
+ };
166
+ }
167
+
168
+ export async function onboard(options = {}) {
169
+ const saved = readTradexConfig();
170
+ const interactive = process.stdin.isTTY && !options.yes;
171
+ const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : null;
172
+
173
+ try {
174
+ const workspace = path.resolve(
175
+ options.workspace ||
176
+ (interactive
177
+ ? await ask(rl, "Workspace directory", saved.workspace || DEFAULT_WORKSPACE)
178
+ : saved.workspace || DEFAULT_WORKSPACE)
179
+ );
180
+
181
+ const mode =
182
+ options.live ? "live" : options.paper ? "paper" : interactive ? await chooseMode(rl, saved.mode || "paper") : saved.mode || "paper";
183
+
184
+ const bankroll =
185
+ options.bankroll ??
186
+ (interactive ? await ask(rl, "Starting bankroll (USD)", String(saved.bankroll || DEFAULT_ENV.BANKROLL)) : saved.bankroll || DEFAULT_ENV.BANKROLL);
187
+
188
+ const interval =
189
+ options.interval ??
190
+ (interactive
191
+ ? await ask(rl, "Loop interval in seconds", String(saved.interval || DEFAULT_ENV.CYCLE_INTERVAL))
192
+ : saved.interval || DEFAULT_ENV.CYCLE_INTERVAL);
193
+
194
+ const installDeps =
195
+ options.install ?? (options.skipInstall ? false : interactive ? await confirm(rl, "Install Python and web dependencies now", true) : true);
196
+
197
+ const apifyToken =
198
+ options.apifyToken ??
199
+ (interactive ? await ask(rl, "Apify API token", saved.apifyToken || "") : saved.apifyToken || "");
200
+
201
+ const kalshiKeyId =
202
+ mode === "live"
203
+ ? options.kalshiKeyId ??
204
+ (interactive ? await ask(rl, "Kalshi API key id", saved.kalshiKeyId || "") : saved.kalshiKeyId || "")
205
+ : "";
206
+
207
+ const kalshiPrivateKeyPath =
208
+ mode === "live"
209
+ ? options.kalshiPrivateKeyPath ??
210
+ (interactive
211
+ ? await ask(rl, "Kalshi private key path", saved.kalshiPrivateKeyPath || "")
212
+ : saved.kalshiPrivateKeyPath || "")
213
+ : "";
214
+
215
+ const workspaceExists = existsSync(path.join(workspace, "main.py"));
216
+ if (interactive && workspaceExists && !(await confirm(rl, `Reuse existing workspace at ${workspace}`, true))) {
217
+ throw new Error("Onboarding cancelled.");
218
+ }
219
+
220
+ ensureWorkspaceFiles(workspace, { force: Boolean(options.force) });
221
+
222
+ const env = writeEnvFile(workspace, {
223
+ APIFY_API_TOKEN: apifyToken,
224
+ BANKROLL: Number(bankroll).toFixed(2),
225
+ CYCLE_INTERVAL: String(interval),
226
+ KALSHI_USE_DEMO: mode === "live" ? "false" : "true",
227
+ LIVE_TRADING: mode === "live" ? "true" : "false",
228
+ KALSHI_API_KEY_ID: kalshiKeyId,
229
+ KALSHI_PRIVATE_KEY_PATH: kalshiPrivateKeyPath
230
+ });
231
+
232
+ writeTradexConfig({
233
+ workspace,
234
+ mode,
235
+ bankroll: Number(bankroll).toFixed(2),
236
+ interval: Number(interval),
237
+ apifyToken,
238
+ kalshiKeyId,
239
+ kalshiPrivateKeyPath,
240
+ installedAt: new Date().toISOString()
241
+ });
242
+
243
+ if (installDeps) {
244
+ await runCommand("python", ["-m", "pip", "install", "-r", "requirements.txt"], { cwd: workspace });
245
+ await runCommand("npm", ["install"], { cwd: path.join(workspace, "web") });
246
+ }
247
+
248
+ return {
249
+ workspace,
250
+ mode,
251
+ env,
252
+ interval: Number(interval),
253
+ installDeps
254
+ };
255
+ } finally {
256
+ rl?.close();
257
+ }
258
+ }
259
+
260
+ export async function runTradingLoop(options = {}) {
261
+ const workspace = resolveWorkspace(options.workspace);
262
+ const config = readTradexConfig();
263
+ const args = ["main.py", "--loop"];
264
+
265
+ if (options.interval || config.interval) {
266
+ args.push("--interval", String(options.interval || config.interval));
267
+ }
268
+
269
+ if (options.rationale) {
270
+ args.push("--rationale", options.rationale);
271
+ }
272
+
273
+ await runCommand("python", args, { cwd: workspace });
274
+ }
275
+
276
+ export async function runSingleCycle(options = {}) {
277
+ const workspace = resolveWorkspace(options.workspace);
278
+ const args = ["main.py"];
279
+
280
+ if (options.rationale) {
281
+ args.push("--rationale", options.rationale);
282
+ }
283
+
284
+ if (options.prompt) {
285
+ args.push("--prompt", options.prompt);
286
+ }
287
+
288
+ await runCommand("python", args, { cwd: workspace });
289
+ }
290
+
291
+ export async function runDashboard(options = {}) {
292
+ const workspace = resolveWorkspace(options.workspace);
293
+ const webDir = path.join(workspace, "web");
294
+
295
+ if (options.install) {
296
+ await runCommand("npm", ["install"], { cwd: webDir });
297
+ }
298
+
299
+ await runCommand("npm", ["run", "dev"], { cwd: webDir });
300
+ }
301
+
302
+ export function formatDoctorReport(report) {
303
+ const lines = ["OpenTradex doctor", `workspace: ${report.workspace}`, ""];
304
+
305
+ for (const item of report.checks) {
306
+ lines.push(`${item.ok ? "[ok]" : "[warn]"} ${item.name}`);
307
+ if (!item.ok) {
308
+ lines.push(` ${item.help}`);
309
+ }
310
+ }
311
+
312
+ return lines.join("\n");
313
+ }
314
+
315
+ function readJson(filePath, fallback) {
316
+ try {
317
+ return JSON.parse(readFileSync(filePath, "utf8"));
318
+ } catch {
319
+ return fallback;
320
+ }
321
+ }
322
+
323
+ function ensureDir(dirPath) {
324
+ mkdirSync(dirPath, { recursive: true });
325
+ }
326
+
327
+ function check(name, ok, help) {
328
+ return { name, ok, help };
329
+ }
330
+
331
+ function commandWorks(command, args) {
332
+ if (process.platform === "win32") {
333
+ const result = spawnSync("where.exe", [command], { stdio: "ignore" });
334
+ return !result.error && result.status === 0;
335
+ }
336
+
337
+ for (const candidate of getCommandCandidates(command)) {
338
+ const result = spawnSync(candidate, args, { stdio: "ignore" });
339
+ if (!result.error && result.status === 0) {
340
+ return true;
341
+ }
342
+ }
343
+ return false;
344
+ }
345
+
346
+ async function runCommand(command, args, options = {}) {
347
+ await new Promise((resolve, reject) => {
348
+ const spec = getSpawnSpec(command, args);
349
+ const child = spawn(spec.command, spec.args, {
350
+ cwd: options.cwd,
351
+ stdio: "inherit",
352
+ env: { ...process.env, ...(options.env || {}) }
353
+ });
354
+
355
+ child.on("error", reject);
356
+ child.on("exit", (code) => {
357
+ if (code === 0) {
358
+ resolve();
359
+ return;
360
+ }
361
+ reject(new Error(`${command} ${args.join(" ")} exited with code ${code}`));
362
+ });
363
+ });
364
+ }
365
+
366
+ async function ask(rl, label, fallback = "") {
367
+ const prompt = fallback ? `${label} [${fallback}]: ` : `${label}: `;
368
+ const answer = (await rl.question(prompt)).trim();
369
+ return answer || fallback;
370
+ }
371
+
372
+ async function confirm(rl, label, defaultYes = true) {
373
+ const hint = defaultYes ? "[Y/n]" : "[y/N]";
374
+ const answer = (await rl.question(`${label} ${hint}: `)).trim().toLowerCase();
375
+ if (!answer) {
376
+ return defaultYes;
377
+ }
378
+ return answer === "y" || answer === "yes";
379
+ }
380
+
381
+ async function chooseMode(rl, fallback) {
382
+ const answer = (await rl.question(`Trading mode [paper/live] (${fallback}): `)).trim().toLowerCase();
383
+ if (!answer) {
384
+ return fallback;
385
+ }
386
+ return answer === "live" ? "live" : "paper";
387
+ }
388
+
389
+ function getCommandCandidates(command) {
390
+ if (process.platform !== "win32") {
391
+ return [command];
392
+ }
393
+
394
+ if (command.includes(".")) {
395
+ return [command];
396
+ }
397
+
398
+ return [command, `${command}.cmd`, `${command}.exe`, `${command}.bat`];
399
+ }
400
+
401
+ function getSpawnCommand(command) {
402
+ if (process.platform === "win32" && command === "npm") {
403
+ return "npm.cmd";
404
+ }
405
+ return command;
406
+ }
407
+
408
+ function getSpawnSpec(command, args) {
409
+ if (process.platform === "win32" && command === "npm") {
410
+ return {
411
+ command: "cmd.exe",
412
+ args: ["/d", "/s", "/c", "npm", ...args]
413
+ };
414
+ }
415
+
416
+ return {
417
+ command: getSpawnCommand(command),
418
+ args
419
+ };
420
+ }
package/web/AGENTS.md ADDED
@@ -0,0 +1,5 @@
1
+ <!-- BEGIN:nextjs-agent-rules -->
2
+ # This is NOT the Next.js you know
3
+
4
+ This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
5
+ <!-- END:nextjs-agent-rules -->
package/web/CLAUDE.md ADDED
@@ -0,0 +1 @@
1
+ @AGENTS.md
package/web/README.md ADDED
@@ -0,0 +1,36 @@
1
+ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
2
+
3
+ ## Getting Started
4
+
5
+ First, run the development server:
6
+
7
+ ```bash
8
+ npm run dev
9
+ # or
10
+ yarn dev
11
+ # or
12
+ pnpm dev
13
+ # or
14
+ bun dev
15
+ ```
16
+
17
+ Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
18
+
19
+ You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
20
+
21
+ This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
22
+
23
+ ## Learn More
24
+
25
+ To learn more about Next.js, take a look at the following resources:
26
+
27
+ - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
28
+ - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
29
+
30
+ You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
31
+
32
+ ## Deploy on Vercel
33
+
34
+ The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
35
+
36
+ Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
@@ -0,0 +1,25 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema.json",
3
+ "style": "base-nova",
4
+ "rsc": true,
5
+ "tsx": true,
6
+ "tailwind": {
7
+ "config": "",
8
+ "css": "src/app/globals.css",
9
+ "baseColor": "neutral",
10
+ "cssVariables": true,
11
+ "prefix": ""
12
+ },
13
+ "iconLibrary": "lucide",
14
+ "rtl": false,
15
+ "aliases": {
16
+ "components": "@/components",
17
+ "utils": "@/lib/utils",
18
+ "ui": "@/components/ui",
19
+ "lib": "@/lib",
20
+ "hooks": "@/hooks"
21
+ },
22
+ "menuColor": "default",
23
+ "menuAccent": "subtle",
24
+ "registries": {}
25
+ }
@@ -0,0 +1,18 @@
1
+ import { defineConfig, globalIgnores } from "eslint/config";
2
+ import nextVitals from "eslint-config-next/core-web-vitals";
3
+ import nextTs from "eslint-config-next/typescript";
4
+
5
+ const eslintConfig = defineConfig([
6
+ ...nextVitals,
7
+ ...nextTs,
8
+ // Override default ignores of eslint-config-next.
9
+ globalIgnores([
10
+ // Default ignores of eslint-config-next:
11
+ ".next/**",
12
+ "out/**",
13
+ "build/**",
14
+ "next-env.d.ts",
15
+ ]),
16
+ ]);
17
+
18
+ export default eslintConfig;
@@ -0,0 +1,7 @@
1
+ import type { NextConfig } from "next";
2
+
3
+ const nextConfig: NextConfig = {
4
+ /* config options here */
5
+ };
6
+
7
+ export default nextConfig;