[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-82067":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":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":21,"hasPages":19,"topics":22,"createdAt":10,"pushedAt":10,"updatedAt":29,"readmeContent":30,"aiSummary":31,"trendingCount":16,"starSnapshotCount":16,"syncStatus":32,"lastSyncTime":33,"discoverSource":34},82067,"weather-prediction-bot","Signal-Trade-Core\u002Fweather-prediction-bot","Signal-Trade-Core","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","",null,"TypeScript",367,5235,101,1,0,177,10,false,"main",true,[23,24,25,26,27,28],"polymarket-bot","polymarket-trading-bot","polymarket-weather-trading-bot","trading-bot","weather-bot","weather-prediction","2026-06-12 02:04:22","# Polymarket Weather Trading Bot\n\nNode.js \u002F TypeScript trading automation for Polymarket daily temperature markets. The bot fuses multi-region weather forecasts (NWS for US cities, Open-Meteo for international cities) with Polymarket CLOB pricing: it maps each city's forecast max temperature to the matching market bucket, then either prints read-only signals, paper-trades against a local JSON ledger, or posts real CLOB limit orders.\n\n## Overview\n\nFor each configured city, the bot:\n\n1. Pulls a daily-max forecast for the next few days from the right weather provider.\n2. Looks up the matching Polymarket \"Highest temperature in {city} on {date}\" event.\n3. Finds the temperature bucket (Yes\u002FNo market) whose range contains the forecast.\n4. Compares the YES price to `ENTRY_THRESHOLD` and `EXIT_THRESHOLD` and acts according to the selected mode.\n\nEverything is driven by `.env` at runtime; there is no `config.json` in the primary flows.\n\n---\n\n## Key features\n\n- **Multi-region weather data**: NWS observations + hourly forecasts for US cities (°F), Open-Meteo `temperature_2m_max` (with `timezone=auto`) for international cities (°C). The provider, coordinates, and temperature unit are declared per city in `src\u002Fnws.ts` (`LOCATIONS`).\n- **Unit-safe bucket matching**: each city declares `tempUnit` (`F` or `C`); the parser tags every Polymarket bucket question with its own unit, and the strategy only matches buckets whose unit equals the city's. °F and °C markets are never cross-matched.\n- **Three execution modes**:\n  - `signal` (dry-run) — no orders, no state changes.\n  - `paper` (`--live`) — simulated PnL written to `simulation.json`.\n  - `execute` (`--execute`) — real CLOB limit orders on Polygon.\n- **Proxy wallet support**: MetaMask signer with Polymarket proxy\u002FSafe funder via `USE_PROXY_WALLET=true` and `SIGNATURE_TYPE=2`. Signature types 0 (EOA), 1 (Polymarket proxy\u002FMagic), 2 (Gnosis Safe) all supported.\n- **Live wallet check**: before any `execute` run the bot reads pUSD collateral via the CLOB `getBalanceAllowance` endpoint (with a Polygon `eth_call` fallback) and prints the current wallet balance.\n- **Loop mode**: `--interval N` runs the strategy every N minutes until Ctrl+C; `npm run trade` is a 30-minute live preset.\n\n## Architecture\n\n### Technology stack\n\n- **Runtime**: Node.js 18+, TypeScript 5\n- **Chain**: Polygon (chainId 137)\n- **Execution**: Polymarket CLOB V2 via `@polymarket\u002Fclob-client-v2`\n- **Signing**: `@ethersproject\u002Fwallet` (EOA \u002F proxy \u002F Safe)\n- **Weather data**: `api.weather.gov` for US cities; `api.open-meteo.com` for international cities (no API key required)\n- **Markets**: `gamma-api.polymarket.com` for event + price lookup; CLOB for orders and balances\n- **CLI \u002F output**: `yargs`, `chalk`, `sleek-pretty` (boxed status panels)\n- **Config**: `.env` only for the primary flows\n\n### System flow\n\n```\nWeather forecast (NWS \u002F Open-Meteo) + city list\n  → Polymarket event for date (gamma-api)\n    → Map daily-max temp to bucket (unit-aware)\n      → Compare YES to ENTRY_THRESHOLD \u002F EXIT_THRESHOLD\n        → Signal | Update simulation.json | Place CLOB limit order\n```\n\n## Installation\n\n### Prerequisites\n\n- Node.js 18+ and npm\n- Outbound network access to `api.weather.gov`, `api.open-meteo.com`, `gamma-api.polymarket.com`, `clob.polymarket.com`, and `polygon-rpc.com`\n- For live mode: a wallet funded with **Polymarket USD (pUSD)** collateral on Polygon and CLOB trading allowance set up, with the keys provided only via environment variables\n\n### Setup\n\n1. **Clone the repository and enter the directory**\n\n2. **Install dependencies**\n\n   ```bash\n   npm install\n   ```\n\n3. **Configure environment**\n\n   ```bash\n   cp .env.example .env\n   ```\n\n   Edit `.env`. Example:\n\n   ```env\n   POLYMARKET_PRIVATE_KEY=0xYOUR_METAMASK_PRIVATE_KEY\n   POLYMARKET_PROXY_WALLET_ADDRESS=0xYOUR_POLYMARKET_PROXY_WALLET\n   USE_PROXY_WALLET=true\n   SIGNATURE_TYPE=2\n   ENTRY_THRESHOLD=0.15\n   EXIT_THRESHOLD=0.45\n   MAX_TRADES_PER_RUN=5\n   MIN_HOURS_TO_RESOLUTION=2\n   LOCATIONS=\"nyc,london,hong-kong,seattle\"\n   ```\n\n4. **Credentials**\n\n   For live trading, double-check the private key, proxy address, pUSD balance, and CLOB trading allowance. Always test with `npm run signal` and `npm run paper` before `npm run execute` or `npm run trade`.\n\n## Configuration\n\n### Environment variables\n\n| Variable | Type | Default | Description |\n|----------|------|---------|-------------|\n| `POLYMARKET_PRIVATE_KEY` | string | **required** | EOA \u002F MetaMask private key used to sign (64 hex chars, with or without `0x`) |\n| `POLYMARKET_PROXY_WALLET_ADDRESS` | string | **required** | Polymarket proxy \u002F funder address from `polymarket.com\u002Fsettings` (`0x` + 40 hex) |\n| `USE_PROXY_WALLET` | boolean | `false` | When `true`, the proxy\u002FSafe at `POLYMARKET_PROXY_WALLET_ADDRESS` funds the trades |\n| `SIGNATURE_TYPE` | `0` \\| `1` \\| `2` | derived | `0` EOA, `1` Polymarket proxy (Magic), `2` Gnosis Safe. If unset and `USE_PROXY_WALLET=true`, defaults to `2` |\n| `ENTRY_THRESHOLD` | number | `0.15` | Buy when the matched-bucket YES price is below this |\n| `EXIT_THRESHOLD` | number | `0.45` | Exit an open position when YES reaches or exceeds this |\n| `MAX_TRADES_PER_RUN` | number | `5` | Hard cap on new entries per run (existing-position skips still count toward iteration) |\n| `MIN_HOURS_TO_RESOLUTION` | number | `2` | Skip markets resolving sooner than this many hours from now |\n| `LOCATIONS` | string | `nyc,chicago,miami,dallas,seattle,atlanta,london,hong-kong,tokyo,singapore,los-angeles,paris` | Comma-separated city keys to scan |\n\n`POLYMARKET_PRIVATE_KEY` and `POLYMARKET_PROXY_WALLET_ADDRESS` are validated at startup; the bot exits early with a formatted error panel if either is missing or malformed.\n\n### Supported cities\n\nUS (NWS forecast, °F Polymarket buckets):\n\n- `nyc`, `chicago`, `miami`, `dallas`, `seattle`, `atlanta`\n\nUS (Open-Meteo fallback, °F buckets):\n\n- `boston`, `houston`, `los-angeles`, `san-francisco`, `washington-dc`, `philadelphia`, `phoenix`, `denver`, `las-vegas`\n\nInternational (Open-Meteo forecast, °C Polymarket buckets):\n\n- `london`, `hong-kong`, `tokyo`, `singapore`, `paris`, `berlin`, `madrid`, `rome`, `amsterdam`, `toronto`, `sydney`, `mexico-city`, `dubai`\n\nThe authoritative list is `LOCATIONS` in `src\u002Fnws.ts`. Each entry declares its `lat` \u002F `lon`, display `name`, weather `provider` (`nws` | `open-meteo`), and `tempUnit` (`F` | `C`). Polymarket slugs are the same as the city key, so `hong-kong` (with hyphen) is required — `hongkong` will not resolve to a market.\n\n### Strategy parameters (hardcoded)\n\nThese live in `src\u002Fstrategy.ts` and are intentionally not env-driven:\n\n| Constant | Value | Meaning |\n|---|---|---|\n| `POSITION_PCT` | `0.05` | Each entry sizes at 5% of the current balance |\n| `MIN_PAPER_ORDER_USD` | `$0.50` | Floor for paper-mode order size |\n| `MIN_EXECUTE_ORDER_USD` | `$1.00` | Floor for live CLOB order size |\n| Scan window | next 4 days | The strategy iterates `i = 0..3` daily forecasts per city |\n| Buy limit price | `min(price + 0.03, 0.99)` | Crosses the spread by ~3¢ to improve fill odds |\n| Sell limit price | `max(currentPrice - 0.01, 0.01)` | Crosses the spread by ~1¢ on exits |\n\n## Usage\n\n### Run modes\n\n| Mode | Command | Real orders? | Side effects |\n|------|---------|---|---|\n| Signal | `npm run signal` | No | None |\n| Paper | `npm run paper` | No | Updates `simulation.json` |\n| One-shot live | `npm run execute` | Yes (single pass) | CLOB orders + `simulation.json` |\n| Live on interval | `npm run trade` | Yes | CLOB orders every 30 min until Ctrl+C |\n\n```bash\nnpm run signal\nnpm run paper\nnpm run execute\nnpm run trade\n```\n\n### Other scripts\n\n```bash\nnpm run positions   # show open positions and PnL from simulation.json\nnpm run reset       # delete simulation.json (restart paper balance at $1000)\nnpm run build       # tsc only\n```\n\n### CLI flags\n\nAll scripts compile with `tsc` first and then invoke `node dist\u002Findex.js` with flags:\n\n| Flag | Type | Description |\n|---|---|---|\n| `--execute` | boolean | Place real limit orders on Polymarket CLOB (requires pUSD + allowance) |\n| `--live` | boolean | Paper trading — update `simulation.json`, no on-chain orders |\n| `--interval N` | number | With `--execute` or `--live`, run every N minutes (Ctrl+C to stop) |\n| `--positions` | boolean | Print open positions with current price and unrealized PnL |\n| `--reset` | boolean | Reset `simulation.json` to the $1000 starting balance |\n\n`--execute` and `--live` are mutually exclusive; passing both exits with an error.\n\n## Technical details\n\n### Entry logic\n\n1. For each city in `LOCATIONS` (filtered by `LOCATIONS` env), pull daily-max temps for today + the next 3 days.\n2. For each (city, date), GET `gamma-api.polymarket.com\u002Fevents?slug=highest-temperature-in-{city}-on-{month}-{day}-{year}`.\n3. Skip if the event resolves in fewer than `MIN_HOURS_TO_RESOLUTION` hours.\n4. Walk the event's markets and pick the one whose bucket range contains the rounded forecast, **only if** the bucket's unit matches the city's `tempUnit`.\n5. If YES is below `ENTRY_THRESHOLD`, the position isn't already open, `MAX_TRADES_PER_RUN` hasn't been hit, and the sized order is above the per-mode minimum, open the position (paper or CLOB).\n\n### Exit logic\n\nFor every open position the bot checks the current YES price from gamma. If it is at or above `EXIT_THRESHOLD`, the bot sells (CLOB limit on `execute`, virtual close on `paper`), records the trade, and updates win\u002Floss counters.\n\n### State\n\n- **Paper \u002F simulation**: `simulation.json` at the project root tracks virtual balance, peak balance, total trades, wins, losses, open positions, and trade history. The file is gitignored and auto-created on first run (`$1000` starting balance).\n- **Live**: positions are *also* persisted to `simulation.json` so that `--positions` and exit detection work across runs; on `execute` the on-chain order is the source of truth and the local file is just a tracker.\n\n## Project structure\n\n```\nPolymarket-Weather-Bot\u002F\n├── src\u002F\n│   ├── index.ts          # CLI entry, validateKeys, mode dispatch\n│   ├── config.ts         # .env loading, defaults, getActiveLocations\n│   ├── nws.ts            # LOCATIONS + getForecast (NWS + Open-Meteo)\n│   ├── polymarket.ts     # gamma-api event \u002F price lookup\n│   ├── clob.ts           # CLOB client init, signing, buy\u002Fsell limit helpers\n│   ├── walletBalance.ts  # pUSD balance via CLOB (with Polygon eth_call fallback)\n│   ├── strategy.ts       # entry\u002Fexit scan, sizing, position tracking\n│   ├── parsing.ts        # parseTempBucket (°F + °C), hoursUntilResolution\n│   ├── simState.ts       # load\u002Fsave\u002Freset simulation.json\n│   ├── time.ts           # month names\n│   └── colors.ts         # chalk + sleek-pretty panel\u002Fstat\u002Fbadge helpers\n├── dist\u002F                  # tsc output (gitignored)\n├── simulation.json        # local paper state (gitignored, $1000 default)\n├── package.json\n├── tsconfig.json\n├── .env.example\n└── README.md\n```\n\n## API integration\n\n### CLOB\n\nOrders use `@polymarket\u002Fclob-client-v2` with the configured signer and, when `SIGNATURE_TYPE` is `1` or `2`, the proxy\u002FSafe at `POLYMARKET_PROXY_WALLET_ADDRESS` as funder. API keys are derived on demand (`deriveApiKey`) and created via `createApiKey` as a fallback. All entries and exits go in as `GTC` limit orders.\n\n### Weather providers\n\n- **NWS** (`api.weather.gov`, US cities): hourly forecast + recent station observations, daily-max derived in code. Respect NWS terms of use and rate limits; the bot identifies itself with a `User-Agent: weatherbot-ts\u002F1.0` header.\n- **Open-Meteo** (`api.open-meteo.com`, international cities): `daily=temperature_2m_max` with `timezone=auto`, so the daily max aligns with the city's local calendar day — the same basis Polymarket uses for resolution. No API key required.\n\n### Adding a new city\n\n1. Find the resolution source for the market (the description on Polymarket usually names the weather station, e.g. London City Airport \u002F Hong Kong Observatory).\n2. Add an entry to `LOCATIONS` in `src\u002Fnws.ts` with the station coordinates, the right `tempUnit`, and `provider: \"open-meteo\"` (or `\"nws\"` if it's a new US city, in which case also add NWS gridpoint and station ID).\n3. Make sure the key you use matches Polymarket's URL slug for that city (e.g. `hong-kong`, not `hongkong`).\n4. Add the key to your `.env` `LOCATIONS` list.\n\n## Monitoring and logging\n\n- Console output uses `chalk` + `sleek-pretty` for boxed panels: a header per city\u002Fdate, a \"Matched Bucket\" panel, an \"Entry Signal\" panel, a \"Run Summary\" panel, and a final dry-run reminder when running in signal mode.\n- Paper mode: inspect `simulation.json` directly or run `npm run positions`.\n- Live mode: every `execute` run prints a \"Live Wallet Check\" panel with the current pUSD balance and uses that figure for sizing.\n\n## Risk considerations\n\n1. **Forecast error**: NWS \u002F Open-Meteo can disagree with the official resolution source Polymarket uses (e.g. Wunderground for London).\n2. **Liquidity and slippage**: temperature-bucket order books can be thin, especially for tail buckets.\n3. **Time to resolution**: short horizons increase sensitivity to price moves; the `MIN_HOURS_TO_RESOLUTION` guard exists for this reason.\n4. **Live credentials**: a mistake in `POLYMARKET_PRIVATE_KEY` \u002F `POLYMARKET_PROXY_WALLET_ADDRESS` or insufficient allowance can still move real funds. Validate with `signal` and `paper` first.\n\n**Operational suggestion**: run `signal` → `paper` → small-size `execute` → scheduled `trade` in that order, and watch a few full cycles before scaling size.\n\n## Development\n\n```bash\nnpm run build      # type-check + emit to dist\u002F\nnpm run signal     # dry-run end-to-end smoke test\n```\n\nThe project is plain TypeScript compiled with `tsc`; there is no bundler. Source lives in `src\u002F`, output goes to `dist\u002F`.\n\n## Support\n\nUse repository issues for bugs and feature requests. For CLOB and proxy-wallet behavior, refer to Polymarket's official documentation.\n\n---\n\n**Disclaimer**: This software is provided as-is, without warranty. Prediction markets and digital assets involve substantial risk of loss. Use only capital you can afford to lose and comply with applicable laws in your jurisdiction.\n\n**Version**: 1.0.0  \n**Last updated**: May 2026\n","Polymarket Weather Trading Bot 是一个用于 Polymarket 日温度市场的自动化交易机器人。它结合了多区域天气预报（美国城市使用NWS，国际城市使用Open-Meteo）和Polymarket的CLOB定价机制，将每个城市的预测最高温度映射到相应的市场区间，并根据设定的阈值执行只读信号、模拟交易或真实限价订单。项目采用TypeScript编写，支持三种执行模式：信号模式（无实际操作）、纸面交易（模拟盈亏记录）和执行模式（在Polygon链上进行真实交易）。此外，该机器人还支持多种钱包签名方式及代理钱包功能，适用于希望利用天气数据自动参与Polymarket温度预测市场的用户。",2,"2026-06-01 03:57:12","CREATED_QUERY"]