[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-75896":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":15,"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":22,"readmeContent":23,"aiSummary":24,"trendingCount":15,"starSnapshotCount":15,"syncStatus":25,"lastSyncTime":26,"discoverSource":27},75896,"Polymarket-Arbitrage-Trading-Bot-v2","heyFive-dev\u002FPolymarket-Arbitrage-Trading-Bot-v2","heyFive-dev","Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot Polymarket Arbitrage Trading Bot","",null,"TypeScript",268,2578,110,0,89,10,false,"main",true,[],"2026-06-12 02:03:37","# Polymarket Arbitrage Trading Bot\n\nA **polymarket trading bot** for automated trading on Polymarket’s 15-minute Up\u002FDown prediction markets. This polymarket trading bot predicts direction from the live orderbook, places the first leg at best ask, and hedges with the opposite side—so you can run a polymarket trading bot 24\u002F7 without using the Polymarket UI.\n\nThis polymarket trading bot is built for traders and developers: TypeScript, Polymarket CLOB API, WebSocket orderbook, and a configurable adaptive price predictor. Whether you want to run a polymarket trading bot on BTC or extend the code, this repo gives you a full stack in one place.\n\n---\n\n## Table of Contents\n\n- [Why This Polymarket Trading Bot?](#why-this-polymarket-trading-bot)\n- [How This Polymarket Trading Bot Works](#how-this-polymarket-trading-bot-works)\n- [Strategy Deep Dive (For Traders)](#strategy-deep-dive-for-traders)\n- [Requirements](#requirements)\n- [Install](#install)\n- [Configuration](#configuration)\n- [Configuration Reference (Full)](#configuration-reference-full)\n- [Usage](#usage)\n- [Architecture (For Developers)](#architecture-for-developers)\n- [Project Structure](#project-structure)\n- [Extending the Polymarket Trading Bot](#extending-the-polymarket-trading-bot)\n\n---\n\n## Why This Polymarket Trading Bot?\n\n- **Capture every 15m window** — This polymarket trading bot resolves market slugs, connects to the orderbook, and trades on schedule. No missed rounds.\n- **Predict then hedge** — The polymarket trading bot uses an adaptive price predictor (momentum, volatility, trend) to choose Up or Down from orderbook flow; it buys the predicted side at best ask (GTC), then places the hedge at `0.98 − firstSidePrice` (GTC).\n- **One config, many markets** — Set `COPYTRADE_MARKETS=btc` or `btc,eth,sol`; the polymarket trading bot resolves slugs as `{market}-updown-15m-{startOf15mUnix}` via Polymarket’s Gamma API.\n- **Full stack** — CLOB client, USDC\u002FCTF allowances, and redemption scripts. Run the polymarket trading bot, then redeem resolved positions with one command.\n\nIf you are looking for an open-source polymarket trading bot for 15m Up\u002FDown markets, this is it.\n\n---\n\n## How This Polymarket Trading Bot Works\n\nHigh-level flow of the polymarket trading bot:\n\n1. **Bootstrap** — Load config from `.env`, create or load CLOB API credentials (`src\u002Fdata\u002Fcredential.json`), approve USDC and CTF allowances on Polygon, and wait until wallet USDC meets `BOT_MIN_USDC_BALANCE`.\n2. **Market resolution** — For each market (e.g. `btc`), the polymarket trading bot computes the current 15m slug (e.g. `btc-updown-15m-1734567890`) and fetches Up\u002FDown token IDs and `conditionId` from Gamma API.\n3. **Orderbook** — The polymarket trading bot subscribes to Polymarket’s CLOB WebSocket for those token IDs and receives real-time best bid\u002Fask updates.\n4. **Prediction** — On each price update, an **AdaptivePricePredictor** (per market) consumes smoothed price history and outputs: direction (Up\u002FDown), confidence, and signal (BUY_UP \u002F BUY_DOWN \u002F HOLD). The predictor uses momentum, volatility, trend, and optional pole (peak\u002Ftrough) logic; it adapts weights with online gradient descent.\n5. **Execution** — When the polymarket trading bot gets BUY_UP or BUY_DOWN, it places a limit order on the predicted side at best ask (with optional `COPYTRADE_PRICE_BUFFER`), then places the hedge on the opposite side at `0.98 − firstSidePrice` (GTC by default). Optional: `COPYTRADE_HEDGE_SECOND_LEG=taker` posts a market-style hedge (FOK\u002FFAK), and `COPYTRADE_HEDGE_UNWIND_TIMEOUT_MS` can cancel an unfilled limit hedge within that window and FAK-sell any filled first-leg shares to reduce one-sided risk.\n6. **State** — Per-slug state (e.g. last prices, buy counts, conditionId) is stored in `src\u002Fdata\u002Fcopytrade-state.json`. The polymarket trading bot rolls to the next 15m slug at quarter-hour boundaries and re-initializes markets as needed.\n7. **Redemption** — After markets resolve, use the included scripts to redeem winnings (by holdings file or by condition ID). The polymarket trading bot does not auto-redeem; you run redemption separately.\n\n---\n\n## Strategy Deep Dive (For Traders)\n\n### Markets\n\nThis polymarket trading bot targets **15-minute Up\u002FDown** binary markets on Polymarket (e.g. “Will BTC be higher or lower in 15 minutes?”). Each market has:\n\n- **Slug** — `{market}-updown-15m-{startOf15mUnix}` (e.g. `btc-updown-15m-1734567890`). The polymarket trading bot computes the slug from the current time and fetches token IDs from Gamma.\n- **Up (YES) and Down (NO) tokens** — Complementary outcomes; prices typically sum near 1 (minus spread\u002Ffees). The polymarket trading bot trades both sides to implement a predict-then-hedge strategy.\n\n### Order Flow\n\n1. **Signal** — The polymarket trading bot’s predictor outputs BUY_UP or BUY_DOWN (or HOLD). HOLD means no order is placed.\n2. **First leg** — Limit buy on the predicted side at **best ask** (optionally plus `COPYTRADE_PRICE_BUFFER` for faster fill). Size is `COPYTRADE_SHARES` per side.\n3. **Second leg (hedge)** — Limit buy on the opposite side at **0.98 − firstSidePrice**. If the first side is filled at e.g. 0.52, the hedge is at 0.46. This targets a combined cost below 0.98 so that if one side wins, the position can be profitable after redemption.\n4. **Caps** — `COPYTRADE_MAX_BUY_COUNTS_PER_SIDE` (if &gt; 0) limits how many times per market cycle the polymarket trading bot can buy each side; after the cap, that market is paused until the next 15m cycle.\n\n### Predictor (AdaptivePricePredictor)\n\nThe polymarket trading bot uses a multi-feature adaptive predictor:\n\n- **Inputs** — Smoothed price history (EMA), momentum, volatility, trend (short\u002Flong EMA and price-change history). Optional pole detection (peaks\u002Ftroughs) can gate or weight predictions.\n- **Outputs** — `direction` (up\u002Fdown), `confidence` (0–1), `signal` (BUY_UP \u002F BUY_DOWN \u002F HOLD). Prices outside 0.003–0.97 are ignored to avoid extreme quotes.\n- **Learning** — Online gradient descent updates weights (e.g. momentum, volatility, trend) over time; recent accuracy is tracked in a sliding window so the polymarket trading bot can adapt to market regime.\n\nUnderstanding the predictor helps you tune risk and interpret logs when running this polymarket trading bot.\n\n### Risk and Position Sizing\n\n- **Balance** — The polymarket trading bot checks `BOT_MIN_USDC_BALANCE` before starting and uses `COPYTRADE_MIN_BALANCE_USDC` for runtime. Ensure your wallet has enough USDC for intended size and number of rounds.\n- **Exposure** — You are taking prediction-market risk on each 15m outcome. The hedge reduces but does not eliminate variance; both legs can fill at worse prices than expected.\n- **Redemption** — Resolved positions must be redeemed on-chain. Use the provided redemption scripts; the polymarket trading bot does not redeem automatically.\n\n---\n\n## Requirements\n\n- **Node.js 18+** (or Bun)\n- **Polygon wallet** with USDC (for the polymarket trading bot to place orders and pay fees)\n- **RPC URL** for Polygon (e.g. Alchemy) for allowances and redemption\n\n---\n## Install\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FheyFive-dev\u002FPolymarket-Arbitrage-Trading-Bot-v2.git\ncd Polymarket-Arbitrage-Trading-Bot-v2\nnpm install\n```\n\n---\n\n## Configuration\n\nCopy the example env and set at least `PRIVATE_KEY` and `COPYTRADE_MARKETS`:\n\n```bash\ncp .env.example .env\n# or: cp .env.temp .env\n```\n\nMinimum for running the polymarket trading bot:\n\n- `PRIVATE_KEY` — Wallet private key (required).\n- `COPYTRADE_MARKETS` — Comma-separated list (e.g. `btc` or `btc,eth,sol`).\n\nOptional: set `RPC_URL` (and `RPC_TOKEN` if needed) for allowances and redemption. API credentials are created on first run and stored in `src\u002Fdata\u002Fcredential.json`.\n\n---\n\n## Configuration Reference (Full)\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `PRIVATE_KEY` | Wallet private key | **required** |\n| `COPYTRADE_MARKETS` | Comma-separated markets (e.g. `btc`) | `btc` |\n| `COPYTRADE_SHARES` | Shares per side per trade | `5` |\n| `COPYTRADE_TICK_SIZE` | Price precision | `0.01` |\n| `COPYTRADE_PRICE_BUFFER` | Price buffer for execution (e.g. 0.01 = 1¢) | `0` |\n| `COPYTRADE_WAIT_FOR_NEXT_MARKET_START` | Wait for next 15m boundary before starting | `false` |\n| `COPYTRADE_MAX_BUY_COUNTS_PER_SIDE` | Max buys per side per market (0 = no cap) | `0` |\n| `COPYTRADE_FIRE_AND_FORGET` | Don’t wait for order confirmation | `true` |\n| `COPYTRADE_HEDGE_SECOND_LEG` | Hedge leg: `limit` (GTC, default) or `taker` (CLOB market FOK\u002FFAK) | `limit` |\n| `COPYTRADE_HEDGE_TAKER_ORDER_TYPE` | With `taker`: `FOK` (fill all or cancel) or `FAK` (partial ok) | `FOK` |\n| `COPYTRADE_HEDGE_TAKER_SLIPPAGE` | Extra USDC headroom for taker hedge buy (e.g. `1.15` = 15% above ask×size) | `1.1` |\n| `COPYTRADE_HEDGE_WAIT_FIRST_FILL_MS` | Wait up to this many ms for first-leg fills before posting taker hedge (`0` = immediate) | `0` |\n| `COPYTRADE_HEDGE_UNWIND_TIMEOUT_MS` | With limit hedge: if hedge not fully filled in this window, cancel both legs and FAK-sell first-leg fills (`0` = off) | `0` |\n| `COPYTRADE_HEDGE_UNWIND_POLL_MS` | Poll interval for unwind watcher (ms) | `150` |\n| `COPYTRADE_NEG_RISK` | Use neg-risk order type | `false` |\n| `COPYTRADE_MIN_BALANCE_USDC` | Min USDC to keep trading | `1` |\n| `CHAIN_ID` | Chain ID (Polygon) | `137` |\n| `CLOB_API_URL` | CLOB API base URL | `https:\u002F\u002Fclob.polymarket.com` |\n| `RPC_URL` \u002F `RPC_TOKEN` | RPC for allowances\u002Fredemption | — |\n| `BOT_MIN_USDC_BALANCE` | Min USDC to start polymarket trading bot | `1` |\n| `USE_PROXY_WALLET` | Use Polymarket proxy wallet | `false` |\n| `PROXY_WALLET_ADDRESS` | Proxy wallet address (if above true) | — |\n| `LOG_DIR` \u002F `LOG_FILE_PREFIX` | Log directory and file prefix | `logs` \u002F `bot` |\n| `LOG_FILE_PATH` | Override log file path (supports `{date}`) | — |\n| `DEBUG` | Verbose logs | `false` |\n\n---\n\n## Usage\n\n### Run the polymarket trading bot\n\n```bash\nnpm start\n# or: bun src\u002Findex.ts\n```\n\n### Redemption\n\nAfter markets resolve, redeem winnings:\n\n```bash\n# Auto-redeem from holdings file (generated by polymarket trading bot activity)\nnpm run redeem:holdings\n# or: bun src\u002Fredeem-holdings.ts [--dry-run] [--clear-holdings] [--api] [--max N]\n\n# Redeem by condition ID\nnpm run redeem\n# or: bun src\u002Fredeem.ts [conditionId] [indexSets...]\nbun src\u002Fredeem.ts --check \u003CconditionId>\n```\n\n### Development\n\n```bash\nnpx tsc --noEmit\nbun --watch src\u002Findex.ts\n```\n\n---\n\n## Architecture (For Developers)\n\n### Entry and Bootstrap\n\n- **`src\u002Findex.ts`** — Validates `PRIVATE_KEY`, creates\u002Floads CLOB credentials, approves USDC\u002FCTF allowances, waits for `BOT_MIN_USDC_BALANCE`, optionally waits for the next 15m boundary, then instantiates `CopytradeArbBot` and starts it. Handles SIGINT\u002FSIGTERM and triggers summary generation before exit.\n\n### Config\n\n- **`src\u002Fconfig\u002Findex.ts`** — Loads `.env` and exposes typed config: chain, CLOB URL, copytrade (markets, shares, tick size, buffers, caps), logging, redeem args. Used everywhere the polymarket trading bot needs settings.\n\n### Core Bot and Order Flow\n\n- **`src\u002Forder-builder\u002Fcopytrade.ts`** — **CopytradeArbBot**: holds CLOB client and config; computes 15m slugs; fetches token IDs and conditionId from Gamma; subscribes to WebSocket orderbook per token; maintains per-market `AdaptivePricePredictor` and per-slug state; on price updates runs predictor and, on BUY_UP\u002FBUY_DOWN, places first-side then hedge orders. Persists state to `src\u002Fdata\u002Fcopytrade-state.json` and tracks prediction\u002Ftrade stats for summaries.\n\n### Data and APIs\n\n- **`src\u002Fproviders\u002Fclobclient.ts`** — Singleton CLOB client (credentials + `PRIVATE_KEY`); used for order placement and balance\u002Fallowance sync.\n- **`src\u002Fproviders\u002FwebsocketOrderbook.ts`** — WebSocket client for Polymarket CLOB “market” channel; subscribes by token ID; exposes best bid\u002Fask and price-update callbacks used by the polymarket trading bot for real-time signals.\n\n### Prediction and Utilities\n\n- **`src\u002Futils\u002FpricePredictor.ts`** — **AdaptivePricePredictor**: price history (smoothed), momentum, volatility, trend, optional pole detection; outputs direction, confidence, signal; online learning. Used once per market by the polymarket trading bot.\n- **`src\u002Futils\u002Fredeem.ts`** — CTF redemption helpers, resolution checks, auto-redeem from holdings or API (used by redeem scripts).\n- **`src\u002Futils\u002Fholdings.ts`** — Writes\u002Freads token holdings for redemption (e.g. `src\u002Fdata\u002Ftoken-holding.json`).\n\n### Security and On-Chain\n\n- **`src\u002Fsecurity\u002Fallowance.ts`** — USDC and CTF approvals. Called at startup so the polymarket trading bot can trade.\n- **`src\u002Fsecurity\u002FcreateCredential.ts`** \u002F **`src\u002Fsecurity\u002FvalidatePrivateKey.ts`** — CLOB API credential creation and key validation.\n\n### Data Files (generated at runtime)\n\n- **`src\u002Fdata\u002Fcredential.json`** — CLOB API credentials (created on first run).\n- **`src\u002Fdata\u002Fcopytrade-state.json`** — Per-slug state (prices, timestamps, conditionId, buy counts).\n- **`src\u002Fdata\u002Ftoken-holding.json`** — Token holdings for redemption.\n\n---\n\n## Project Structure\n\n| Path | Role |\n|------|------|\n| `src\u002Findex.ts` | Entry: credentials, CLOB, allowances, min balance, start polymarket trading bot (`CopytradeArbBot`). |\n| `src\u002Fconfig\u002Findex.ts` | Loads `.env`; exposes config for the polymarket trading bot. |\n| `src\u002Forder-builder\u002Fcopytrade.ts` | **CopytradeArbBot**: 15m slugs, WebSocket, predictor → first-side + hedge; state. |\n| `src\u002Forder-builder\u002Fhelpers.ts` | Order-building helpers (prices, sizes, options). |\n| `src\u002Forder-builder\u002Ftypes.ts` | Shared types for orders and bot. |\n| `src\u002Fproviders\u002Fclobclient.ts` | CLOB client singleton. |\n| `src\u002Fproviders\u002FwebsocketOrderbook.ts` | WebSocket orderbook; best bid\u002Fask by token ID. |\n| `src\u002Futils\u002FpricePredictor.ts` | **AdaptivePricePredictor**: direction, confidence, signal. |\n| `src\u002Futils\u002Fredeem.ts` | CTF redemption and resolution checks. |\n| `src\u002Futils\u002Fholdings.ts` | Token holdings for redemption. |\n| `src\u002Futils\u002Flogger.ts` | Logging used by the polymarket trading bot. |\n| `src\u002Futils\u002Fbalance.ts` | Min USDC balance wait logic. |\n| `src\u002Fsecurity\u002Fallowance.ts` | USDC\u002FCTF approvals. |\n| `src\u002Fsecurity\u002FcreateCredential.ts` | CLOB credential creation. |\n| `src\u002Fsecurity\u002FvalidatePrivateKey.ts` | Private key validation. |\n| `src\u002Fdata\u002F*.json` | Credentials, state, holdings (generated). |\n\n---\n\n## Extending the Polymarket Trading Bot\n\n- **New markets** — Add symbols to `COPYTRADE_MARKETS`. The polymarket trading bot only supports 15m Up\u002FDown slugs resolved via Gamma; other market types would require slug resolution and possibly different predictor logic.\n- **Predictor** — Replace or wrap `AdaptivePricePredictor` in `src\u002Futils\u002FpricePredictor.ts`, or add features\u002Fweights. The polymarket trading bot expects `direction`, `confidence`, and `signal` (BUY_UP \u002F BUY_DOWN \u002F HOLD).\n- **Order logic** — First-side and hedge prices\u002Fsizes are in `src\u002Forder-builder\u002Fcopytrade.ts`. Change formulas (e.g. hedge at something other than `0.98 − firstSidePrice`) or add filters (e.g. min confidence) there.\n- **Redemption** — Use or adapt `src\u002Futils\u002Fredeem.ts` and the redeem scripts; the polymarket trading bot does not call redemption itself.\n","这是一个用于Polymarket平台上15分钟涨跌预测市场的自动交易机器人。其核心功能包括从实时订单簿中预测市场方向，并以最佳卖价下单，同时在相反方向进行对冲，从而实现24\u002F7不间断的自动化交易。该机器人采用TypeScript编写，利用了Polymarket CLOB API和WebSocket技术来获取最新的订单簿数据，并配备了一个可配置的自适应价格预测器。适用于希望在不直接操作Polymarket用户界面的情况下执行高频套利策略的交易者及开发者。此外，项目还提供了完整的堆栈支持，便于扩展至其他市场或进一步开发。",2,"2026-05-18 11:13:06","CREATED_QUERY"]