From e9baa4ce6a061448d2b4ac469baff041796a1387 Mon Sep 17 00:00:00 2001 From: Pushpenderrathore Date: Mon, 16 Feb 2026 22:10:32 +0530 Subject: [PATCH 1/6] help & project_source_dump included --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 9144a21..ba1c70b 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,8 @@ env/ .coverage coverage.xml htmlcov/ +help +project_source_dump.txt # IDE / OS files .vscode/ From d7e0fac358705465ca63dbf437041b1e0e4ca97d Mon Sep 17 00:00:00 2001 From: Pushpenderrathore Date: Mon, 16 Feb 2026 22:40:11 +0530 Subject: [PATCH 2/6] From library imported Position --- strategies/base_strategy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strategies/base_strategy.py b/strategies/base_strategy.py index 3b415a9..e85d4f5 100644 --- a/strategies/base_strategy.py +++ b/strategies/base_strategy.py @@ -53,7 +53,7 @@ async def on_tick(self, prices): from lib.terminal_utils import LogBuffer, log from lib.market_manager import MarketManager, MarketInfo from lib.price_tracker import PriceTracker -from lib.position_manager import PositionManager +from lib.position_manager import PositionManager , Position from src.bot import TradingBot from src.websocket_client import OrderbookSnapshot From aa43837e15ade80d24ab8dc5113180aa30768902 Mon Sep 17 00:00:00 2001 From: Pushpenderrathore Date: Mon, 16 Feb 2026 23:29:45 +0530 Subject: [PATCH 3/6] Harden CLI runner: add private key validation, improve exception handling, and enhance debug logging --- apps/flash_crash_runner.py | 48 +++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/apps/flash_crash_runner.py b/apps/flash_crash_runner.py index 793d4a1..37d207a 100644 --- a/apps/flash_crash_runner.py +++ b/apps/flash_crash_runner.py @@ -47,15 +47,13 @@ import os import sys +import re import asyncio import argparse import logging +logger = logging.getLogger(__name__) from pathlib import Path -# Suppress noisy logs -logging.getLogger("src.websocket_client").setLevel(logging.WARNING) -logging.getLogger("src.bot").setLevel(logging.WARNING) - # Auto-load .env file from dotenv import load_dotenv load_dotenv() @@ -121,8 +119,17 @@ def main(): # Enable debug logging if requested if args.debug: - logging.basicConfig(level=logging.DEBUG) + logging.basicConfig( + level=logging.DEBUG, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s" + ) logging.getLogger("src.websocket_client").setLevel(logging.DEBUG) + else: + logging.basicConfig( + level=logging.INFO, + format="%(message)s" + ) + logging.getLogger("src.websocket_client").setLevel(logging.WARNING) # Check environment private_key = os.environ.get("POLY_PRIVATE_KEY") @@ -132,14 +139,25 @@ def main(): print(f"{Colors.RED}Error: POLY_PRIVATE_KEY and POLY_PROXY_WALLET must be set{Colors.RESET}") print("Set them in .env file or export as environment variables") sys.exit(1) + + # Validate private key format + if not re.fullmatch(r"0x[a-fA-F0-9]{64}", private_key): + print(f"{Colors.RED}⚠ Invalid private key format.{Colors.RESET}") + print("Must be 0x + 64 hexadecimal characters.") + sys.exit(1) # Create bot config = Config.from_env() - bot = TradingBot(config=config, private_key=private_key) - - if not bot.is_initialized(): - print(f"{Colors.RED}Error: Failed to initialize bot{Colors.RESET}") + try: + bot = TradingBot(config=config, private_key=private_key) + except ValueError as e: + print(f"{Colors.RED}⚠ Configuration Error: {e}{Colors.RESET}") + print("Check your POLY_PRIVATE_KEY in .env") sys.exit(1) + except Exception as e: + print(f"{Colors.RED}⚠ Unexpected initialization error: {e}{Colors.RESET}") + sys.exit(1) + # Create strategy config strategy_config = FlashCrashConfig( @@ -171,12 +189,16 @@ def main(): try: asyncio.run(strategy.run()) except KeyboardInterrupt: - print("\nInterrupted") + print("\nInterrupted by user") except Exception as e: - print(f"\n{Colors.RED}Error: {e}{Colors.RESET}") - import traceback - traceback.print_exc() + if args.debug: + logger.exception("Unhandled runtime error") + else: + print(f"\n{Colors.RED} Runtime Error: {e}{Colors.RESET}") + print("Run with --debug to see full traceback.") sys.exit(1) + finally: + print("Shutting down...") if __name__ == "__main__": From 7565ae56d221699f02fc7c5842b57a9bff281f6e Mon Sep 17 00:00:00 2001 From: Pushpenderrathore Date: Tue, 17 Feb 2026 23:48:14 +0530 Subject: [PATCH 4/6] Modified --- README.md | 153 +++++++++++++++++++++++++++++-------------------- README1.md | 163 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 254 insertions(+), 62 deletions(-) create mode 100644 README1.md diff --git a/README.md b/README.md index 87c42bd..425b0e9 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,96 @@ -# Polymarket Bot | Polymarket Trading Bot | Polymarket Arbitrage Bot +# Polymarket Bot: Automated Trading & Arbitrage System -Polymarket Bot, Polymarket Trading Bot, Polymarket Arbitrage Bot, Polymarket Automatic Trading Bot -Advanced Polymarket Trading Bot (Python) – A high-performance automated trading system for Polymarket prediction markets, built in Python. Supports gasless trading, real-time WebSocket market data streaming, and fully automated arbitrage and volatility strategies optimized for short-term and high-frequency trading environments. Designed for efficient capital allocation, low-latency execution, and scalable quantitative crypto trading. +An advanced Python trading bot for Polymarket prediction markets. This system provides high-performance automation, including gasless trading, real-time WebSocket market data, and sophisticated arbitrage and volatility strategies. Designed for efficient capital allocation, low-latency execution, and scalable quantitative crypto trading in active and high-frequency environments. -Status: Live trading enabled. Dashboard available at configured domain. +**Status:** Live trading enabled. Dashboard available at your configured domain. -Read article here: https://medium.com/@benjamin.bigdev/high-roi-polymarket-arbitrage-in-2026-programmatic-dutch-book-strategies-bots-and-portfolio-41372221bb79 +_Read the [Medium article](https://medium.com/@benjamin.bigdev/high-roi-polymarket-arbitrage-in-2026-programmatic-dutch-book-strategies-bots-and-portfolio-41372221bb79) for more insight._ +--- -## Contact info +## Table of Contents +1. [Contact](#contact) +2. [Demo Video](#demo-video) +3. [Strategy Overview](#strategy-overview) + - [Directional/Speculative Strategy](#directionalspeculative-strategy) + - [Pure Arbitrage](#pure-arbitrage) +4. [Status](#status) +5. [Features](#features) +6. [Setup](#setup) +7. [Configuration](#configuration) +8. [Contract Approvals](#contract-approvals) +9. [Geo-Restrictions & Proxy Setup](#geo-restrictions--proxy-setup) +10. [Documentation](#documentation) +11. [License](#license) +--- +## Contact -Telegram: [@BenjaminCup](https://t.me/BenjaminCup) +- Telegram: [@BenjaminCup](https://t.me/BenjaminCup) +--- -## Video +## Demo Video +Watch the video demonstration: https://github.com/user-attachments/assets/f06d66ee-4408-4076-91c3-5476d780cf7a -## Strategy +--- -Core Steps (Binary Yes/No market): +## Strategy Overview -Identify a directional conviction (“Yes” or “No” is undervalued). -Execute a sizable buy of the favored outcome when its price is around $0.60 (opposite side therefore ~$0.40). In thin order books this visibly moves the favored price to $0.61–$0.62 and the opposite to $0.38–$0.39. -Rely on other participants observing the price action (and possibly your on-chain wallet activity) to interpret it as strong conviction → retail/FOMO buying pushes the favored outcome to ~$0.70 and the opposite to ~$0.30. -At the widened spread, buy the now-cheap opposite outcome at ~$0.30. -Claimed P&L: $0.10 gross per share equivalent (difference created by the spread widening you helped engineer) minus ~$0.03 in assumed fees/gas → net ~$0.07 per unit. +### Directional/Speculative Strategy (Binary Yes/No Markets) +1. **Formulate a Directional Conviction:** Identify if "Yes" or "No" is undervalued. +2. **Initiate Position:** Buy the favored outcome when near $0.60. In thin books, this moves the price to ~$0.61–$0.62. +3. **Market Impact:** Others interpret this as strong conviction; retail/FOMO may push the price to ~$0.70. +4. **Counter-Trade:** Buy the now-cheap opposite outcome (~$0.30). +5. **Profit Potential:** ~$0.10 gross per share less estimated $0.03 fees/gas, netting ~$0.07/unit. -This is not arbitrage. It is a speculative momentum + mean-reversion hybrid that attempts to influence short-term order flow. - -Strategy is Not for sale but going to share it to customers. - -Pure arbitrage: when YES + NO token prices sum to less than $1.00, buy both. One token always pays out $1.00, guaranteeing profit regardless of outcome. +*Note: This is a speculative momentum/mean-reversion approach, not pure arbitrage. The core strategy is not for public sale but may be shared with customers.* +### Pure Arbitrage +When YES + NO token prices sum to under $1.00, purchase both: ``` Example: YES @ $0.48 + NO @ $0.49 = $0.97 cost -Payout = $1.00 (guaranteed) +Guaranteed payout = $1.00 Profit = $0.03 per dollar (3.09%) ``` + +--- + ## Status -Live trading enabled. Dashboard available at configured domain. +- Live trading enabled +- Dashboard accessible via your configured domain + +--- ## Features -- Real-time WebSocket price monitoring (6 parallel connections, up to 1500 markets) -- Automatic arbitrage detection and execution -- **Low-latency async order execution** (native async HTTP with HTTP/2, parallel order signing) -- Order monitoring with 10-second timeout and auto-cancellation -- Market filtering by liquidity ($10k+ default) and resolution date (7 days default) -- Web dashboard with live order visibility (HTTPS with auto SSL) -- Slack notifications for trades -- SOCKS5 proxy support for geo-restricted order placement +- Real-time WebSocket price monitoring (6 parallel connections, covers up to 1500 markets) +- Automatic arbitrage detection & execution +- **Low-latency async order execution** (native async HTTP/2, parallel signing) +- Order monitoring with 10s timeout & auto-cancel +- Market filtering: by liquidity (default $10k+) and event resolution (default 7 days) +- Web dashboard with live visibility (HTTPS, auto SSL) +- Slack trades notifications +- SOCKS5 proxy support for geo-restricted execution + +--- ## Setup ```bash -# Clone +# Clone repo git clone https://github.com/VectorPulser/polymarket-trading-bot.git cd rarb # Install dependencies pip install -e . -# Configure +# Configure environment cp .env.example .env # Edit .env with your settings @@ -81,83 +105,88 @@ print(f'POLY_API_SECRET={creds.api_secret}') print(f'POLY_API_PASSPHRASE={creds.api_passphrase}') " -# Approve Polymarket contracts (one-time setup) +# Approve contracts (one-time) python scripts/approve_usdc.py -# Run +# Run bot rarb run --live --realtime ``` +--- + ## Configuration -Required environment variables: +Key environment variables in `.env`: ```bash # Wallet -PRIVATE_KEY=0x... # Your wallet private key -WALLET_ADDRESS=0x... # Your wallet address +PRIVATE_KEY=0x... # Your wallet private key +WALLET_ADDRESS=0x... # Your wallet address -# Polymarket L2 API Credentials (generate with script above) +# Polymarket L2 API Credentials (see setup) POLY_API_KEY=... POLY_API_SECRET=... POLY_API_PASSPHRASE=... -# Trading Parameters -MIN_PROFIT_THRESHOLD=0.005 # 0.5% minimum profit -MAX_POSITION_SIZE=100 # Max $100 per trade -MIN_LIQUIDITY_USD=10000 # $10k minimum market liquidity -MAX_DAYS_UNTIL_RESOLUTION=7 # Skip markets resolving later -NUM_WS_CONNECTIONS=6 # WebSocket connections (250 markets each) -DRY_RUN=true # Set to false for live trading +# Trading parameters +MIN_PROFIT_THRESHOLD=0.005 # 0.5% min profit +MAX_POSITION_SIZE=100 # $100 max per trade +MIN_LIQUIDITY_USD=10000 # $10k min market liquidity +MAX_DAYS_UNTIL_RESOLUTION=7 # Ignore long-resolving markets +NUM_WS_CONNECTIONS=6 # WebSockets (250 markets ea) +DRY_RUN=true # Set false to enable live trading -# Dashboard (optional - omit for no auth) +# Dashboard (optional) DASHBOARD_USERNAME=admin DASHBOARD_PASSWORD=... ``` +Refer to `.env.example` for a complete list of options. -See `.env.example` for all available options. +--- ## Contract Approvals -Before trading, you must approve Polymarket's smart contracts to spend your USDC.e: +Prior to trading, allow Polymarket contracts to spend your USDC.e: ```bash -# Run the approval script (requires PRIVATE_KEY in environment) +# Requires PRIVATE_KEY set in your environment python scripts/approve_usdc.py ``` - -This approves: +Approves: - CTF Exchange - Neg Risk Exchange - Conditional Tokens - Neg Risk Adapter -## Geo-Restrictions +--- -Polymarket blocks US IP addresses for order placement. The recommended architecture: +## Geo-Restrictions & Proxy Setup -- **Bot server (us-east-1)**: Low-latency WebSocket connection for price monitoring -- **Proxy server (ca-central-1 Montreal)**: SOCKS5 proxy for order placement +U.S. IPs are blocked for order placement. Recommended: +- **Bot server (us-east-1):** For fast WebSocket data +- **Proxy server (ca-central-1 Montréal):** SOCKS5 proxy for order routing -Configure the proxy in your `.env`: +Configure your proxy in `.env`: ```bash SOCKS5_PROXY_HOST=your-proxy-ip SOCKS5_PROXY_PORT=1080 SOCKS5_PROXY_USER=rarb SOCKS5_PROXY_PASS=your-password ``` +Deployment scripts: see `infra/` (OpenTofu + Ansible). -See `infra/` for OpenTofu + Ansible deployment scripts. - - +--- ## Documentation -See [PRD.md](PRD.md) for full product requirements and technical architecture. +For product requirements and technical architecture, see [PRD.md](PRD.md). -## License +--- -MIT +## License +This project is licensed under the MIT License. +--- +Let me know if you need further refinement or a different format! \ No newline at end of file diff --git a/README1.md b/README1.md new file mode 100644 index 0000000..87c42bd --- /dev/null +++ b/README1.md @@ -0,0 +1,163 @@ +# Polymarket Bot | Polymarket Trading Bot | Polymarket Arbitrage Bot + +Polymarket Bot, Polymarket Trading Bot, Polymarket Arbitrage Bot, Polymarket Automatic Trading Bot +Advanced Polymarket Trading Bot (Python) – A high-performance automated trading system for Polymarket prediction markets, built in Python. Supports gasless trading, real-time WebSocket market data streaming, and fully automated arbitrage and volatility strategies optimized for short-term and high-frequency trading environments. Designed for efficient capital allocation, low-latency execution, and scalable quantitative crypto trading. + +Status: Live trading enabled. Dashboard available at configured domain. + +Read article here: https://medium.com/@benjamin.bigdev/high-roi-polymarket-arbitrage-in-2026-programmatic-dutch-book-strategies-bots-and-portfolio-41372221bb79 + + +## Contact info + + + +Telegram: [@BenjaminCup](https://t.me/BenjaminCup) + + +## Video + +https://github.com/user-attachments/assets/f06d66ee-4408-4076-91c3-5476d780cf7a + +## Strategy + +Core Steps (Binary Yes/No market): + +Identify a directional conviction (“Yes” or “No” is undervalued). +Execute a sizable buy of the favored outcome when its price is around $0.60 (opposite side therefore ~$0.40). In thin order books this visibly moves the favored price to $0.61–$0.62 and the opposite to $0.38–$0.39. +Rely on other participants observing the price action (and possibly your on-chain wallet activity) to interpret it as strong conviction → retail/FOMO buying pushes the favored outcome to ~$0.70 and the opposite to ~$0.30. +At the widened spread, buy the now-cheap opposite outcome at ~$0.30. +Claimed P&L: $0.10 gross per share equivalent (difference created by the spread widening you helped engineer) minus ~$0.03 in assumed fees/gas → net ~$0.07 per unit. + +This is not arbitrage. It is a speculative momentum + mean-reversion hybrid that attempts to influence short-term order flow. + +Strategy is Not for sale but going to share it to customers. + +Pure arbitrage: when YES + NO token prices sum to less than $1.00, buy both. One token always pays out $1.00, guaranteeing profit regardless of outcome. + +``` +Example: +YES @ $0.48 + NO @ $0.49 = $0.97 cost +Payout = $1.00 (guaranteed) +Profit = $0.03 per dollar (3.09%) +``` +## Status + +Live trading enabled. Dashboard available at configured domain. + +## Features + +- Real-time WebSocket price monitoring (6 parallel connections, up to 1500 markets) +- Automatic arbitrage detection and execution +- **Low-latency async order execution** (native async HTTP with HTTP/2, parallel order signing) +- Order monitoring with 10-second timeout and auto-cancellation +- Market filtering by liquidity ($10k+ default) and resolution date (7 days default) +- Web dashboard with live order visibility (HTTPS with auto SSL) +- Slack notifications for trades +- SOCKS5 proxy support for geo-restricted order placement + +## Setup + +```bash +# Clone +git clone https://github.com/VectorPulser/polymarket-trading-bot.git +cd rarb + +# Install dependencies +pip install -e . + +# Configure +cp .env.example .env +# Edit .env with your settings + +# Generate Polymarket API credentials +python -c " +from py_clob_client.client import ClobClient +import os +client = ClobClient('https://clob.polymarket.com', key=os.environ['PRIVATE_KEY'], chain_id=137) +creds = client.create_or_derive_api_creds() +print(f'POLY_API_KEY={creds.api_key}') +print(f'POLY_API_SECRET={creds.api_secret}') +print(f'POLY_API_PASSPHRASE={creds.api_passphrase}') +" + +# Approve Polymarket contracts (one-time setup) +python scripts/approve_usdc.py + +# Run +rarb run --live --realtime +``` + +## Configuration + +Required environment variables: + +```bash +# Wallet +PRIVATE_KEY=0x... # Your wallet private key +WALLET_ADDRESS=0x... # Your wallet address + +# Polymarket L2 API Credentials (generate with script above) +POLY_API_KEY=... +POLY_API_SECRET=... +POLY_API_PASSPHRASE=... + +# Trading Parameters +MIN_PROFIT_THRESHOLD=0.005 # 0.5% minimum profit +MAX_POSITION_SIZE=100 # Max $100 per trade +MIN_LIQUIDITY_USD=10000 # $10k minimum market liquidity +MAX_DAYS_UNTIL_RESOLUTION=7 # Skip markets resolving later +NUM_WS_CONNECTIONS=6 # WebSocket connections (250 markets each) +DRY_RUN=true # Set to false for live trading + +# Dashboard (optional - omit for no auth) +DASHBOARD_USERNAME=admin +DASHBOARD_PASSWORD=... +``` + +See `.env.example` for all available options. + +## Contract Approvals + +Before trading, you must approve Polymarket's smart contracts to spend your USDC.e: + +```bash +# Run the approval script (requires PRIVATE_KEY in environment) +python scripts/approve_usdc.py +``` + +This approves: +- CTF Exchange +- Neg Risk Exchange +- Conditional Tokens +- Neg Risk Adapter + +## Geo-Restrictions + +Polymarket blocks US IP addresses for order placement. The recommended architecture: + +- **Bot server (us-east-1)**: Low-latency WebSocket connection for price monitoring +- **Proxy server (ca-central-1 Montreal)**: SOCKS5 proxy for order placement + +Configure the proxy in your `.env`: +```bash +SOCKS5_PROXY_HOST=your-proxy-ip +SOCKS5_PROXY_PORT=1080 +SOCKS5_PROXY_USER=rarb +SOCKS5_PROXY_PASS=your-password +``` + +See `infra/` for OpenTofu + Ansible deployment scripts. + + + +## Documentation + +See [PRD.md](PRD.md) for full product requirements and technical architecture. + +## License + +MIT + + + From d31cfcd708d23d8768a5892b9273e15ae23b9473 Mon Sep 17 00:00:00 2001 From: Pushpenderrathore Date: Tue, 17 Feb 2026 23:56:28 +0530 Subject: [PATCH 5/6] Modified --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 425b0e9..bbdeee0 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,6 @@ _Read the [Medium article](https://medium.com/@benjamin.bigdev/high-roi-polymark ## Demo Video -Watch the video demonstration: https://github.com/user-attachments/assets/f06d66ee-4408-4076-91c3-5476d780cf7a --- From cdb17cf56cc4ebe8545b9499e4d9a513d1fb43f0 Mon Sep 17 00:00:00 2001 From: enp7s0d <75983347+Pushpenderrathore@users.noreply.github.com> Date: Wed, 18 Feb 2026 00:05:57 +0530 Subject: [PATCH 6/6] Revise contact section in README.md Updated contact information and added Telegram handle. --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2868691..f3eecb7 100644 --- a/README.md +++ b/README.md @@ -23,12 +23,13 @@ _Read the [Medium article](https://medium.com/@benjamin.bigdev/high-roi-polymark 10. [Documentation](#documentation) 11. [License](#license) -Gmail: benjamin.bigdev@gmail.com +--- -- Telegram: [@BenjaminCup](https://t.me/BenjaminCup) +## Contact -X : [@benjaminccup](https://x.com/benjaminccup) +- Telegram: [@BenjaminCup](https://t.me/BenjaminCup) +--- ## Demo Video @@ -187,4 +188,4 @@ This project is licensed under the MIT License. --- -Let me know if you need further refinement or a different format! \ No newline at end of file +Let me know if you need further refinement or a different format!