[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-78389":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":16,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":17,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":10,"pushedAt":10,"updatedAt":27,"readmeContent":28,"aiSummary":29,"trendingCount":15,"starSnapshotCount":15,"syncStatus":30,"lastSyncTime":31,"discoverSource":32},78389,"arbitrage-trading-bot","ShinyaTomitsuka\u002Farbitrage-trading-bot","ShinyaTomitsuka","polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot polymarket trading bot bot","",null,"TypeScript",342,6235,1,0,122,10,false,"main",true,[22,5,23,24,25,26],"arbitrage-bot","bot","polymarket-arbitrage-trading-bot","polymarket-trading-bot","trading-bot","2026-06-12 02:03:47","# Polymarket Trading Bot\n\n**Open-source TypeScript Polymarket trading bot** for automated UP\u002FDOWN crypto prediction markets on the Polymarket CLOB. Resolves live market slugs (BTC, ETH, SOL, XRP · 5m–24h), polls order-book prices every second, and executes configurable strategies with real on-chain balances and FAK orders via [`@polymarket\u002Fclob-client-v2`](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@polymarket\u002Fclob-client-v2).\n\n\u003Cp>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fnode-%3E%3D20.6.0-339933?style=flat-square&logo=node.js&logoColor=white\" alt=\"Node.js\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Ftypescript-5.3-3178C6?style=flat-square&logo=typescript&logoColor=white\" alt=\"TypeScript\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002F%40polymarket%2Fclob--client--v2-1.0.3-2E5CFF?style=flat-square\" alt=\"@polymarket\u002Fclob-client-v2\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-ISC-lightgrey?style=flat-square\" alt=\"License\"\u002F>\n\u003C\u002Fp>\n\n\u003Cp>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20trading%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket trading bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20arbitrage%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket arbitrage bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20clob%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket clob bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20btc%20trading%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket btc trading bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20up%20down%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket up down bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fprediction%20market%20bot-2E5CFF?style=for-the-badge\" alt=\"prediction market trading bot\"\u002F>\n\u003C\u002Fp>\n\n---\n\n## Table of contents\n\n- [Overview](#overview)\n- [Features](#features)\n- [How it works](#how-it-works)\n- [Strategies](#strategies)\n- [Requirements](#requirements)\n- [Quick start](#quick-start)\n- [Configuration](#configuration)\n- [Runtime output](#runtime-output)\n- [Scripts](#scripts)\n- [Project structure](#project-structure)\n- [Security](#security)\n- [Disclaimer](#disclaimer)\n- [Search terms](#search-terms)\n\n---\n\n## Overview\n\nThis repository is a production-oriented **Polymarket trading bot** focused on short-horizon crypto markets (e.g. “Bitcoin Up or Down — 5m \u002F 15m \u002F 1h”). It is **not** a backtester or paper-trading simulator: portfolio state comes from Polymarket `getBalanceAllowance`, and orders are submitted as Fill-and-Kill (FAK) market orders on Polygon.\n\nUse it if you are looking for a **Polymarket arbitrage bot** or **Polymarket CLOB bot** you can fork, tune via `trade.toml`, and run with `npm run dev`.\n\n---\n\n## Features\n\n| Area | Behavior |\n| --- | --- |\n| **Market discovery** | Builds the active slug from coin + window, fetches UP\u002FDOWN `clobTokenIds` from Gamma, rolls to the next window when time expires |\n| **Pricing** | 1s poll of CLOB `\u002Fprices` (BUY\u002FSELL per token) with timeout, retry, and last-good cache fallback |\n| **Portfolio** | Reads `CONDITIONAL` and `COLLATERAL` balances on-chain — no simulated PnL |\n| **Execution** | FAK orders with configurable retries and post-trade balance polling |\n| **Strategies** | `trade_1` (exit-only) and `trade_2` (entry, exit, optional emergency swap) |\n| **Auth** | L1 API key derive\u002Fcreate; supports proxy and EOA signature types with automatic fallback |\n| **Operator UX** | Live market + portfolio lines, trend\u002Fposition\u002Fengine legend |\n\n---\n\n## How it works\n\n```mermaid\nflowchart LR\n  A[trade.toml + .env] --> B[Bootstrap CLOB client]\n  B --> C[Resolve market slug]\n  C --> D[Gamma: token IDs]\n  D --> E[Poll prices every 1s]\n  E --> F[Strategy decision]\n  F --> G[FAK buy\u002Fsell + balance check]\n  G --> E\n  E --> H{Window ended?}\n  H -->|yes| C\n  H -->|no| E\n```\n\n1. Load and validate `trade.toml` (Zod) and environment variables.\n2. Authenticate against the CLOB (derive API key first, then create if needed).\n3. For each market window: resolve slug → load tokens → loop until `endTimestamp`.\n4. On each tick: update prices, run `trade_1` or `trade_2`, place orders when rules fire.\n5. When the window ends, select the next slug and repeat.\n\n---\n\n## Strategies\n\nStrategy is set with `strategy = \"trade_1\" | \"trade_2\"` in `trade.toml`. Both strategies use the same signals:\n\n| Signal | Formula | Meaning |\n| --- | --- | --- |\n| `remaining_time_ratio` | `(marketTime - remainingTime) \u002F marketTime` | `0` at window open → `1` at close |\n| `up_price_ratio` | `\\|upBuyPrice - 0.5\\| \u002F 0.5` | `0` at $0.50 UP → `1` at $0.00 or $1.00 |\n\n### `trade_1` — exit-only\n\nNo new entries. If a position exists, sell when **either**:\n\n- `remaining_time_ratio > trade_1.exit_time_ratio`, or\n- `up_price_ratio > trade_1.exit_price_ratio`\n\n`entry_price_range`, `swap_price_range`, `take_profit`, and `stop_loss` are required by the schema for validation but are **not** used by the current engine (reserved for future entry logic).\n\n### `trade_2` — entry, exit, emergency swap\n\n- **Entry** (once per window): no position, `remaining_time_ratio > entry_time_ratio`, and `up_price_ratio` inside `entry_price_ratio`. Buys the side with the higher buy price.\n- **Exit**: `up_price_ratio` matches any tuple in `exit_price_ratio_range` → sell held side.\n- **Emergency swap** (optional): after a successful exit, if `up_price_ratio` is inside `emergency_swap_price`, buy the opposite token immediately.\n\n---\n\n## Requirements\n\n- **Node.js** `>= 20.6.0`\n- **Signer** EOA private key (`POLYMARKET_PRIVATE_KEY`) — signs orders and CLOB auth\n- **Funder** address that holds USDC (`POLYMARKET_FUNDER_ADDRESS` or legacy `PROXY_WALLET_ADDRESS`) — typically your Polymarket proxy \u002F Gnosis Safe\n- **USDC on Polygon** (chain id `137`) on the funder wallet\n\n---\n\n## Quick start\n\n```bash\ngit clone \u003Cyour-fork-url>\ncd polymarket-arbitrage-trading-bot\nnpm install\n```\n\n**1. Environment** — copy `.env.example` to `.env`:\n\n```env\nPOLYMARKET_PRIVATE_KEY=0x...\nPOLYMARKET_FUNDER_ADDRESS=0x...\n\n# Optional — force a signature mode (see Configuration)\n# POLYMARKET_SIGNATURE_TYPE=POLY_PROXY\n```\n\n**2. Strategy** — edit `trade.toml` (defaults shown in repo):\n\n```toml\nstrategy = \"trade_2\"\ntrade_usd = 3\nmax_retries = 3\n\n[market]\nmarket_coin = \"btc\"    # btc | eth | sol | xrp\nmarket_period = \"5\"    # 5 | 15 | 60 | 240 | 1440 (minutes)\n```\n\n**3. Run**\n\n```bash\nnpm run dev\n```\n\nFor production, build and run compiled output:\n\n```bash\nnpm run build\nnpm start\n```\n\n---\n\n## Configuration\n\n### Environment variables\n\n| Variable | Required | Description |\n| --- | --- | --- |\n| `POLYMARKET_PRIVATE_KEY` | Yes | EOA private key for signing |\n| `POLYMARKET_FUNDER_ADDRESS` | Yes* | Wallet that holds USDC \u002F positions |\n| `PROXY_WALLET_ADDRESS` | Yes* | Legacy alias for funder address |\n| `POLYMARKET_SIGNATURE_TYPE` | No | `EOA`, `POLY_PROXY`, `POLY_GNOSIS_SAFE`, or `POLY_1271` |\n\n\\*One of `POLYMARKET_FUNDER_ADDRESS` or `PROXY_WALLET_ADDRESS` must be set.\n\n**Signature behavior**\n\n- If `POLYMARKET_SIGNATURE_TYPE` is set, only that mode is used.\n- If unset, the bot tries **`POLY_PROXY`** then **`EOA`** until CLOB auth succeeds (typical for funded proxy wallets vs direct EOA).\n\n### `trade.toml`\n\n| Key | Description |\n| --- | --- |\n| `strategy` | `\"trade_1\"` or `\"trade_2\"` |\n| `trade_usd` | USD notional per entry order |\n| `max_retries` | Retries for failed order posts (default `3`) |\n| `[market].market_coin` | `btc`, `eth`, `sol`, `xrp` |\n| `[market].market_period` | `5`, `15`, `60`, `240`, `1440` (minutes) |\n\n**Market periods**\n\n| Period | Notes |\n| --- | --- |\n| `5` | 5-minute bucket; slug wiring is **BTC-only** today |\n| `15`, `60`, `240`, `1440` | Supported for BTC, ETH, SOL, XRP |\n\nSee `trade.toml` in the repo for full `trade_1` \u002F `trade_2` parameter examples. Invalid config fails fast at startup via Zod.\n\n---\n\n## Runtime output\n\n**Trend** (UP token, last 2 ticks): `UP 🟢` · `DOWN 🔴` · `FLAT ⚪`\n\n**Position** (on-chain): `UP 🟩` · `DOWN 🟥` · `NONE ⬛`\n\n**Engine**: `BUSY` (order in flight) · `IDLE`\n\nStartup logs include signer address, strategy, market (coin + minutes), and `trade_usd`. During the loop (~every 3s):\n\n- **Market line** — `tMinus`, `up`, `down`, spreads, `upRatio`, `timeRatio`, `score`, `trend`, `position`, `engine`\n- **Portfolio line** — `cash`, `shares`, `position`, `shareValue`, `total`, `engine`, `trend`\n\n---\n\n## Scripts\n\n| Command | Description |\n| --- | --- |\n| `npm run dev` | Run with `tsx` (`src\u002Findex.ts`) |\n| `npm run build` | Compile to `dist\u002F` |\n| `npm start` | Run `node dist\u002Findex.js` |\n\n---\n\n## Project structure\n\n```\nsrc\u002F\n├── index.ts              # Main loop, CLOB bootstrap, per-window cycle\n├── types.ts              # Coin, Minutes, Market types\n├── config\u002F\n│   ├── env.ts            # .env loading\n│   ├── toml.ts           # Zod-validated trade.toml → globalThis.__CONFIG__\n│   ├── slug.ts           # Slug + window timestamps\n│   └── market.ts         # Coin\u002Fperiod helpers\n├── services\u002F\n│   ├── clob.ts           # Signer, funder, prices, signature type\n│   └── gamma.ts          # Market lookup by slug\n├── trade\u002F\n│   ├── index.ts          # Trade class\n│   ├── prices.ts         # Ticks, trend, logging\n│   ├── decision.ts       # trade_1 \u002F trade_2 logic\n│   └── trade.ts          # Buy\u002Fsell, retries, balances\n├── constant\u002Findex.ts     # Global in-flight order guard\n└── utils\u002F                # time, retry, logging\ntrade.toml                # Runtime strategy + market config\n```\n\n---\n\n## Security\n\n- Never commit `.env`, private keys, or API credentials.\n- Use a dedicated signer and a funder wallet with **limited** USDC for testing.\n- Start with low `trade_usd` (e.g. `$1–$3`) before scaling.\n- Confirm the **funder address** actually holds USDC; the signer alone does not fund trades.\n- Review `trade.toml` thresholds — aggressive ratios can exit or flip positions quickly.\n\n---\n\n## Disclaimer\n\nThis software is provided for education and research. Trading on prediction markets involves financial risk. The authors are not responsible for losses, failed transactions, or exchange\u002FAPI changes. You are solely responsible for compliance with applicable laws and Polymarket’s terms of use.\n\n---\n\n## Search terms\n\nPeople often find this project when searching for:\n\n**Polymarket trading bot** · Polymarket arbitrage bot · Polymarket BTC trading bot · Polymarket 5 minute bot · Polymarket 15 minute bot · Polymarket CLOB trading bot · Polymarket orderbook bot · Polymarket UP\u002FDOWN bot · Polymarket API bot · Polymarket TypeScript bot · Polymarket Node.js bot · crypto prediction market bot\n\n\u003Cp>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20btc%205min%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket btc 5min bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20btc%2015min%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket btc 15min bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20clob%20trading%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket clob trading bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20market%20making%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket market making bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpolymarket%20typescript%20bot-2E5CFF?style=for-the-badge\" alt=\"polymarket typescript bot\"\u002F>\n  \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fcrypto%20prediction%20market%20bot-2E5CFF?style=for-the-badge\" alt=\"crypto prediction market bot\"\u002F>\n\u003C\u002Fp>\n","这是一个基于TypeScript的开源Polymarket交易机器人，专注于自动化加密货币预测市场的UP\u002FDOWN交易。核心功能包括实时解析市场标识（如BTC、ETH等），每秒轮询订单簿价格，并通过`@polymarket\u002Fclob-client-v2`库执行可配置策略，支持真实链上余额和FAK订单。适用于希望在Polymarket平台上进行套利交易或CLOB（中央限价订单簿）交易的用户。项目提供了灵活的配置选项，允许用户根据自身需求调整策略参数并快速启动运行。",2,"2026-05-29 04:07:00","CREATED_QUERY"]