[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-1464":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":15,"stars30d":15,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":16,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":17,"fork":17,"defaultBranch":18,"hasWiki":17,"hasPages":17,"topics":19,"createdAt":10,"pushedAt":10,"updatedAt":40,"readmeContent":41,"aiSummary":42,"trendingCount":15,"starSnapshotCount":15,"syncStatus":43,"lastSyncTime":44,"discoverSource":45},1464,"ai-trading-agent","endless-sky-team\u002Fai-trading-agent","endless-sky-team","llm trading bot ai agent crypto bitcoin ethereum perpetuals openrouter lighter algorithmic automated quant typescript react postgres bun fintech defi machine-learning open-source crypto-bot signals","https:\u002F\u002Fgithub.com\u002Fendless-sky-team\u002Fai-trading-agent",null,"TypeScript",201,161,1,0,6.63,false,"master",[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"ai-trading","algorithmic-trading","automated-trading","bitcoin","bun","crypto-bot","cryptocurrency","defi","ethereum","fintech","lighter","llm","machine-learning","open-source","openrouter","postgresql","quantitative-finance","react","trading-bot","typescript","2026-06-12 02:00:28","# AI Trading Agent\n\n**Repository (clone \u002F issues \u002F PRs):** [github.com\u002Fendless-sky-team\u002Fai-trading-agent](https:\u002F\u002Fgithub.com\u002Fendless-sky-team\u002Fai-trading-agent)\n\n**Keywords:** trading-bot ai-trading openrouter lighter lighter-xyz perpetuals llm llm-agent tool-calling prisma postgresql bun typescript express react vite vercel-ai-sdk crypto bitcoin ethereum altcoin algorithmic-trading automated-trading quant quantitative fintech audit telemetry positions risk open-source defi research crypto-bot autonomous-agent streaming llm openapi portfolio dashboard invocations-timeseries prisma-studio cors rest-api javascript esm bun-runtime\n\n> **Disclaimer:** Automated trading carries significant financial risk. This software is provided for educational and experimental use. You are solely responsible for API keys, position sizing, capital at risk, and compliance with laws in your jurisdiction. Never trade funds you cannot afford to lose.\n\n---\n\n## Table of contents\n\n1. [Why this project is useful](#why-this-project-is-useful)  \n2. [What you get](#what-you-get)  \n3. [Prerequisites](#prerequisites)  \n4. [Quick start](#quick-start)  \n5. [How a single cycle works](#how-a-single-cycle-works)  \n6. [Database models and tool types](#database-models-and-tool-types)  \n7. [Important: position side handling](#important-position-side-handling)  \n8. [Optional dashboard API and UI](#optional-dashboard-api-and-ui)  \n9. [Project layout](#project-layout-high-level)  \n10. [Tech stack](#tech-stack)  \n11. [Troubleshooting](#troubleshooting)  \n12. [Useful tips](#useful-tips)  \n13. [License](#license)  \n\n---\n\n## Why this project is useful\n\nThis agent is **useful** when you want a **repeatable, observable loop** between market data, an LLM, and a small set of exchange actions—without building that plumbing from scratch every time.\n\n| What it helps with | Why that matters |\n|--------------------|------------------|\n| **Prompt + data assembly** | Each run merges candlestick-derived signals (intraday and longer horizon), balances, positions, and invocation count into one prompt (`prompt.ts`). You reuse the pipeline and only tune strategy text or markets. |\n| **Multi-model experimentation** | Add rows under `Models` with different `openRoutermodelName` strings to **compare models** on similar conditions, or route **multiple Lighter accounts** from one process, without duplicating the runner. |\n| **Auditing and review** | Responses and tool usage land in PostgreSQL (`Invocations`, `ToolCalls`), which is **useful** for debugging behavior, measuring how often the model opens vs. flattens, and tracing what was decided when. |\n| **Guardrailed automation** | The model does not get arbitrary API access—it only invokes the trading tools wired in code, which is **useful** for limiting blast radius compared to unrestricted agents. |\n| **Hands-off scheduling** | A fixed cadence (**every 5 minutes** after start) removes the need to manually trigger runs when you already trust your prompt and sizing rules. |\n\n**Useful for:** researchers comparing LLMs on trading prompts, builders prototyping Lighter + OpenRouter flows, and operators who want logs and database-backed history alongside automation.\n\n### Where this applies more widely\n\nThe **implementation** here targets Lighter and OpenRouter, but the **shape** of the project is easy to reuse in many environments:\n\n| Context | How it extends |\n|---------|----------------|\n| **Other exchanges & venues** | The same loop—scheduled run → enriched prompt → constrained tools → persisted audit—maps to perpetuals, spots, or **simulated\u002Fmock** adapters if you swap the exchange layer (`createPosition`, `cancelOrder`, market data fetchers) for your APIs. |\n| **Education & labs** | Universities and coding bootcamps use this style of repo to teach **tool-calling**, **risk disclosure**, and **observable agents** without students wiring raw websocket trading from day one. |\n| **Product & fintech prototyping** | Teams can demo “AI-assisted execution” internally: keep PostgreSQL telemetry and prompts, stub orders in staging or paper flows, then harden gateway rules before any real capital. |\n| **LLM evaluation & research** | **Any provider** reachable through OpenRouter (or by substituting the AI SDK provider) lets you **compare models** on the same indicator snapshot and record outcomes in one database. |\n| **Compliance-minded workflows** | Immutable-style logs of model output + tool calls support **post-hoc review**—useful in regulated or internal-trading settings where you must show *what* the system did and *when*. |\n| **Home labs & VPS** | A small **self-hosted** Bun process fits low-cost servers or Raspberry Pi-class boxes for experimentation, monitoring, or personal alerting (with firewall and secret hygiene). |\n\nAcross these cases, **wide reuse** comes from separating **strategy text** (`prompt.ts`), **data assembly**, **narrow tools**, and **storage**—you can transplant that split into quant stacks, alerting bots, or research harnesses beyond crypto.\n\n---\n\n## What you get\n\n| Capability | Summary |\n|------------|---------|\n| **Multi-model orchestration** | Each row in `Models` drives its own scheduler pass with a distinct OpenRouter model name and Lighter credentials. |\n| **Rich context each run** | 5‑minute and 4‑hour signals (mid price, EMA20, MACD), open positions, and portfolio totals are injected into the prompt. |\n| **Auditable actions** | Invocations and tool calls (`createPosition`, `closeAllPosition`-style closes) are stored for review. |\n| **Periodic execution** | The agent cycle runs automatically every **5 minutes** once started. |\n\n---\n\n## Prerequisites\n\n- **[Bun](https:\u002F\u002Fbun.sh)** ≥ 1.x (recommended: match the version you use elsewhere in your stack).\n- **PostgreSQL** database reachable from your machine or server.\n- **OpenRouter API key** for the models you intend to call.\n- **Lighter API key** (and associated `accountIndex`) for each automated account configured in `Models`.\n\n---\n\n## Quick start\n\n### 1. Install dependencies\n\n```bash\nbun install\n```\n\n### 2. Configure environment\n\nCreate an environment file (for example `.env`) in this directory with at minimum:\n\n| Variable | Required | Purpose |\n|----------|----------|---------|\n| `DATABASE_URL` | Yes | PostgreSQL connection string used by Prisma. |\n| `OPENROUTER_API_KEY` | Yes | Authenticates requests to OpenRouter from the AI SDK provider. |\n\n### 3. Prepare the database\n\nGenerate the Prisma client and apply migrations (from this directory):\n\n```bash\nbunx prisma migrate deploy\n```\n\nOr during development:\n\n```bash\nbunx prisma migrate dev\n```\n\n### 4. Define trading profiles\n\nPopulate the **`Models`** table with one row per logical trader: each needs a unique `name`, OpenRouter routing string (`openRoutermodelName`), `lighterApiKey`, and `accountIndex`. Empty state means nothing runs—you must insert at least one valid record via your preferred SQL GUI, script, or Prisma Studio (`bunx prisma studio`) before expecting activity.\n\n### 5. Run the agent\n\n```bash\nbun run index.ts\n```\n\nOn startup and every five minutes afterward, the process loads every `Models` row and invokes `invokeAgent` for each. Logs include the enriched prompt body for observability—ensure logging does not violate your confidentiality policy in production environments.\n\n### Commands summary\n\n| Goal | Command |\n|------|---------|\n| Install deps | `bun install` |\n| Apply DB migrations | `bunx prisma migrate deploy` (or `migrate dev`) |\n| Generate Prisma client only | `bunx prisma generate` |\n| Browse DB | `bunx prisma studio` |\n| Run **agent loop** only | `bun run index.ts` |\n| Run **HTTP dashboard API** | `bun run backend.ts` (needs same `DATABASE_URL`; port **3000**) |\n| Run **frontend** UI | `cd frontend && npm install && npm run dev` |\n\n---\n\n## How a single cycle works\n\n1. **Indicators** — For each configured market (e.g. SOL, ZEC, HYPE), the agent fetches short- and medium-term candles and summarizes mid prices, EMA20, and MACD.\n2. **State** — It pulls portfolio value, available balance, and open positions tied to the Lighter credentials for that model.\n3. **LLM turn** — A trading prompt (`prompt.ts`) is filled with placeholders and sent to OpenRouter streaming through the AI SDK (`streamText`).\n4. **Tools** — If the model calls tools, executions are persisted under `Invocations` and `ToolCalls`, and invocation counts update on the corresponding `Models` row.\n\nStrategy text and risk rules are defined in `prompt.ts`; adjust them there if you change markets or risk appetite.\n\n---\n\n## Database models and tool types\n\nPrisma schema: `prisma\u002Fschema.prisma`; client output: `generated\u002Fprisma`.\n\n| Model | Purpose |\n|--------|---------|\n| **Models** | One row per automated profile: `name` (unique), `openRoutermodelName` (OpenRouter model id), `lighterApiKey`, `accountIndex`, `invocationCount`. |\n| **Invocations** | One row per agent run: `response` (final model text after streaming completes), timestamps. |\n| **ToolCalls** | Rows linked to an invocation: `toolCallType` + JSON `metadata`. |\n| **PortfolioSize** | Time series of `netPortfolio` strings per model (used by the optional `\u002Fperformance` API). |\n\n`ToolCallType` enum values: **`CREATE_POSITION`**, **`CLOSE_POSITION`** (close-all flow).\n\n---\n\n## Important: position side handling\n\nIn `index.ts`, the `createPosition` tool handler **inverts** the model’s requested side relative to the `LONG` \u002F `SHORT` enum sent by the LLM (the code comment states this is intentional: the executed side is the opposite of what the model chose). If you fork this repo, **audit this line** before live use—either remove the inversion or align your prompt so intended economics match execution.\n\n---\n\n## Optional dashboard API and UI\n\n| Component | How to run (typical) | Role |\n|-----------|----------------------|------|\n| **HTTP API** | `bun run backend.ts` (from repo root, same env as the agent) | Serves JSON on port **3000**: `GET \u002Fperformance` (cached portfolio history), `GET \u002Finvocations?limit=N` (recent runs with tool calls, limit ≤ 200). |\n| **Frontend** | `cd frontend && npm install && npm run dev` | Vite dev server; point API calls at `http:\u002F\u002Flocalhost:3000` (or your deployed backend). |\n\nThe agent loop and the backend are **separate processes**—run both if you want the UI; run only `index.ts` if you only need automation and Prisma storage.\n\n---\n\n## Project layout (high level)\n\n| Path \u002F area | Role |\n|-------------|------|\n| `index.ts` | Entry point: **5-minute** `setInterval` loop and `invokeAgent` (also runs `main()` once at startup). |\n| `backend.ts` | Express + CORS: `\u002Fperformance`, `\u002Finvocations`. |\n| `prompt.ts` | System prompt template and trading constraints. |\n| `markets.ts` | Symbol → Lighter market metadata. |\n| `prisma\u002Fschema.prisma` | `Models`, `Invocations`, `ToolCalls`, `PortfolioSize`. |\n| `stockData.ts`, `openPositions.ts`, `createPosition.ts`, `cancelOrder.ts` | Market data and exchange-side effects. |\n| `frontend\u002F` | React dashboard (optional). |\n\n---\n\n## Tech stack\n\n- **Runtime:** Bun  \n- **AI:** [`@openrouter\u002Fai-sdk-provider`](https:\u002F\u002Fgithub.com\u002FOpenRouterTeam\u002Fai-sdk-provider), [`ai`](https:\u002F\u002Fsdk.vercel.ai\u002Fdocs\u002Fintroduction) (Vercel AI SDK)  \n- **Data:** Prisma Client (generated under `generated\u002Fprisma`) + PostgreSQL  \n- **API (optional):** Express 5, CORS  \n\n---\n\n## Troubleshooting\n\n| Symptom | What to check |\n|--------|----------------|\n| Nothing runs on schedule | `Models` table is empty or migration not applied; verify `bunx prisma migrate deploy` and at least one valid row. |\n| OpenRouter or DB errors on startup | `OPENROUTER_API_KEY`, `DATABASE_URL`; Postgres reachable from the host. |\n| Lighter auth \u002F position errors | `lighterApiKey` and `accountIndex` match the account; `markets.ts` symbol keys match Lighter. |\n| Backend returns empty `invocations` | Agent must have run at least once; check Prisma `Invocations` in Studio. |\n| Frontend cannot reach API | CORS is enabled on `backend.ts`; ensure the frontend’s fetch URL matches where Express listens (default `3000`). |\n\n---\n\n## Useful tips\n\n- **Inspect history** — Use `bunx prisma studio` to browse `Invocations` and `ToolCalls` when you need to see past model outputs and which tools actually ran.\n- **Tune strategy without redeploying logic** — Most behavioral rules live in `prompt.ts` and `markets.ts`; adjust copy, markets, or constraints there while keeping the same execution path.\n- **Dry-run mindset** — Even with logging, treat small account sizes and clear stop rules as essential; the agent is a tool, not a guarantee of profit.\n\n---\n\n## License\n\nLicense for this repository is unspecified; confirm with the repository owner before redistributing or using in commercial settings.\n","AI Trading Agent 是一个基于大语言模型的自动化交易机器人，专为加密货币（如比特币、以太坊等）和永续合约设计。该项目利用先进的算法交易技术，结合机器学习模型来生成交易信号，并通过预设的交易所API执行交易策略。它支持多模型实验，允许用户比较不同模型的表现或同时管理多个Lighter账户。此外，项目还提供了一个可选的仪表盘界面，用于监控交易活动、审计历史记录及调整策略参数。适用于希望探索量化金融领域、进行自动交易研究或开发个人交易系统的开发者和技术爱好者。",2,"2026-05-06 17:32:59","CREATED_QUERY"]