← Back to list

OpenClaw x Polymarket: Hands to teach you how to build an automated trading machine People

itadol5j

Polymarket Trading Machine People

What's Polymarket?

Polymarket is the largest forecast market in the world, where users can trade the probability of events — from sporting competitions to political elections, from encrypted money prices to science and technology news. The way in which the transaction takes place is similar to "dual power": buys a "yes" or "no" token for a given result and is rewarded if the result occurs.

Its core strengths are:

  • Totally decentralised.: Open and transparent based on the Polygon chain
  • Real-time price discovery: Market forecasts tend to be more accurate than traditional polls
  • API Open: Provide complete transactions API to support automated transactions

Preparations

Install Python Dependence

We need it. py-clob-client This official SDK:

pip install py-clob-client requests python-dotenv

2. Access to wallets and API Key

Polymark supports two types of authentication:

  • EOA Wallet(Pay yourself to Gas)
  • Proxy Wallet(Gasless transaction)

Here is the simplest way to demonstrate -- the EOA wallet:

  1. Create a Polygon wallet (recommended with MetaMask)
  2. Deposit USDC.e(for trade) and small POL(for Gas)
  3. For the wallet. Private Key
  4. Using SDK create_or_derive_api_creds() Method to automatically generate API vouchers

3. OpenClaw Environment

OpenClaw exec The tool executes the Python code and is well suited to run this automated script.

Core Code Achieved

Basic: Monitor the Market + Automatic Listing

import os
import time
import requests
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL

HOST = "https://clob.polymarket.com"
CHAIN_ID = 137
PRIVATE_KEY = os.getenv("POLYMARKET_PRIVATE_KEY")
FUNDER_ADDRESS = os.getenv("POLYMARKET_FUNDER")

def init_client():
    temp_client = ClobClient(HOST, key=PRIVATE_KEY, chain_id=CHAIN_ID)
    api_creds = temp_client.create_or_derive_api_creds()
    client = ClobClient(HOST, key=PRIVATE_KEY, chain_id=CHAIN_ID, creds=api_creds, signature_type=0, funder=FUNDER_ADDRESS)
    return client

def get_markets(tag=None, limit=10):
    url = "https://gamma-api.polymarket.com/markets"
    params = {"active": "true", "closed": "false", "limit": limit}
    if tag:
        params["tagName"] = tag
    resp = requests.get(url, params=params)
    return resp.json()

def get_price(token_id):
    url = f"https://gamma-api.polymarket.com/markets/{token_id}/price"
    resp = requests.get(url)
    return resp.json()

def place_order(client, token_id, price, size, side=BUY):
    order = client.create_and_post_order(
        OrderArgs(token_id=token_id, price=price, size=size, side=side, order_type=OrderType.GTC),
        options={"tick_size": "0.01", "neg_risk": False}
    )
    return order

Progress: Average return strategy machine People

The central idea of this strategy is to buy it automatically when prices deviate from the average and wait for return.

import logging
import time

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class MeanReversionBot:
    def __init__(self, client, token_id, threshold=0.1, size=10):
        self.client = client
        self.token_id = token_id
        self.threshold = threshold
        self.size = size
    
    def get_mid_price(self):
        data = get_price(self.token_id)
        return float(data.get("price", 0.5))
    
    def check_and_trade(self):
        mid_price = self.get_mid_price()
        logger.info(f"当前中间价: {mid_price}")
        
        if mid_price < 0.5 - self.threshold:
            logger.info(f"价格偏低,买入!")
            order = place_order(self.client, self.token_id, mid_price, self.size, BUY)
            logger.info(f"订单已下单: {order}")
        elif mid_price > 0.5 + self.threshold:
            logger.info(f"价格偏高,卖出!")
            order = place_order(self.client, self.token_id, mid_price, self.size, SELL)
            logger.info(f"订单已下单: {order}")
        else:
            logger.info("价格在合理区间,不交易")
    
    def run(self, interval=60):
        logger.info(f"机器人启动,监控 token: {self.token_id}")
        while True:
            try:
                self.check_and_trade()
            except Exception as e:
                logger.error(f"错误: {e}")
            time.sleep(interval)

if __name__ == "__main__":
    client = init_client()
    markets = get_markets(tag="politics", limit=1)
    if markets:
        token_id = markets[0]["clobTokenIds"][0]
        print(f"监控市场: {markets[0]['question']}")
        bot = MeanReversionBot(client, token_id, threshold=0.15, size=5)
        bot.run(interval=120)

OpenClaw Integration

It's very simple to run this robot in OpenClaw. You can save the code above as polymarket_bot.py, and then execute in OpenClaw:

运行 python polymarket_bot.py

Attention

Risk tips

  • Projected market volatility, please use only the funds that are affordable
  • It's recommended that we test the network first.
  • Robotic transactions require constant surveillance to prevent extremes.

2. API Restrictions

  • Open API without authentication
  • Deal API needs wallet and API Key
  • Watch out for speed limits.

Gas Optimization

  • EOA mode requires POL payment Gas
  • You can apply for proxy wallets to perform the Gasless transaction