Skip to content

TroniPM/Bot-polymarket

Repository files navigation

🤖 Polymarket Bot

Leia em Português | Read in English

Browser console automation bot for Polymarket operations with integrated Paper Trading system and Data Collection for market analysis.

📋 About the Project

This bot allows you to execute buy and sell operations on Polymarket through keyboard shortcuts, offering:

  • 🎮 Keyboard Control: Execute trades quickly with shortcuts
  • 📊 Paper Trading: Simulate operations without risking real money
  • 📈 Data Collection: Record market data every 1s for analysis (NEW!)
  • 🛡️ Protections: Anti-spam, market order, and double execution prevention
  • 📈 Real-time Analysis: Track P&L, statistics, and history
  • 🎨 Visual Interface: Control panels integrated in the browser
  • 🔊 Sound Feedback: Trade execution notifications

✅ Tested Markets

The bot has been tested and validated on the following Polymarket market types:

  • Above/Below: Price prediction markets above or below a threshold

🚀 How to Use

Method 1: Build the Project (Recommended)

1️⃣ Install Dependencies

npm install

2️⃣ Compile the Project

npm run build

This will create the dist/bundle.js file with all the compiled code.

3️⃣ Use the Bundle

  1. Open https://polymarket.com and navigate to a market (e.g., above/below)
  2. Press F12 to open the browser console
  3. Go to the Console tab
  4. Copy all the content from dist/bundle.js
  5. Paste it into the console and press Enter
  6. Done! The bot is active 🎉

Method 2: Use Direct Release (TO-DO)

If you prefer, you can copy the code directly from a release. Here's an example based on the latest version:

// Paste this code into the Polymarket console:
// (replace with the actual content of dist/bundle.js after build)

// Example of code structure after build:
// The bundle.js file contains all the minified and optimized code
// To use releases, go to: https://github.com/your-user/polymarket-bot/releases
// And copy the code from the desired version

💡 Tip: To get the latest version, always build or download the latest release from the repository.

⚙️ Configuration

Before executing, you can adjust settings through the control panel that appears in the top right corner, or by editing src/config.js before building:

export const config = {
    QUOTA: 1,                      // 💰 Value in USD per operation
    CAN_TRADE: false,              // 🔴 true = PRODUCTION | false = DEBUG
    AUTO_NEXT_EVENT: true,         // ⏭️ Auto next event
    PAPER_TRADING_ENABLED: true,   // 📊 Enable Paper Trading
    PAPER_INITIAL_BALANCE: 1000,   // 💵 Initial balance (USD)
    COOLDOWN_MS: 300,              // ⏱️ Cooldown between operations (ms)
};

⚠️ IMPORTANT: Always leave CAN_TRADE = false for testing! Only change to true when you're ready to operate with real money.

⌨️ Keyboard Shortcuts

The shortcuts work for both Paper Trading and Real Trading:

Key Action Description
C 📈 BUY UP Buy betting on the upside
B 📉 BUY DOWN Buy betting on the downside
Q 💰 SELL 25% Sell 25% of positions
W 💰 SELL 50% Sell 50% of positions
E 💰 SELL 100% Sell all positions (MAX)

🎯 Features

🤖 Automated Trading

Trade Execution

  • Anti-Spam Protection: 300ms cooldown between operations
  • Auto Next Event: Automatically navigates to next available events
  • Market Order: Ensures execution at market price
  • Double Initialization Protection: Prevents multiple bot instances
  • Automatic Versioning: Each execution traceable with timestamp

Main Control Panel (Top Right)

  • 💵 Real-time adjustment of value per operation
  • 🔴/🟢 Toggle between DEBUG and PRODUCTION mode
  • 📊 Enable/disable Paper Trading
  • ⏭️ Auto next event control
  • 📌 System status and version

📊 Paper Trading (Realistic Simulation)

The Paper Trading system offers a complete simulation without executing real operations:

Main Features

  • 💰 Virtual Balance: Configurable initial balance control
  • 📈 Open Positions: Real-time tracking of all positions (UP/DOWN)
  • 📊 Complete History: Detailed record of all transactions
  • 💹 Real-time P&L: Realized and unrealized profit/loss
  • 📉 Detailed Statistics: Complete performance metrics

Information Tracked per Transaction

Each operation records:

  • ⏰ Date and time of operation
  • 📌 Type (BUY UP/DOWN, SELL)
  • 💵 Entry/exit price
  • 📊 Number of shares (value/price)
  • 💰 Amount invested in USD
  • 📈 Profit/Loss (for sales)
  • 📊 Gain/loss percentage

Session Metrics

The totalizer displays:

  • 🔢 Total Trades: Total number of operations
  • 💰 Total Invested: Sum of all purchases
  • 📈 Realized P&L: Profit/loss from closed positions
  • 📉 Unrealized P&L: Profit/loss from open positions
  • 🎯 Win Rate: Percentage of winning trades
  • Winning Trades: Number of profitable trades
  • Losing Trades: Number of trades with loss

Paper Trading Panel (Top Left)

Displayed when Paper Trading is active:

  • 💵 Real-time available balance
  • 📊 List of open positions with unrealized P&L
  • 📈 Complete session statistics
  • 📜 Transaction history (last 10 or all)
  • 🔘 Action buttons (export/reset)

Advanced Features

  • 📥 JSON Export: Saves all history and statistics
  • 🔄 Session Reset: Clears data and restarts with initial balance
  • 📜 Expandable History: Toggle between last 10 or all transactions
  • 💹 FIFO Calculation: Sales processed by First-In-First-Out
  • 🔄 Automatic Update: P&L updated on every price change

📖 How to Use Paper Trading

1. Activation

Paper Trading is enabled by default. You can:

  • Disable/enable via checkbox in the control panel
  • Or change PAPER_TRADING_ENABLED in src/config.js before building

2. Configure Initial Balance

Define how much you want to simulate in src/config.js:

PAPER_INITIAL_BALANCE: 1000  // USD

3. Operate

Use the same keyboard shortcuts (C, B, Q, W, E):

  • BUY: Deducts value from balance and opens position
  • SELL: Closes positions using FIFO, calculates P&L and returns to balance

4. Track Results

The panel shows in real-time:

  • All open positions with unrealized P&L
  • Transaction history
  • Complete session statistics

5. Export Data

Click 📥 Export to save a JSON with:

{
  "balance": 1050.25,
  "initialBalance": 1000,
  "positions": [...],
  "transactions": [...],
  "stats": {...},
  "exportDate": "2026-03-13T10:30:00.000Z"
}

6. Reset Session

Click 🔄 Reset to:

  • Return to initial balance
  • Clear all positions
  • Zero history and statistics

📊 Data Collection System

NEW FEATURE! The bot now includes an automated data collection system for market analysis.

Features

  • 📈 Automatic Collection: Records market data every 1 second
  • 💾 Export Options: JSON and CSV formats
  • 🎯 Rich Data: 20+ metrics per record including prices, probabilities, volatility
  • 🔄 Continuous: Keeps collecting after export
  • 🎛️ Control: Toggle on/off anytime from control panel

What Data is Collected?

Each record includes:

  • Prices: Target price, current price, UP/DOWN prices
  • Probabilities: Implied market probabilities
  • Trends: Price changes, market bias
  • Volatility: 1-minute rolling volatility
  • Metadata: Timestamps, session ID, sequence number

How to Use

  1. Start Collection (enabled by default)

    • Toggle "📊 Coletar Dados" in the control panel
  2. Monitor Progress

    • See record count update in real-time
  3. Export Data

    • Click 💾 JSON for structured data
    • Click 📊 CSV for spreadsheet analysis
    • Files download automatically with timestamp
  4. Clear Data

    • Click 🗑️ Limpar Dados to reset

Use Cases

  • 🔍 Pattern Discovery: Find profitable entry points
  • 📈 Backtesting: Test strategies on historical data
  • 🎯 Optimization: Identify best timing for trades
  • 📊 Analysis: Correlation between metrics

Documentation

For complete documentation, see __DATA_COLLECTION.md


🔧 Development

Watch Mode (Development)

For development with automatic recompilation:

npm run dev

This monitors changes in src/ and recompiles automatically.

Project Structure

src/
├── config.js              → Global configurations
├── index.js               → Main entry point
├── trading/               → Trading logic
│   ├── buy.js            → Buy (UP/DOWN)
│   ├── sell.js           → Sell (25%/50%/100%)
│   ├── selectors.js      → DOM selectors
│   └── autoNext.js       → Auto next event
├── paperTrading/          → Simulation system
│   ├── core.js           → Simulated buy/sell
│   └── calculations.js   → P&L calculations
├── dataCollector/         → Data collection system
│   ├── collector.js      → Market data collector
│   └── exporter.js       → JSON/CSV export
├── ui/                    → Visual interface
│   ├── controlPanel.js   → Control panel
│   ├── paperPanel.js     → Paper trading panel
│   └── notifications.js  → Notification system
└── utils/                 → Utilities
    ├── helpers.js        → Helper functions
    ├── protection.js     → Anti-spam protections
    └── sounds.js         → Audio system

Releases

To create a new release:

# Patch (1.0.0 → 1.0.1)
npm run release:patch

# Minor (1.0.0 → 1.1.0)
npm run release:minor

# Major (1.0.0 → 2.0.0)
npm run release:major

⚠️ Important Warnings

  1. ⚠️ Always test in DEBUG mode (CAN_TRADE = false) before using in production
  2. 🔄 Don't reload the script without first refreshing the page (F5)
  3. 💰 The bot executes real trades when CAN_TRADE = true
  4. ⚖️ Use at your own risk - financial operations involve risks
  5. 🧪 Paper Trading is for learning - real prices may vary
  6. 📊 Validate your strategies in Paper Trading before operating with real money

🔧 Helper Functions in Console

After initialization, you can manually call:

getCurrentAssetValue()    // Returns current asset value
getCurrentAssetTarget()   // Returns target asset value
buyUp()                   // Executes UP buy
buyDown()                 // Executes DOWN buy
sell25()                  // Sells 25%
sell50()                  // Sells 50%
sellMax()                 // Sells 100%

📝 To-Do

High Priority

  • ✅ Add "paper trading" mode with realistic simulation
  • 🎯 Implement automatic stop-loss/take-profit
  • ⚠️ Implement risk analysis before each operation

Future Improvements

  • ✅ Add history of completed operations
  • ✅ Create visual panel for P&L tracking
  • 📝 Implement persistent error log
  • 🧠 Add support for multiple strategies
  • 📊 Performance charts over time
  • 🔔 Customizable price alerts

Optimizations

  • 🔄 Implement queue system for operations
  • ↩️ Add automatic retry on failure
  • 🔍 Improve DOM element detection
  • 🧪 Add automated tests
  • ⚡ Optimize bundle size

✅ Completed

  • Implement sell shortcuts (Q, W, E)
    • Q: Sells 25% of shares
    • W: Sells 50% of shares
    • E: Sells 100% (Max) of shares
  • Reduce setTimeout usage with promises
  • Add sound notifications for executed trades
  • Create graphical user interface (GUI) in the browser
  • Complete Paper Trading system
  • Control panel with real-time settings
  • JSON data export
  • Detailed performance statistics
  • Modular architecture with Vite

📄 License

This project is provided "as is", without warranties of any kind, express or implied.

Use at your own risk. The author is not responsible for financial losses, damages, or any other problems arising from the use of this software.

This bot is intended for educational and learning purposes only.

🤝 Contributions

Contributions are welcome! Feel free to:

  • 🐛 Report bugs
  • 💡 Suggest new features
  • 🔧 Submit pull requests
  • 📖 Improve documentation
  • ⭐ Star the project

How to Contribute

  1. Fork the project
  2. Create a branch for your feature (git checkout -b feature/MyFeature)
  3. Commit your changes (git commit -m 'Add MyFeature')
  4. Push to the branch (git push origin feature/MyFeature)
  5. Open a Pull Request

Version: 1.0.5
Last updated: March 13, 2026
Author: Bot Polymarket Team

💙 Made with dedication for the trading community

About

🤖 Browser automation bot for Polymarket trading with keyboard shortcuts, integrated Paper Trading system, real-time P&L tracking, and visual control panels. Test strategies risk-free before going live. Educational purposes only.

Topics

Resources

Stars

Watchers

Forks

Contributors