Skill: deliverydriver/polymarket-bot (version 1.0.0)

--- name: polymarket-bot description: Automate Polymarket bot operations including fetching market data, placing trades, and implementing strategies like arbitrage. Use when users need to build or run bots for prediction markets, monitor prices, or execute trades on the Polygon blockchain. --- # Polymarket Bot Skill ## Overview This skill enables the creation and operation of a Polymarket bot for tasks such as fetching active markets, monitoring prices, placing orders, and running strategies. It's designed for users involved in cryptocurrency prediction markets, helping automate interactions via the Polymarket APIs while minimizing risks. ## Quick Start To get started, use the scripts in this skill to initialize and run a basic bot. For example, execute `scripts/fetch_markets.py` to retrieve active markets, then use `scripts/bot_strategy.py` for arbitrage checks. ## Task-Based Structure This skill is organized by tasks from the SOP, providing modular components for bot development. ### Step 1: Research and Setup Prerequisites - Review Polymarket APIs (Gamma, CLOB, Data) as outlined in the SOP. - Ensure tools like Python and Web3.py are installed. - Reference `references/api_guide.md` for detailed API usage. ### Step 2: Define Bot Functionality and Strategy - Implement core features like data fetching and trade execution. - Use prompts in `references/prompts.md` to generate code for strategies. - Example: Run `scripts/strategy_logic.py` for arbitrage detection. ### Step 3: Development Phases - **Data Fetching Module**: Use `scripts/fetch_markets.py` to query markets. - **Authentication and Trading Setup**: Handle in `scripts/auth_setup.py`. - **Testing and Deployment**: Test with `scripts/test_bot.py` and deploy via references. ### Step 4: Potential Challenges and Mitigations - Reference `references/challenges.md` for rate limits, fees, and security tips. ### Step 5: Resources - See below for scripts and references based on the SOP. ## Resources ### scripts/ - `fetch_markets.py`: Script to fetch and parse market data from Polymarket APIs. - `auth_setup.py`: Handles authentication and deriving API keys. - `strategy_logic.py`: Implements bot strategies like arbitrage. - `bot_integration.py`: Combines phases into a full bot script. ### references/ - `api_guide.md`: Documentation on Polymarket APIs and setup. - `strategy_examples.md`: Examples of prompts for code generation. - `challenges.md`: Common issues and mitigations for bot development. ### assets/ - (No assets needed for this skill at the moment.)

path: references/api_guide.md
content: # API Guide for Polymarket Bot Skill

## Overview
This reference covers the Polymarket APIs used in the bot, including Gamma, CLOB, and Data APIs. These are essential for fetching market data, authentication, and trading.

## Gamma API (Public Read-Only)
- Base URL: https://gamma-api.polymarket.com
- Endpoints: Use `/markets?active=true&closed=false&limit=20` to list active markets.
- No authentication required for public data.

## CLOB API (Authenticated Trading)
- Base URL: https://clob.polymarket.com
- Requires EIP-712 signature for API keys.
- Use for placing orders; see scripts/auth_setup.py for implementation.

## Data API (User Analytics)
- Base URL: https://data-api.polymarket.com
- Endpoints: Fetch leaderboards and trades, e.g., /leaderboards for copy trading.

## Best Practices
- Handle private keys securely via environment variables.
- Add error handling for API failures and rate limits.

path: references/challenges.md
content: # Challenges and Mitigations for Polymarket Bot Skill

## Overview
This reference outlines potential challenges in building and running a Polymarket bot, along with mitigations based on the SOP. It's designed to help users anticipate and handle common issues for smoother bot operation.

## Key Challenges and Mitigations
1. **Rate Limits on APIs**: Polymarket APIs may have limits on requests; add delays (e.g., 5-10 seconds between polls) and implement exponential backoff in scripts.
   - Mitigation: Use asyncio for efficient, non-blocking requests, and monitor API usage in `bot_integration.py`.

2. **Trading Fees and Slippage**: Fees (e.g., 2%) and slippage can eat into profits.
   - Mitigation: Factor fees into strategy logic in `strategy_logic.py`, set minimum profit thresholds, and test in dry-run mode.

3. **Blockchain Delays and Gas Fees**: Polygon network can have gas spikes, delaying trades.
   - Mitigation: Use low-gas times (e.g., off-peak hours), monitor gas prices with Web3.py, and include error handling for failed transactions.

4. **API Errors and Invalid Signatures**: Authentication failures or invalid EIP-712 signatures can halt the bot.
   - Mitigation: Add robust error handling in `auth_setup.py`, use secure environment variables for private keys, and log errors for debugging.

5. **Security Risks**: Hardcoding keys or exposing credentials.
   - Mitigation: Store sensitive data in .env files, use libraries like dotenv, and never commit secrets to repositories.

6. **Scaling and Performance**: Monitoring multiple markets can overwhelm resources.
   - Mitigation: Use multiprocessing or asyncio for concurrency, and limit the number of markets in `bot_integration.py`.

## Best Practices
- Test thoroughly in dry-run mode before live trading.
- Monitor bot performance with logging and alerts.
- Regularly review and update the bot based on Polymarket's API changes.

This reference ensures the skill is robust and user-friendly for handling real-world bot development challenges.

path: references/prompts.md
content: # Prompts for Polymarket Bot Skill

## Overview
This reference consolidates the example prompts from the SOP for generating code and strategies using an AI code generator (e.g., Grok or ChatGPT). These prompts help build or extend the bot's functionality in a modular way.

## Consolidated Prompts
1. **Data Fetching Module Prompt**:
   "Write a Python script using requests library to fetch active markets from Polymarket's Gamma API. Include functions to list markets with filters for active=true, closed=false, and limit=20. Parse the JSON response to extract market ID, question, outcomes, and current prices. Add error handling for API failures. Output the data in a pandas DataFrame for easy analysis."

2. **Authentication Setup Prompt**:
   "Create a Python function using web3.py to authenticate with Polymarket's CLOB API. Take a private key as input, sign an EIP-712 message to derive API key, secret, and passphrase. Include code to initialize a trading client. Handle proxy wallet if using Gnosis Safe."

3. **Strategy Logic Prompt**:
   "Build a Python class for a Polymarket arbitrage bot. It should poll a specific market every 10 seconds using the CLOB API for prices. If YES price + NO price < 0.98, buy equal amounts of both, then sell the losing side when conditions are met. Include position limits and logging. Use asyncio for concurrency."

4. **Full Bot Integration Prompt**:
   "Combine the above into a complete Python script for a Polymarket trading bot. Load environment variables for private key. Run an infinite loop to monitor markets, execute strategies, and handle notifications. Add backtesting mode using historical data."

5. **Advanced Features Prompt**:
   "Extend the Polymarket bot to include copy trading. Fetch the leaderboard, select top traders, and mirror their trades with a proportional amount. Include filters and risk management."

## How to Use These Prompts
- Copy and paste a prompt into an AI code generator to produce Python code.
- Test the generated code in the skill's scripts and integrate it iteratively.
- Refer to `strategy_examples.md` for additional context on implementation.

This ensures the skill supports easy code generation and extension based on the SOP.

path: references/strategy_examples.md
content: # Strategy Examples for Polymarket Bot Skill

## Overview
This reference provides examples of prompts for generating code and strategies for the Polymarket bot, based on the SOP. Use these to build or extend bot functionality in Python.

## Prompt Examples
1. **Data Fetching Module Prompt**:
   "Write a Python script using requests library to fetch active markets from Polymarket's Gamma API. Include functions to list markets with filters for active=true, closed=false, and limit=20. Parse the JSON response to extract market ID, question, outcomes, and current prices. Add error handling for API failures. Output the data in a pandas DataFrame for easy analysis."

2. **Authentication Setup Prompt**:
   "Create a Python function using web3.py to authenticate with Polymarket's CLOB API. Take a private key as input, sign an EIP-712 message to derive API key, secret, and passphrase. Include code to initialize a trading client. Handle proxy wallet if using Gnosis Safe."

3. **Strategy Logic Prompt**:
   "Build a Python class for a Polymarket arbitrage bot. It should poll a specific market every 10 seconds using the CLOB API for prices. If YES price + NO price < 0.98, buy equal amounts of both, then sell the losing side when conditions are met. Include position limits and logging. Use asyncio for concurrency."

4. **Full Bot Integration Prompt**:
   "Combine the above into a complete Python script for a Polymarket trading bot. Load environment variables for private key. Run an infinite loop to monitor markets, execute strategies, and handle notifications. Add backtesting mode using historical data."

5. **Advanced Features Prompt**:
   "Extend the Polymarket bot to include copy trading. Fetch the leaderboard, select top traders, and mirror their trades with a proportional amount. Include filters and risk management."

## How to Use These Prompts
- Feed these into an AI code generator (e.g., via Grok or ChatGPT) to produce code snippets.
- Test and integrate the generated code into the skill's scripts.

This helps in iteratively developing the bot's strategies.

path: scripts/advanced_features.py
content: # advanced_features.py
from strategy_logic import PolymarketArbitrageBot  # Import for extension
import requests
import asyncio

class PolymarketCopyTradingBot(PolymarketArbitrageBot):
    async def monitor_leaderboard_and_copy(self, category='crypto'):
        url = "https://data-api.polymarket.com/leaderboards"
        params = {"category": category}  # Filter by category like crypto
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
            leaderboard = response.json()
            top_traders = leaderboard['traders'][:3]  # Top 3 traders
            
            while True:
                for trader in top_traders:
                    trades_url = f"https://data-api.polymarket.com/traders/{trader['id']}/trades"
                    trades_response = requests.get(trades_url)
                    trades = trades_response.json()
                    for trade in trades:
                        # Mirror trade with 10% of your balance
                        if not self.dry_run:
                            amount = trade['amount'] * 0.10  # Proportional amount
                            self.place_order(trade['market_id'], trade['side'], amount)
                        print(f"Copied trade: {trade}")
                await asyncio.sleep(30)  # Monitor every 30 seconds
        except Exception as e:
            print(f"Error in copy trading: {e}")

# Example usage
if __name__ == "__main__":
    api_creds = {}  # Load from auth_setup.py or env
    copy_bot = PolymarketCopyTradingBot(api_creds, dry_run=True)
    asyncio.run(copy_bot.monitor_leaderboard_and_copy(category='crypto'))


path: scripts/auth_setup.py
content: # auth_setup.py
import os
from web3 import Web3
import requests

def authenticate_with_clob(private_key):
    # Set up Web3 provider for Polygon
    w3 = Web3(Web3.HTTPProvider('https://rpc.ankr.com/polygon'))
    account = w3.eth.account.from_key(private_key)
    
    # EIP-712 signature setup (simplified; adapt from docs)
    message = {
        "domain": {},  # Define as per Polymarket docs
        "message": {},
        "primaryType": "SomeType"
    }
    signed_message = w3.eth.account.signTypedData(message, private_key=private_key)
    
    # Derive API key using CLOB endpoint
    url = "https://clob.polymarket.com/api-keys"
    response = requests.post(url, json={"signed_message": signed_message})
    if response.status_code == 200:
        api_data = response.json()
        return api_data  # Returns API key, secret, passphrase
    else:
        raise Exception("Authentication failed")

# Example usage
if __name__ == "__main__":
    private_key = os.getenv('POLY_PRIVATE_KEY')  # Load from env for security
    if private_key:
        try:
            creds = authenticate_with_clob(private_key)
            print("API creds derived:", creds)
        except Exception as e:
            print(f"Error: {e}")
    else:
        print("Set POLY_PRIVATE_KEY environment variable.")


path: scripts/bot_integration.py
content: # bot_integration.py
from dotenv import load_dotenv
import os
from fetch_markets import fetch_active_markets
from auth_setup import authenticate_with_clob
from strategy_logic import PolymarketArbitrageBot
import asyncio

# Load environment variables for security
load_dotenv()
private_key = os.getenv('POLY_PRIVATE_KEY')

if __name__ == "__main__":
    if not private_key:
        print("Error: Set POLY_PRIVATE_KEY in .env file.")
        exit(1)
    
    # Step 1: Authenticate and get API creds
    try:
        api_creds = authenticate_with_clob(private_key)
    except Exception as e:
        print(f"Authentication failed: {e}")
        exit(1)
    
    # Step 2: Fetch markets
    markets = fetch_active_markets(limit=5)  # Fetch 5 markets as example
    if not markets:
        print("No markets fetched.")
        exit(1)
    
    # Step 3: Initialize and run the bot for each market
    bot = PolymarketArbitrageBot(api_creds, dry_run=False)  # Set dry_run=True for testing
    for market in markets:
        market_id = market['id']
        asyncio.run(bot.poll_market(market_id))
    
    # In a real setup, use multiprocessing for multiple markets
    print("Bot integrated and running.")


path: scripts/fetch_markets.py
content: # fetch_markets.py

import requests
import json

def fetch_active_markets(limit=20):
    url = "https://gamma-api.polymarket.com/markets"
    params = {"active": "true", "closed": "false", "limit": str(limit)}
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        markets = response.json()
        return markets  # Returns list of markets with ID, question, outcomes, and prices
    except requests.exceptions.RequestException as e:
        print(f"Error fetching markets: {e}")
        return None

# Example usage
if __name__ == "__main__":
    markets = fetch_active_markets()
    if markets:
        for market in markets:
            print(f"Market ID: {market.get('id')}, Question: {market.get('question')}")


path: scripts/strategy_logic.py
content: # strategy_logic.py
import asyncio
from web3 import Web3
import requests  # Assume API integration

class PolymarketArbitrageBot:
    def __init__(self, api_creds, dry_run=False):
        self.api_creds = api_creds  # From auth_setup.py
        self.w3 = Web3(Web3.HTTPProvider('https://rpc.ankr.com/polygon'))
        self.dry_run = dry_run  # Flag for simulation
        self.position_limit = 100  # USD max position
        self.current_position = 0  # Track total position

    async def poll_market(self, market_id):
        while True:
            try:
                # Fetch prices from CLOB API
                url = f"https://clob.polymarket.com/markets/{market_id}/prices"
                response = requests.get(url, auth=self.api_creds)
                prices = response.json()
                yes_price = prices.get('YES', 0)
                no_price = prices.get('NO', 0)
                
                if yes_price + no_price < 0.98 and self.current_position < self.position_limit:
                    amount = 10  # Example $10 per side
                    if self.current_position + amount * 2 <= self.position_limit:
                        if not self.dry_run:
                            # Place buys (simplified)
                            self.place_order(market_id, 'YES', amount)
                            self.place_order(market_id, 'NO', amount)
                            self.current_position += amount * 2
                        print(f"Arbitrage opportunity detected and acted on: Bought YES and NO for {amount} each")
                
                # Monitor and sell if condition met
                if yes_price > 0.6:
                    self.sell_order(market_id, 'NO', amount)
                elif no_price > 0.6:
                    self.sell_order(market_id, 'YES', amount)
            except Exception as e:
                print(f"Error in polling: {e}")
            await asyncio.sleep(10)  # Poll every 10 seconds
    
    def place_order(self, market_id, side, amount):
        # Simplified order placement; integrate with API
        print(f"Placing {amount} on {side} for market {market_id}")
        # Actual implementation would use authenticated API calls
    
    def sell_order(self, market_id, side, amount):
        print(f"Selling {amount} on {side} for market {market_id}")
        # Logic to execute sell

# Example usage
if __name__ == "__main__":
    # Load API creds from env or file
    api_creds = {}  # Placeholder
    bot = PolymarketArbitrageBot(api_creds, dry_run=True)
    asyncio.run(bot.poll_market('example_market_id'))  # Replace with actual ID


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)