### Install Project Dependencies with UV Source: https://github.com/warproxxx/poly-maker/blob/main/README.md Commands to install project dependencies using the UV package manager. 'uv sync' installs all dependencies, while 'uv sync --extra dev' includes development dependencies like black and pytest. ```bash # Install all dependencies uv sync # Install with development dependencies (black, pytest) uv sync --extra dev ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/warproxxx/poly-maker/blob/main/README.md Command to copy the example environment file to a new file named '.env'. This file will store sensitive credentials and configuration settings for the Poly-Maker bot. ```bash cp .env.example .env ``` -------------------------------- ### Install Node.js Dependencies for Poly Merger Source: https://github.com/warproxxx/poly-maker/blob/main/README.md Instructions to install Node.js dependencies specifically for the 'poly_merger' module. This requires navigating into the 'poly_merger' directory and running 'npm install'. ```bash cd poly_merger npm install cd .. ``` -------------------------------- ### Install UV Package Manager Source: https://github.com/warproxxx/poly-maker/blob/main/README.md Instructions for installing the UV package manager using curl for macOS/Linux, PowerShell for Windows, or pip. UV is used for fast and reliable package management in this project. ```bash # macOS/Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # Or with pip pip install uv ``` -------------------------------- ### Run Poly-Maker Scripts with UV Source: https://github.com/warproxxx/poly-maker/blob/main/README.md Quick start commands to run the main market maker bot, update market data, and update statistics using the UV package manager. These commands initiate the core functionalities of the Poly-Maker bot. ```bash # Run the market maker (recommended) uv run python main.py # Update market data uv run python update_markets.py # Update statistics uv run python update_stats.py ``` -------------------------------- ### Initialize and Start Polymarket Market Making Bot Source: https://context7.com/warproxxx/poly-maker/llms.txt Initializes the Polymarket client, fetches initial market and position data, and establishes WebSocket connections for real-time updates. It loads configurations from Google Sheets and environment variables for credentials. ```python import asyncio from poly_data.polymarket_client import PolymarketClient from poly_data.data_utils import update_markets, update_positions, update_orders from poly_data.websocket_handlers import connect_market_websocket, connect_user_websocket import poly_data.global_state as global_state from dotenv import load_dotenv # Load environment variables (PK, BROWSER_ADDRESS, SPREADSHEET_URL) load_dotenv() async def main(): # Initialize Polymarket client with credentials from .env global_state.client = PolymarketClient() # Fetch initial data: market configs from Google Sheets, positions from API, open orders global_state.all_tokens = [] update_markets() # Loads market parameters from Google Sheets update_positions() # Gets current positions from Polymarket API update_orders() # Gets open orders from Polymarket API print(f'Starting with {len(global_state.df)} markets, {len(global_state.positions)} positions, {len(global_state.orders)} orders') # Connect to WebSockets for real-time market data and user order updates # If connection drops, automatically reconnects while True: try: await asyncio.gather( connect_market_websocket(global_state.all_tokens), # Subscribe to order book updates connect_user_websocket() # Subscribe to user trade fills ) except Exception as e: print(f"Connection lost, reconnecting: {e}") await asyncio.sleep(1) # Run the bot asyncio.run(main()) ``` -------------------------------- ### Google Sheets Configuration Structure in Python Source: https://context7.com/warproxxx/poly-maker/llms.txt Illustrates the structure of Google Sheets used for configuring trading parameters. It details the columns and example data for two main worksheets: 'Selected Markets' for active trading parameters and 'Hyperparameters' for risk management settings. ```python # Google Sheets structure (3 main worksheets): # 1. "Selected Markets" - Markets to actively trade # Columns: question, answer1, answer2, token1, token2, condition_id, trade_size, # max_size, min_size, max_spread, tick_size, neg_risk, param_type, multiplier # Example row: # question: "Will Bitcoin hit $100k by end of 2024?" # answer1: "Yes" # answer2: "No" # token1: "71321045679252212594626385532706912750332728571942532289631379312455583992833" # token2: "12345678901234567890123456789012345678901234567890123456789012345678901234" # condition_id: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" # trade_size: 100 # Normal order size in USDC # max_size: 250 # Maximum position size in USDC # min_size: 20 # Minimum order size in USDC # max_spread: 5.0 # Maximum acceptable spread (percentage points) # tick_size: 0.01 # Price increment (0.01 = 1 cent) # neg_risk: TRUE # Whether this is a negative-risk market # param_type: default # Which hyperparameters to use (from "Hyperparameters" sheet) # multiplier: 2 # Size multiplier for low-price assets (<0.10) # 2. "Hyperparameters" - Risk management settings by parameter type # Columns: param_type, stop_loss_threshold, take_profit_threshold, volatility_threshold, # spread_threshold, sleep_period # Example rows: # param_type: default ``` -------------------------------- ### Query Positions and Balances with PolymarketClient Source: https://context7.com/warproxxx/poly-maker/llms.txt Retrieves current positions, USDC balance, and total account value across all markets using the PolymarketClient. It demonstrates how to get wallet balance, the value of open positions, and the total account value. It also shows how to fetch all positions as a DataFrame and specific positions by token ID. The `update_positions` function can be used to refresh position data. ```python from poly_data.polymarket_client import PolymarketClient from poly_data.data_utils import get_position, update_positions client = PolymarketClient() # Get USDC balance in wallet usdc_balance = client.get_usdc_balance() print(f"USDC Balance: ${usdc_balance:.2f}") # Get total value of all positions across all markets positions_value = client.get_pos_balance() print(f"Positions Value: ${positions_value:.2f}") # Get total account value total_value = client.get_total_balance() print(f"Total Account Value: ${total_value:.2f}") # Get all positions as DataFrame all_positions = client.get_all_positions() print(f"\nAll Positions ({len(all_positions)} markets):") for idx, pos in all_positions.iterrows(): print(f" Market: {pos['market']}, Token: {pos['asset']}") print(f" Size: {pos['size']:.2f}, Avg Price: ${pos['avgPrice']:.3f}") print(f" P&L: ${(pos['size'] * pos['avgPrice']):.2f}\n") # Get position for a specific token token_id = "71321045679252212594626385532706912750332728571942532289631379312455583992833" position_data = get_position(token_id) print(f"Token {token_id}:") print(f" Size: {position_data['size']:.2f} shares") print(f" Average Price: ${position_data['avgPrice']:.3f}") # Update positions from API (typically called in background loop every 5 seconds) update_positions(avgOnly=True) # Only updates average price, not size (faster) # or update_positions(avgOnly=False) # Full update of size and average price ``` -------------------------------- ### Get Order Book Data and Calculate Optimal Prices Source: https://context7.com/warproxxx/poly-maker/llms.txt This Python code retrieves order book depth for a given market and token, identifies best bid/ask prices with minimum size requirements, and calculates liquidity. It uses `poly_data.trading_utils` and `poly_data.global_state`. The output includes various metrics like best bid/ask, liquidity within a deviation threshold, and optimal order prices. ```python from poly_data.trading_utils import get_best_bid_ask_deets, get_order_prices import poly_data.global_state as global_state # Market and token to analyze market = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" token_name = "token1" # 'token1' for YES, 'token2' for NO min_order_size = 100 # Minimum size in USDC to consider deviation_threshold = 0.1 # 10% from mid price for liquidity analysis # Get comprehensive order book details # Returns prices and sizes at different depth levels, plus liquidity metrics deets = get_best_bid_ask_deets(market, token_name, min_order_size, deviation_threshold) print(f"Best bid: ${deets['best_bid']:.3f} with size {deets['best_bid_size']:.1f}") print(f"Best ask: ${deets['best_ask']:.3f} with size {deets['best_ask_size']:.1f}") print(f"Top bid (any size): ${deets['top_bid']:.3f}") print(f"Top ask (any size): ${deets['top_ask']:.3f}") print(f"Second best bid: ${deets['second_best_bid']:.3f}") print(f"Bid liquidity within {deviation_threshold*100}%: {deets['bid_sum_within_n_percent']:.1f}") print(f"Ask liquidity within {deviation_threshold*100}%: {deets['ask_sum_within_n_percent']:.1f}") # Calculate optimal order prices based on market conditions ``` -------------------------------- ### Configure Environment Variables in Bash Source: https://context7.com/warproxxx/poly-maker/llms.txt Sets up authentication credentials (private key, browser address) and Google Sheets integration by creating a `.env` file in the project root. It also includes instructions for setting file permissions and placing Google Service Account credentials. ```bash # Create .env file in project root cat > .env << 'EOF' # Polymarket Authentication # Your Ethereum private key (must have completed at least one UI trade for proper permissions) PK=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef # Your Gnosis Safe wallet address on Polygon BROWSER_ADDRESS=0x1234567890123456789012345678901234567890 # Google Sheets URL for market configuration # Copy template from: https://docs.google.com/spreadsheets/d/1Kt6yGY7CZpB75cLJJAdWo7LSp9Oz7pjqfuVWwgtn7Ns SPREADSHEET_URL=https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit?gid=97507557#gid=97507557 EOF # Set proper permissions chmod 600 .env # Place Google Service Account credentials in project root # Download from Google Cloud Console -> IAM & Admin -> Service Accounts # File should be named something like: service-account-credentials.json ``` -------------------------------- ### Clone Poly-Maker Repository Source: https://github.com/warproxxx/poly-maker/blob/main/README.md Standard Git command to clone the Poly-Maker repository from GitHub and navigate into the project directory. This is the first step in setting up the project locally. ```bash git clone https://github.com/yourusername/poly-maker.git cd poly-maker ``` -------------------------------- ### Environment Variables Configuration Source: https://context7.com/warproxxx/poly-maker/llms.txt Sets up authentication credentials and Google Sheets integration for the trading bot using environment variables. ```APIDOC ## Environment Variables Configuration ### Description Set up authentication credentials and Google Sheets integration for the trading bot by creating and configuring a `.env` file. ### Method File Configuration & Permissions ### Endpoint Project root directory ### Parameters #### Environment Variables in `.env` file - **PK** (string) - Required - Your Ethereum private key (must have completed at least one UI trade for proper permissions). - **BROWSER_ADDRESS** (string) - Required - Your Gnosis Safe wallet address on Polygon. - **SPREADSHEET_URL** (string) - Required - The URL of your Google Sheets document for market configuration. ### Request Example (Creating `.env` file) ```bash cat > .env << 'EOF' # Polymarket Authentication PK=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef # Gnosis Safe Wallet Address BROWSER_ADDRESS=0x1234567890123456789012345678901234567890 # Google Sheets URL SPREADSHEET_URL=https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit?gid=97507557#gid=97507557 EOF # Set proper permissions chmod 600 .env # Place Google Service Account credentials in project root # Download from Google Cloud Console -> IAM & Admin -> Service Accounts # File should be named something like: service-account-credentials.json ``` ``` -------------------------------- ### Connect to User Orders WebSocket in Python Source: https://context7.com/warproxxx/poly-maker/llms.txt Establishes an authenticated WebSocket connection to receive real-time updates on order fills, cancellations, and position changes. It requires initialized Polymarket client with API credentials and processes incoming data using `process_user_data`. ```python import asyncio import json import websockets from poly_data.data_processing import process_user_data import poly_data.global_state as global_state async def connect_user_websocket(): """ Subscribe to real-time user order and trade updates with authentication. Requires initialized Polymarket client with API credentials. """ uri = "wss://ws-subscriptions-clob.polymarket.com/ws/user" async with websockets.connect(uri, ping_interval=5, ping_timeout=None) as websocket: # Authenticate with API credentials auth_message = { "type": "user", "auth": { "apiKey": global_state.client.client.creds.api_key, "secret": global_state.client.client.creds.api_secret, "passphrase": global_state.client.client.creds.api_passphrase } } await websocket.send(json.dumps(auth_message)) print("Authenticated to user WebSocket") try: while True: # Receive order/trade update message = await websocket.recv() data = json.loads(message) # Example fill message: # { # "type": "TRADE", # "asset_id": "71321045679...", # "side": "BUY", # "size": "100.0", # "price": "0.550", # "status": "MATCHED", # "timestamp": 1234567890 # } # Process update: adjust positions, update orders, log fills # process_user_data updates global_state.positions and global_state.orders process_user_data(data) except websockets.ConnectionClosed: print("User WebSocket connection closed, will reconnect") except Exception as e: print(f"Error in user WebSocket: {e}") finally: await asyncio.sleep(5) # Brief delay before reconnect # Run alongside market WebSocket async def run_both_websockets(): await asyncio.gather( connect_market_websocket(global_state.all_tokens), # Assuming connect_market_websocket is defined elsewhere connect_user_websocket() ) asyncio.run(run_both_websockets()) ``` -------------------------------- ### Place Buy Order for YES Token in Prediction Market Source: https://context7.com/warproxxx/poly-maker/llms.txt This Python snippet demonstrates how to place a buy order for a YES token in a prediction market. It prepares order details, including token ID, action, price, and size, and intelligently decides whether to create a new order or keep an existing one based on price changes. It utilizes a client object likely from a library like 'poly_data'. ```python token_id = "71321045679252212594626385532706912750332728571942532289631379312455583992833" action = "BUY" price = 0.55 # 55 cents probability size = 100 # 100 USDC worth of shares neg_risk = False # Set True for negative-risk markets # Prepare order details order = { "token": token_id, "price": price, "size": size, "mid_price": 0.50, "max_spread": 5.0, # Max spread in percentage points "neg_risk": "TRUE" if neg_risk else "FALSE", "orders": {"buy": {"price": 0.54, "size": 90}, "sell": {"price": 0, "size": 0}}, "token_name": "token1", "row": {"tick_size": 0.01} } # Smart order placement: only cancels and replaces if price moved >0.5 cents or size changed >10% existing_buy_price = order['orders']['buy']['price'] price_diff = abs(existing_buy_price - order['price']) if price_diff > 0.005: # Price changed significantly client.cancel_all_asset(order['token']) # Cancel existing orders # Create new order response = client.create_order( token_id, action, price, size, neg_risk ) print(f"Order created: {response}") else: print("Keeping existing order - price change too small") # Example response: {'success': True, 'orderId': 'abc123...'} ``` -------------------------------- ### Google Sheets Configuration Structure Source: https://context7.com/warproxxx/poly-maker/llms.txt Configure trading parameters, market selection, and hyperparameters through Google Sheets for real-time adjustments. ```APIDOC ## Google Sheets Configuration Structure ### Description Configure trading parameters, market selection, and hyperparameters through Google Sheets for real-time adjustments. The bot reads data from specific worksheets to dynamically adjust its behavior. ### Method Data Configuration via Google Sheets ### Worksheets 1. **Selected Markets** * **Purpose**: Defines the markets the bot will actively trade. * **Columns**: `question`, `answer1`, `answer2`, `token1`, `token2`, `condition_id`, `trade_size`, `max_size`, `min_size`, `max_spread`, `tick_size`, `neg_risk`, `param_type`, `multiplier` * **Example Row**: ``` question: "Will Bitcoin hit $100k by end of 2024?" answer1: "Yes" answer2: "No" token1: "71321045679252212594626385532706912750332728571942532289631379312455583992833" token2: "12345678901234567890123456789012345678901234567890123456789012345678901234" condition_id: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" trade_size: 100 max_size: 250 min_size: 20 max_spread: 5.0 tick_size: 0.01 neg_risk: TRUE param_type: default multiplier: 2 ``` 2. **Hyperparameters** * **Purpose**: Defines risk management settings and trading strategy parameters, categorized by `param_type`. * **Columns**: `param_type`, `stop_loss_threshold`, `take_profit_threshold`, `volatility_threshold`, `spread_threshold`, `sleep_period` * **Example Rows**: ``` param_type: default stop_loss_threshold: 0.1 take_profit_threshold: 0.2 volatility_threshold: 0.05 spread_threshold: 2.0 sleep_period: 60 ``` ### Data Types and Descriptions - **question** (string) - The question posed by the market. - **answer1** (string) - The first possible answer/outcome. - **answer2** (string) - The second possible answer/outcome. - **token1** (string) - The unique identifier for the first answer's token. - **token2** (string) - The unique identifier for the second answer's token. - **condition_id** (string) - The unique identifier for the market's condition. - **trade_size** (number) - The base order size in USDC for trades. - **max_size** (number) - The maximum allowable position size in USDC. - **min_size** (number) - The minimum order size in USDC for trades. - **max_spread** (number) - The maximum acceptable bid-ask spread, in percentage points. - **tick_size** (number) - The minimum price increment (e.g., 0.01 for 1 cent). - **neg_risk** (boolean) - Indicates if the market is a negative-risk market (TRUE/FALSE). - **param_type** (string) - Identifier to link to the 'Hyperparameters' sheet. - **multiplier** (number) - A multiplier for trade size, especially for low-priced assets. - **stop_loss_threshold** (number) - The percentage at which to trigger a stop-loss order. - **take_profit_threshold** (number) - The percentage at which to trigger a take-profit order. - **volatility_threshold** (number) - The threshold for market volatility to adjust trading behavior. - **spread_threshold** (number) - The threshold for the bid-ask spread to adjust trading behavior. - **sleep_period** (number) - The duration (in seconds) the bot should sleep between certain operations. ``` -------------------------------- ### Discover and Rank Polymarket Markets by Profitability (Python) Source: https://context7.com/warproxxx/poly-maker/llms.txt Scans all Polymarket markets to calculate potential maker rewards, ranks markets by a profitability/volatility ratio, and updates a Google Sheet with the findings. It uses libraries like pandas, gspread-dataframe, and custom utilities for data fetching and processing. The script filters markets based on volatility, reward potential, and bid prices. ```python from data_updater.trading_utils import get_clob_client from data_updater.google_utils import get_spreadsheet from data_updater.find_markets import get_all_markets, get_all_results, get_markets, add_volatility_to_df from gspread_dataframe import set_with_dataframe import pandas as pd # Initialize connections spreadsheet = get_spreadsheet() # Connects using credentials file client = get_clob_client() # Creates Polymarket API client # Get all active markets from Polymarket all_df = get_all_markets(client) print(f"Found {len(all_df)} total markets") # Fetch detailed data for each market (order book, liquidity, etc.) all_results = get_all_results(all_df, client) print(f"Retrieved data for {len(all_results)} markets") # Calculate potential maker rewards based on order book depth # maker_reward parameter: percentage of spread captured (e.g., 0.75 = 75%) selected_df = get_sel_df(spreadsheet, "Selected Markets") # Currently selected markets market_data, all_markets = get_markets(all_results, selected_df, maker_reward=0.75) # Add volatility metrics (1h, 3h, 6h, 12h, 24h, 7d, 14d, 30d) enhanced_df = add_volatility_to_df(all_markets) # Calculate composite profitability score enhanced_df['volatility_sum'] = enhanced_df['24_hour'] + enhanced_df['7_day'] + enhanced_df['14_day'] enhanced_df['volatility/reward'] = (enhanced_df['gm_reward_per_100'] / enhanced_df['volatility_sum']).round(2) # Filter for low-volatility, high-reward markets best_markets = enhanced_df[ (enhanced_df['volatility_sum'] < 20) & # Low volatility (enhanced_df['gm_reward_per_100'] > 0.5) & # Good maker rewards (enhanced_df['best_bid'] >= 0.1) & # Reasonable prices (enhanced_df['best_bid'] <= 0.9) ].sort_values('gm_reward_per_100', ascending=False).head(50) print(f"\nTop 5 Markets by Maker Rewards:") for idx, market in best_markets.head().iterrows(): print(f"{market['question']}") print(f" Maker Reward: ${market['gm_reward_per_100']:.2f} per $100") print(f" Spread: {market['spread']:.3f}") print(f" Volatility: {market['volatility_sum']:.2f}") print(f" Best Bid: ${market['best_bid']:.3f}, Best Ask: ${market['best_ask']:.3f}\n") # Update Google Sheets with discovered markets wk_volatility = spreadsheet.worksheet("Volatility Markets") set_with_dataframe(wk_volatility, best_markets, include_index=False, include_column_header=True) print("Updated Google Sheets with market data") ``` -------------------------------- ### Connect to User Orders WebSocket Source: https://context7.com/warproxxx/poly-maker/llms.txt Establishes an authenticated WebSocket connection to receive real-time updates on order fills, cancellations, and position changes. This connection requires initialized Polymarket client with API credentials. ```APIDOC ## Connect to User Orders WebSocket ### Description Establishes an authenticated WebSocket connection to receive real-time updates about order fills, cancellations, and position changes. Requires initialized Polymarket client with API credentials. ### Method WebSocket Connection ### Endpoint `wss://ws-subscriptions-clob.polymarket.com/ws/user` ### Parameters #### Request Body (Authentication Message) ```json { "type": "user", "auth": { "apiKey": "", "secret": "", "passphrase": "" } } ``` ### Request Example (Python - sending auth message) ```python import asyncio import json import websockets # Assuming global_state.client is initialized with credentials async def send_auth_message(websocket): auth_message = { "type": "user", "auth": { "apiKey": global_state.client.client.creds.api_key, "secret": global_state.client.client.creds.api_secret, "passphrase": global_state.client.client.creds.api_passphrase } } await websocket.send(json.dumps(auth_message)) print("Authenticated to user WebSocket") ``` ### Response #### Incoming Messages (Examples) - **Trade Update**: ```json { "type": "TRADE", "asset_id": "71321045679...", "side": "BUY", "size": "100.0", "price": "0.550", "status": "MATCHED", "timestamp": 1234567890 } ``` ### Error Handling - `websockets.ConnectionClosed`: Indicates the WebSocket connection was closed, triggering a reconnection attempt. - `Exception`: Catches other potential errors during WebSocket communication. ``` -------------------------------- ### Merge Positions to Recover Collateral using PolymarketClient Source: https://context7.com/warproxxx/poly-maker/llms.txt This Python function merges opposing YES and NO positions in the same market to recover USDC collateral. It retrieves current positions, calculates the mergeable amount, and executes the merge if it exceeds a minimum threshold. Dependencies include `poly_data.polymarket_client`, `poly_data.CONSTANTS`, and `poly_data.data_utils`. ```python from poly_data.polymarket_client import PolymarketClient import poly_data.CONSTANTS as CONSTANTS client = PolymarketClient() # Example market with opposing positions token1 = "71321045679252212594626385532706912750332728571942532289631379312455583992833" # YES token token2 = "12345678901234567890123456789012345678901234567890123456789012345678901234" # NO token condition_id = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" is_neg_risk_market = True # Get current positions (returns raw amount and decimal shares) pos_1_raw, pos_1 = client.get_position(token1) # e.g., (150000000, 150.0) pos_2_raw, pos_2 = client.get_position(token2) # e.g., (120000000, 120.0) # Calculate mergeable amount (minimum of the two positions) amount_to_merge_raw = min(pos_1_raw, pos_2_raw) amount_to_merge = amount_to_merge_raw / 10**6 print(f"Position 1: {pos_1} shares, Position 2: {pos_2} shares") print(f"Mergeable amount: {amount_to_merge} USDC") # Only merge if above minimum threshold (avoids gas costs for tiny amounts) if amount_to_merge > CONSTANTS.MIN_MERGE_SIZE: # MIN_MERGE_SIZE typically 10-20 USDC # Calls Node.js script that interacts with Polygon smart contracts # Returns USDC to wallet equal to merged amount tx_hash = client.merge_positions( amount_to_merge_raw, # Raw token amount (e.g., 120000000) condition_id, is_neg_risk_market ) print(f"Merge successful, transaction: {tx_hash}") # Example output: "merge positions 0xabc123def456..." # Update local position tracking after merge from poly_data.data_utils import set_position set_position(token1, 'SELL', amount_to_merge, 0, 'merge') set_position(token2, 'SELL', amount_to_merge, 0, 'merge') else: print(f"Amount {amount_to_merge} below minimum, skipping merge") ``` -------------------------------- ### Connect to Polymarket Market Data WebSocket (Python) Source: https://context7.com/warproxxx/poly-maker/llms.txt Establishes a WebSocket connection to Polymarket's order book feed to receive real-time price and liquidity updates for specified markets. It uses the `websockets` library for asynchronous communication and `asyncio` for managing the connection. Incoming data is processed by a `process_data` function, which is expected to handle order book updates and potentially trigger trading logic. ```python import asyncio import json import websockets from poly_data.data_processing import process_data async def connect_market_websocket(token_ids): """ Subscribe to real-time order book updates for specified tokens. Args: token_ids: List of token IDs to monitor (e.g., ["71321045679...", "12345678..."]) """ uri = "wss://ws-subscriptions-clob.polymarket.com/ws/market" async with websockets.connect(uri, ping_interval=5, ping_timeout=None) as websocket: # Subscribe to order book updates for specified tokens subscription_message = {"assets_ids": token_ids} await websocket.send(json.dumps(subscription_message)) print(f"Subscribed to {len(token_ids)} tokens") try: while True: # Receive order book update message = await websocket.recv() data = json.loads(message) # Example message format: # { # "asset_id": "71321045679252212594626385532706912750332728571942532289631379312455583992833", # "hash": "0xabc123...", # "price": "0.550", # "side": "BUY", # "size": "100.5", # "timestamp": 1234567890 # } # Process update and trigger trading if conditions are met # process_data updates global order book and calls perform_trade process_data(data) except websockets.ConnectionClosed: print("Market WebSocket connection closed, will reconnect") except Exception as e: print(f"Error in market WebSocket: {e}") finally: await asyncio.sleep(5) # Brief delay before reconnect # Example: Monitor specific markets token_list = [ "71321045679252212594626385532706912750332728571942532289631379312455583992833", "12345678901234567890123456789012345678901234567890123456789012345678901234" ] asyncio.run(connect_market_websocket(token_list)) ``` -------------------------------- ### Node.js Utility to Merge Positions via Polygon Smart Contracts Source: https://context7.com/warproxxx/poly-maker/llms.txt A JavaScript utility that interacts with Polygon smart contracts to merge opposing positions (e.g., YES and NO tokens for a market). This process aims to recover USDC collateral. It requires environment variables for private keys and uses ethers.js for contract interactions. It can handle both standard and negative-risk markets. ```javascript // poly_merger/merge.js - Called from Python via subprocess const { ethers } = require('ethers'); require('dotenv').config(); // Initialize wallet and provider const provider = new ethers.providers.JsonRpcProvider("https://polygon-rpc.com"); const privateKey = process.env.PK; const wallet = new ethers.Wallet(privateKey, provider); // Polymarket contract addresses on Polygon const addresses = { neg_risk_adapter: '0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296', // For neg-risk markets collateral: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174', // USDC conditional_tokens: '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045' // CTF contract }; // Contract ABIs (minimal interface) const negRiskAdapterAbi = [ "function mergePositions(bytes32 conditionId, uint256 amount)" ]; const conditionalTokensAbi = [ "function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)" ]; /** * Merge YES and NO positions to recover USDC * @param {string} amountToMerge - Raw token amount (e.g., "120000000" = 120 USDC) * @param {string} conditionId - Market condition ID (bytes32 hex string) * @param {boolean} isNegRiskMarket - Whether this is a negative-risk market */ async function mergePositions(amountToMerge, conditionId, isNegRiskMarket) { const nonce = await provider.getTransactionCount(wallet.address); const gasPrice = await provider.getGasPrice(); let tx; if (isNegRiskMarket) { // Use negative risk adapter const negRiskAdapter = new ethers.Contract( addresses.neg_risk_adapter, negRiskAdapterAbi, wallet ); tx = await negRiskAdapter.populateTransaction.mergePositions( conditionId, amountToMerge ); } else { // Use conditional tokens directly const conditionalTokens = new ethers.Contract( addresses.conditional_tokens, conditionalTokensAbi, wallet ); tx = await conditionalTokens.populateTransaction.mergePositions( addresses.collateral, // USDC ethers.constants.HashZero, // Parent collection (none) conditionId, // Market ID [1, 2], // Partition (YES=1, NO=2) amountToMerge // Amount to merge ); } // Execute via Gnosis Safe const transaction = { ...tx, chainId: 137, // Polygon gasPrice: gasPrice, gasLimit: 10000000, nonce: nonce }; const safeAddress = process.env.BROWSER_ADDRESS; const safe = new ethers.Contract(safeAddress, safeAbi, wallet); const txResponse = await signAndExecuteSafeTransaction( wallet, safe, transaction.to, transaction.data, { gasPrice: transaction.gasPrice, gasLimit: transaction.gasLimit } ); const txReceipt = await txResponse.wait(); console.log("merge positions " + txReceipt.transactionHash); return txReceipt.transactionHash; } // Parse command line arguments and execute // Usage: node merge.js [amount] [conditionId] [isNegRisk] // Example: node merge.js 120000000 0x1234...abcd true const args = process.argv.slice(2); mergePositions(args[0], args[1], args[2] === 'true') .catch(error => { console.error("Error merging positions:", error); process.exit(1); }); ``` -------------------------------- ### Calculate Optimal Order Prices Using Market Data Source: https://context7.com/warproxxx/poly-maker/llms.txt Calculates the optimal bid and ask prices for placing orders based on market data, average position price, and market row configuration. It considers improving the best bid/ask by one tick if sufficient size is available, otherwise matching the best price. Dependencies include 'deets' object and 'market_row' configuration. ```python market_row = { 'tick_size': 0.01, # Price increment (1 cent) 'min_size': 20, # Minimum order size 'max_spread': 5.0, # Maximum spread in percentage points } avg_position_price = 0.48 # Your average entry price (0 if no position) # Calculate where to place buy and sell orders # Logic: improve best bid/ask by one tick if there's sufficient size, otherwise match best price bid_price, ask_price = get_order_prices( deets['best_bid'], deets['best_bid_size'], deets['top_bid'], deets['best_ask'], deets['best_ask_size'], deets['top_ask'], avg_position_price, market_row ) print(f"\nOptimal bid price: ${bid_price:.3f}") print(f"Optimal ask price: ${ask_price:.3f}") print(f"Spread: {(ask_price - bid_price) * 100:.1f} cents") ``` -------------------------------- ### Create and Manage Orders on Polymarket Source: https://context7.com/warproxxx/poly-maker/llms.txt Handles the creation of buy or sell orders on Polymarket. This function is part of the broader trading strategy and aims to optimize order placement while minimizing API calls and gas expenses through intelligent cancellation logic. ```python from poly_data.polymarket_client import PolymarketClient import os # Initialize client client = PolymarketClient() ``` -------------------------------- ### Execute Market Making Strategy Source: https://context7.com/warproxxx/poly-maker/llms.txt Performs the core market making logic, including position merging, order book analysis, risk management (stop-loss, volatility filters), and order placement. It uses configurable parameters from Google Sheets for trading decisions. ```python import asyncio from trading import perform_trade import poly_data.global_state as global_state # Example: Trade on a specific market after initialization async def trade_example(): # Market condition_id from Google Sheets (identifies a specific prediction market) market = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" # perform_trade handles the complete trading logic: # 1. Merges opposing positions if both YES and NO holdings exist (recovers USDC) # 2. Gets best bid/ask from order book with minimum size requirements # 3. Calculates optimal bid/ask prices based on market depth and tick size # 4. Checks position limits (trade_size and max_size from Google Sheets) # 5. Implements stop-loss: exits if PnL < threshold and spread is tight # 6. Implements volatility filter: skips trading if 3_hour volatility is too high # 7. Places buy orders up to max_size, sell orders for take-profit # 8. Avoids trading during risk-off periods (after stop-loss triggers) await perform_trade(market) # Output: Places orders, prints detailed logs of decisions, handles errors gracefully # In production, perform_trade is called automatically when WebSocket receives order book updates # The data_processing module triggers trades based on price changes and order book depth asyncio.run(trade_example()) ``` -------------------------------- ### Update Market Data from Google Sheets Source: https://context7.com/warproxxx/poly-maker/llms.txt Fetches market configurations, trading parameters, and volatility data from Google Sheets using the `update_markets` function. This data is loaded into `global_state.df` and `global_state.params` for configuring trading behavior. The function reads from specified worksheets and provides access to detailed market information and hyperparameters for different market types. ```python from poly_data.data_utils import update_markets import poly_data.global_state as global_state # Fetch market data from Google Sheets # Reads from worksheet "Selected Markets" and "Hyperparameters" update_markets() # Access loaded market data print(f"Loaded {len(global_state.df)} markets") # Example market configuration from global_state.df for idx, market in global_state.df.iterrows(): print(f"Question: {market['question']}") print(f" Token 1 ({market['answer1']}): {market['token1']}") print(f" Token 2 ({market['answer2']}): {market['token2']}") print(f" Condition ID: {market['condition_id']}") print(f" Trade Size: ${market['trade_size']}") print(f" Max Size: ${market.get('max_size', market['trade_size'])}") print(f" Min Size: ${market['min_size']}") print(f" Max Spread: {market['max_spread']}% ") print(f" Tick Size: ${market['tick_size']}") print(f" Negative Risk: {market['neg_risk']}") print(f" 3-Hour Volatility: {market['3_hour']:.2f}") print(f" Parameter Type: {market['param_type']}\n") # Access hyperparameters for different market types # Keys might be: 'default', 'high_volume', 'volatile', etc. for param_type, params in global_state.params.items(): print(f"\n{param_type} parameters:") print(f" Stop Loss Threshold: {params.get('stop_loss_threshold', -5)}%") print(f" Take Profit Threshold: {params.get('take_profit_threshold', 2)}%") print(f" Volatility Threshold: {params.get('volatility_threshold', 15)}") print(f" Spread Threshold: {params.get('spread_threshold', 0.10)}") print(f" Sleep Period: {params.get('sleep_period', 1)} hours") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.