### Aggressive Polymarket Setup with WS Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Example configuration for an aggressive trading strategy on Polymarket using WebSocket connectivity. ```env # Auth POLYMARKET_PRIVATE_KEY=abc123... POLYMARKET_FUNDER_ADDRESS=0x... # Core ORDER_SIZE=150 MAX_POSITION=750 MAX_DAILY_LOSS=500 MM_VENUE=polymarket # Mode MM_TRADING_MODE=aggressive REFRESH_INTERVAL=2000 # WebSocket MM_WS_ENABLED=true MM_WS_MAX_AGE_MS=3000 MM_WS_ONLY_DIRTY=true # Polymarket Rewards POLYMARKET_REWARD_MIN_EFFICIENCY=0.0015 POLYMARKET_REWARD_PAUSE_MS=180000 # Real trading ENABLE_TRADING=true ``` -------------------------------- ### Install Dependencies Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/README.md Run this command after cloning the repository to install all necessary Node.js dependencies. ```bash npm install ``` -------------------------------- ### start Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Establishes the WebSocket connection. ```APIDOC ## Method: start() ### Description Connects to the WebSocket server and begins receiving updates. ``` -------------------------------- ### Start Market Making with Logging Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/README.md This command starts the market making process using the CLI. It includes logging to provide output and insights into the process. ```bash npm run start:cli ``` -------------------------------- ### Conservative Predict.fun Setup Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Example configuration for a conservative trading strategy on the Predict.fun venue. ```env # Auth PRIVATE_KEY=abc123... API_KEY=key_... PREDICT_ACCOUNT_ADDRESS=0x... # Core Trading ORDER_SIZE=100 MAX_POSITION=500 MAX_DAILY_LOSS=1000 MM_VENUE=predict # Mode MM_TRADING_MODE=conservative REFRESH_INTERVAL=3000 # Enable real trading ENABLE_TRADING=true SIMULATION_MODE=false ``` -------------------------------- ### Authorize Contract for Predict Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/README.md Run this script for the initial setup of Predict to authorize smart contracts. This is a one-time setup for new Predict accounts. ```bash npx tsx src/setup-approvals.ts ``` -------------------------------- ### Position examples Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/types.md Examples of long YES and hedged market-neutral positions. ```typescript // Long YES position { yes_amount: 100, no_amount: 0, avg_entry_price: 0.45, current_price: 0.52, pnl: 7 // 100 * (0.52 - 0.45) = $7 } // Hedged position (market-neutral) { yes_amount: 100, no_amount: -100, // Short 100 NO pnl: 0 // Net risk is zero } ``` -------------------------------- ### Configure WebSocket Settings Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Example configuration for enabling WebSocket feeds and tuning cache behavior. ```bash MM_WS_ENABLED=true MM_WS_MAX_AGE_MS=3000 MM_WS_FALLBACK_REST=true MM_WS_ONLY_DIRTY=true ``` -------------------------------- ### Initialize and Run the Bot Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Demonstrates how to instantiate, initialize, and start the bot, including a graceful shutdown handler. ```typescript import { PredictMarketMakerBot } from './index.js'; const bot = new PredictMarketMakerBot(); await bot.initialize(); await bot.start(); // Runs main loop indefinitely // Graceful shutdown process.on('SIGINT', () => { bot.stop(); // Cancels all orders, closes connections process.exit(0); }); ``` -------------------------------- ### Live Status Output Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Example of the status summary printed during each loop iteration. ```text πŸ“Š Market Maker Status Markets: 10 active Open Orders: 15 Positions: 8 markets Session PnL: +$42.50 WS Health: 95% (fresh data) Uptime: 4h 23m 15s ``` -------------------------------- ### Start WebSocket Feed Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Initiates the connection to the WebSocket server. ```typescript feed.start(); console.log('WebSocket feed connected'); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/README.md Copy the example environment file and edit it to include your API keys and other required credentials. Ensure all necessary fields like API_KEY, PRIVATE_KEY, and PREDICT_ACCOUNT_ADDRESS are filled. ```bash cp .env.example .env # Edit .env to fill in API_KEY, PRIVATE_KEY, PREDICT_ACCOUNT_ADDRESS, etc. ``` -------------------------------- ### Polymarket API Integration Example Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Demonstrates initializing the Polymarket client, checking USDC balances, filtering markets by reward efficiency, and placing GTC buy orders. ```typescript import { PolymarketAPI } from './api/polymarket-client.js'; import { loadConfig } from './config.js'; const config = loadConfig(); const api = new PolymarketAPI( config.polymarketClobUrl, config.polymarketPrivateKey, config.polymarketFunderAddress, config.polymarketApiKey, config.polymarketApiSecret, config.polymarketApiPassphrase ); // Check balance const { usdc } = await api.getBalance(); console.log(`Balance: $${usdc}`); // Get markets with rewards const markets = await api.getMarkets(); const rewardMarkets = markets.filter(m => m.polymarket_rewards_enabled && m.polymarket_reward_efficiency > 0.0015 ); // Place orders on top markets for (const market of rewardMarkets.slice(0, 5)) { const book = await api.getOrderbook(market.token_id); const order = await api.placeOrder({ token_id: market.token_id, side: 'BUY', price: (book.best_bid - 0.01).toFixed(4), // 1c below bid size: 100, time_in_force: 'GTC' }); console.log(`Placed order: ${order.order_id}`); } ``` -------------------------------- ### Predict.fun Example Error Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Concrete example of an INVALID_PRICE error response. ```json { "error": "INVALID_PRICE", "message": "Price must be between 0.0001 and 0.9999" } ``` -------------------------------- ### Place Limit Order via cURL Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Example of placing a limit order using the command line. ```bash curl -X POST \ -H "Authorization: Bearer JWT_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "token_id": "token123", "side": "BUY", "price": "0.50", "shares": 100, "post_only": true }' \ https://api.predict.fun/v1/orders ``` -------------------------------- ### Low-Score Market Calculation Example Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/market-selection-and-filtering.md Example calculation for a market rejected due to low liquidity, high spread, and high fill risk. ```text Market: "Will currency X crash?" - Liquidity 24h: $5,000 (too low) - Volume 24h: $8,000 (too low) - Best Bid: 0.05 - Best Ask: 0.15 - Spread: 100% (10Β’!) β€” extremely wide - L1 Depth: $2 (BID) + $1 (ASK) β€” super thin - Fill Risk Score: 85/100 β€” very high Score Calculation: liquidity: 5,000 * 0.2 = 1,000 volume: 8,000 * 0.05 = 400 price_signal: (0.05 + 0.15) * 100 = 20 -spread_penalty: 1.0 * -50 = -50,000 -risk_penalty: 35,000 (high fill risk) -depth_penalty: 25,000 (thin book) TOTAL: -78,580 ❌ BLOCKED ``` -------------------------------- ### GET /orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch open orders for an account. ```APIDOC ## GET /orders ### Description Fetch open orders. ### Method GET ### Endpoint /orders ### Parameters #### Query Parameters - **address** (string) - Optional - Account address - **orderStatus** (string) - Optional - Filter by status ### Response #### Success Response (200) - **orders** (Array) - List of Order objects ``` -------------------------------- ### High-Score Market Calculation Example Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/market-selection-and-filtering.md Example calculation for a market meeting high liquidity and volume criteria. ```text Market: "Will Apple stock reach $250 by year-end?" - Liquidity 24h: $500,000 - Volume 24h: $1,200,000 - Best Bid: 0.62 - Best Ask: 0.64 - Spread: 2% (1.3Β’) - L1 Depth: $80 (BID) + $75 (ASK) - L2 Depth: $45 (BID) + $50 (ASK) Score Calculation: liquidity: 500,000 * 0.2 = 100,000 volume: 1,200,000 * 0.05 = 60,000 price_signal: (0.62 + 0.64) * 100 = 126 -spread_penalty: 0.02 * -50 = -1,000 -risk_penalty: 0 TOTAL: 159,126 βœ… EXCELLENT ``` -------------------------------- ### Initialize and Start PredictWebSocketFeed Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Instantiate the feed with configuration options and register an orderbook update callback. ```typescript import { PredictWebSocketFeed } from './external/predict-ws.js'; const feed = new PredictWebSocketFeed({ url: 'wss://ws.predict.fun/ws', apiKey: config.apiKey, topicKey: 'token_id', // Subscribe by token_id staleTimeoutMs: 5000, // 5 second TTL resetOnReconnect: true // Clear cache on reconnect }); feed.subscribeMarkets(selectedMarkets); feed.start(); feed.onOrderbook((tokenId) => { console.log(`Orderbook updated: ${tokenId}`); const orderbook = feed.getOrderbook(tokenId, 5000); // Get cached // Immediately reprice or cancel await marketMaker.placeMMOrders(market, orderbook); }); ``` -------------------------------- ### GET /user/{address} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch account information including balance and nonce. ```APIDOC ## GET /user/{address} ### Description Fetch account info. ### Method GET ### Endpoint /user/{address} ### Parameters #### Path Parameters - **address** (string) - Required - Account address ### Response #### Success Response (200) - **address** (string) - Account address - **balance** (number) - USDC balance - **nextNonce** (number) - Next nonce to use ``` -------------------------------- ### GET /markets Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Retrieves a list of all available markets. ```APIDOC ## GET /markets ### Description Lists all available markets on the platform. ### Method GET ### Endpoint /markets ``` -------------------------------- ### Fetch Markets via cURL Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Example request to retrieve a list of markets using an API key for authentication. ```bash curl -H "x-api-key: key_..." \ https://api.predict.fun/v1/markets?limit=50 ``` -------------------------------- ### Configure Custom Markets Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Example of defining specific market token IDs in the configuration to restrict trading. ```typescript // In .env or config MARKET_TOKEN_IDS=market1,market2,market3 // Bot will only trade these markets ``` -------------------------------- ### Get Recommended Markets Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/README.md This script helps identify recommended markets based on specified criteria. Use the --venue and --top flags to filter results. ```bash npx tsx scripts/market-recommender.ts --venue predict --top 10 ``` -------------------------------- ### Initialize Polymarket WebSocket Feed Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Instantiate and start the WebSocket feed to receive orderbook updates for selected markets. ```typescript import { PolymarketWebSocketFeed } from './external/polymarket-ws.js'; const feed = new PolymarketWebSocketFeed({ url: 'wss://clob.polymarket.com/ws', staleTimeoutMs: 5000, resetOnReconnect: true }); feed.subscribeMarkets(selectedMarkets); feed.start(); feed.onOrderbook((tokenId) => { const orderbook = feed.getOrderbook(tokenId, 5000); await mm.placeMMOrders(market, orderbook); }); ``` -------------------------------- ### GET /orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetches orders associated with the user. ```APIDOC ## GET /orders ### Description Retrieves a list of orders placed by the user. ### Method GET ### Endpoint /orders ``` -------------------------------- ### Orderbook Example Response Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md A sample JSON response for an orderbook request, showing bid and ask levels. ```json { "token_id": "token123", "best_bid": 0.55, "best_ask": 0.57, "spread": 0.02, "spread_pct": 0.036, "mid_price": 0.56, "bids": [ { "price": "0.55", "shares": "500" }, { "price": "0.54", "shares": "800" } ], "asks": [ { "price": "0.57", "shares": "600" }, { "price": "0.58", "shares": "900" } ] } ``` -------------------------------- ### GET /balances/{address} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch the USDC balance for a specific account. ```APIDOC ## GET /balances/{address} ### Description Fetch account USDC balance. ### Method GET ### Endpoint /balances/{address} ### Parameters #### Path Parameters - **address** (string) - Required - Account address ### Response #### Success Response (200) - **USDC** (string) - USDC balance as string - **balance** (number) - Numeric balance ``` -------------------------------- ### GET /books/{tokenId} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch the orderbook for a specific token. ```APIDOC ## GET /books/{tokenId} ### Description Fetch orderbook for a token. ### Method GET ### Endpoint /books/{tokenId} ### Parameters #### Path Parameters - **tokenId** (string) - Required - Token ID (outcome) #### Query Parameters - **depth** (number) - Optional - Number of levels ### Response #### Success Response (200) - **bids** (Array) - 2D array of [price, size] - **asks** (Array) - 2D array of [price, size] ``` -------------------------------- ### GET /markets Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch all active markets with optional filtering and pagination. ```APIDOC ## GET /markets ### Description Fetch all active markets. ### Method GET ### Endpoint /markets ### Parameters #### Query Parameters - **skip** (number) - Optional - Records to skip - **limit** (number) - Optional - Records to return - **active** (boolean) - Optional - Filter by active status ### Response #### Success Response (200) - **markets** (Array) - List of PlatformMarket objects ``` -------------------------------- ### Start Market Maker API Call Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/public/index.html Initiates the market maker process by sending a POST request to the /api/start endpoint. Updates the running status and logs the outcome. ```javascript async function startMarketMaker() { try { addLog('info', 'ζ­£εœ¨ε―εŠ¨εšεΈ‚ε•†...'); const response = await fetch('/api/start', { method: 'POST' }); const result = await response.json(); if (result.success) { isRunning = true; startTime = Date.now(); updateStatus(); addLog('success', 'βœ… εšεΈ‚ε•†ε―εŠ¨ζˆεŠŸοΌ'); } else { addLog('error', '❌ 启动倱θ΄₯: ' + result.message); } } catch (error) { addLog('error', '❌ 连ζŽ₯ε€±θ΄₯: ' + error.message); } } ``` -------------------------------- ### GET /orders?orderStatus=OPEN Response Schema Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema for the response when fetching open orders. ```typescript { orders: Order[]; } ``` -------------------------------- ### GET /v1/orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch open orders for the authenticated account, with optional filtering by signer or status. ```APIDOC ## GET /v1/orders ### Description Fetch open orders for account. ### Method GET ### Endpoint /v1/orders ### Parameters #### Query Parameters - **signer** (string) - Optional - Account address - **status** (string) - Optional - Filter by status (OPEN, FILLED, CANCELED) ### Response #### Success Response (200) - **data** (Order[]) - List of orders - **orders** (Order[]) - List of orders ``` -------------------------------- ### GET /balances/{address} Response Schema Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema for the response when fetching account USDC balance. ```typescript { USDC: string; // USDC balance as string balance: number; // Numeric balance } ``` -------------------------------- ### Update Uptime Display Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/public/index.html Calculates and displays the elapsed time since the market maker started in minutes and seconds. Updates every second. ```javascript function updateUptime() { if (!startTime) { document.getElementById('uptime').textContent = '0εˆ† 0η§’'; return; } const elapsed = Math.floor((Date.now() - startTime) / 1000); const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; document.getElementById('uptime').textContent = `${minutes}εˆ† ${seconds}η§’`; } ``` -------------------------------- ### Initialize PolymarketAPI Constructor Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Instantiate the client with base URL and optional authentication credentials. ```typescript const api = new PolymarketAPI( 'https://clob.polymarket.com', config.polymarketPrivateKey, config.polymarketFunderAddress, config.polymarketApiKey, config.polymarketApiSecret, config.polymarketApiPassphrase ); ``` -------------------------------- ### initialize() Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Initializes the market maker with the current market state. ```APIDOC ## initialize() ### Description Initializes the market maker with market state. ### Returns - **Promise** - Resolves when initialization is complete. ### Throws - **Error** - If initialization fails. ``` -------------------------------- ### Load and Validate Configuration Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Validates essential credentials and logs the current configuration state upon startup. ```typescript const config = loadConfig(); if (!config.privateKey) throw new Error('PRIVATE_KEY required'); if (!config.apiKey && config.mmVenue === 'predict') throw new Error('API_KEY required'); console.log(`Loaded config for ${config.mmVenue}`); console.log(`Order size: $${config.orderSize}`); console.log(`Trading mode: ${config.mmTradingMode}`); ``` -------------------------------- ### Initialize Market Maker State and Event Listeners Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/public/index.html Sets up initial state variables and attaches an event listener for DOM content loading to initialize the status and uptime updates. ```javascript let isRunning = false; let startTime = null; let stats = { totalOrders: 0, successOrders: 0, failedOrders: 0, markets: 0, activeOrders: 0 }; // Initialize document.addEventListener('DOMContentLoaded', () => { loadStatus(); setInterval(updateUptime, 1000); }); ``` -------------------------------- ### GET /orderbooks/{id} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Retrieves the orderbook for a specific market ID. ```APIDOC ## GET /orderbooks/{id} ### Description Fetches the orderbook data for a specific market. ### Method GET ### Endpoint /orderbooks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the market. ``` -------------------------------- ### Configure WebSocket and Timeout Settings Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Environment variables to manage WebSocket connectivity and timeout thresholds. ```bash MM_WS_ENABLED=false ``` ```bash MM_WS_MAX_AGE_MS=10000 ``` -------------------------------- ### GET /markets/{marketId} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch details for a single market by its ID. ```APIDOC ## GET /markets/{marketId} ### Description Fetch a single market. ### Method GET ### Endpoint /markets/{marketId} ### Parameters #### Path Parameters - **marketId** (string) - Required - Market ID (e.g., condition_id) ### Response #### Success Response (200) - **market** (Object) - PlatformMarket object ``` -------------------------------- ### Lifecycle Initialization Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Perform the initialization sequence to prepare the market maker for trading. ```typescript await mm.initialize(); console.log('Market maker ready'); ``` -------------------------------- ### Run Market Recommender Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Use this script to identify and verify markets that meet safety thresholds. ```bash npx tsx scripts/market-recommender.ts ``` -------------------------------- ### Configure trading parameters Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Set order sizing and risk management limits via environment variables. ```text ORDER_SIZE=100 MAX_POSITION=500 MAX_DAILY_LOSS=1000 ``` -------------------------------- ### GET /v1/auth/message Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Retrieve a message that must be signed by the user to authenticate. ```APIDOC ## GET /v1/auth/message ### Description Get message to sign for JWT generation. ### Method GET ### Endpoint /v1/auth/message ### Parameters #### Query Parameters - **signer** (string) - Optional - Account address ### Response #### Success Response (200) - **data** (string) - Authentication message - **message** (string) - Authentication message ``` -------------------------------- ### Market Maker Lifecycle Integration Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Demonstrates the full lifecycle including initialization, the main execution loop, and shutdown procedures. ```typescript // Full lifecycle import { MarketMaker } from './market-maker.js'; import { PredictAPI } from './api/client.js'; import { loadConfig } from './config.js'; const config = loadConfig(); const api = new PredictAPI(config.apiBaseUrl, config.apiKey, config.jwtToken); const mm = new MarketMaker(api, config); // Initialize await mm.initialize(); // Main loop while (true) { // Sync state every 30s if (Date.now() - lastStateUpdate > 30_000) { await mm.updateState(config.predictAccountAddress); lastStateUpdate = Date.now(); } // Place/reprice orders for each market for (const market of selectedMarkets) { const orderbook = await api.getOrderbook(market.token_id); await mm.placeMMOrders(market, orderbook); } mm.printStatus(); await sleep(config.refreshInterval); } // Shutdown mm.cancelAllOpenOrders(); ``` -------------------------------- ### Authentication Message Retrieval Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema and example response for obtaining a message to sign. ```typescript { data?: string; message?: string; } ``` ```text "Please sign this message to authenticate: \nNonce: abc123" ``` -------------------------------- ### GET /markets Response Schema Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema for the response when fetching all active markets. ```typescript { markets: PlatformMarket[]; } ``` -------------------------------- ### Get Feed Status Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Retrieves the current connection and health status of the feed. ```typescript interface WsFeedStatus { connected: boolean; lastMessageAt?: number; // unix ms of last message messageCount: number; errorCount: number; markets: Map; } const status = feed.getStatus(); if (!status.connected) { console.log('WS disconnected, falling back to REST'); } ``` -------------------------------- ### Configuration Hierarchy Structure Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/INDEX.md Visual representation of the .env file configuration hierarchy, including authentication, core trading parameters, and strategy settings. ```text .env file β”œβ”€ Authentication (PRIVATE_KEY, API_KEY, JWT_TOKEN, etc.) β”œβ”€ Core Trading (ORDER_SIZE, MAX_POSITION, MAX_DAILY_LOSS) β”œβ”€ Trading Mode (MM_TRADING_MODE: conservative|aggressive) β”œβ”€ Strategy (900+ tuning parameters) β”‚ β”œβ”€ Spread Control (SPREAD, MIN_SPREAD, MAX_SPREAD) β”‚ β”œβ”€ Market Selection (MM_VENUE, MARKET_TOKEN_IDS) β”‚ β”œβ”€ Risk Management (MM_FILL_RISK_*, MM_POSITION_MONITOR_*) β”‚ β”œβ”€ WebSocket (MM_WS_ENABLED, MM_WS_MAX_AGE_MS, etc.) β”‚ └─ Platform-Specific (PREDICT_*, POLYMARKET_*) └─ Metrics (MM_METRICS_PATH, ENABLE_TRADING, SIMULATION_MODE) ``` -------------------------------- ### GET /user/{address} Response Schema Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema for the response when fetching account information. ```typescript { address: string; balance: number; // USDC balance nextNonce: number; // Next nonce to use } ``` -------------------------------- ### Configure WebSocket and Fallback Settings Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Environment variables to control WebSocket enablement, data age thresholds, and fallback frequency. ```env MM_WS_ENABLED=true MM_WS_MAX_AGE_MS=5000 MM_WS_FALLBACK_REST=true MM_WS_FALLBACK_MIN_INTERVAL_MS=1000 # Don't REST fallback more than once per second MM_WS_GAP_MAX=3 # After 3 bad data points, enter gap MM_WS_GAP_COOLDOWN_MS=30000 # Gap lasts 30 seconds MM_WS_GAP_RECONNECT=true # Attempt WS reconnect ``` -------------------------------- ### GET /markets/{marketId} Response Schema Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema for the response when fetching a single market. ```typescript { market: PlatformMarket; } ``` -------------------------------- ### Initialize MarketMaker Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Instantiate the MarketMaker with a configured API client and initialize the service. ```typescript import { MarketMaker } from './market-maker.js'; import { PredictAPI } from './api/client.js'; const api = new PredictAPI(config.apiBaseUrl, config.apiKey, config.jwtToken); const mm = new MarketMaker(api, config); await mm.initialize(); ``` -------------------------------- ### GET /v1/markets Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch a list of all active markets with optional pagination and venue filtering. ```APIDOC ## GET /v1/markets ### Description Fetch all active markets. Supports pagination and venue filtering. ### Method GET ### Endpoint /v1/markets ### Parameters #### Query Parameters - **skip** (number) - Optional - Records to skip - **limit** (number) - Optional - Records to return - **venue** (string) - Optional - Filter by venue ### Response #### Success Response (200) - **data** (Market[]) - List of markets - **markets** (Market[]) - List of markets - **items** (Market[]) - List of markets ``` -------------------------------- ### Authentication Configuration Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Required environment variables for wallet and API authentication. ```env PRIVATE_KEY=abc123... # Wallet private key PREDICT_ACCOUNT_ADDRESS=0x... # Predict account (optional) API_KEY=key_... # Predict API key POLYMARKET_PRIVATE_KEY=... # Polymarket wallet key POLYMARKET_FUNDER_ADDRESS=0x... # Polymarket funder ``` -------------------------------- ### Exchange Signed Message for JWT Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Request body schema and example response for the authentication exchange. ```typescript { signer: string; // Account address signature: string; // Signed message (0x-prefixed hex) message: string; // Original message (from /auth/message) } ``` ```typescript { data?: { token?: string; jwt?: string; accessToken?: string; }; token?: string; jwt?: string; accessToken?: string; } ``` ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` -------------------------------- ### PolymarketAPI Constructor Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Initializes a new instance of the PolymarketAPI client with the necessary configuration for interacting with the CLOB API. ```APIDOC ## Constructor ### Description Initializes the PolymarketAPI client. This client handles order placement, cancellation, position queries, and reward calculations. ### Parameters - **baseUrl** (string) - Required - CLOB API base URL (e.g., https://clob.polymarket.com) - **privateKey** (string) - Optional - Wallet private key for signing orders - **funderAddress** (string) - Optional - Funder wallet address for USDC approval - **apiKey** (string) - Optional - API key for L2 authentication - **apiSecret** (string) - Optional - API secret for L2 authentication - **apiPassphrase** (string) - Optional - API passphrase for L2 authentication ``` -------------------------------- ### GET /v1/positions Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch account positions, optionally filtered by signer or market token ID. ```APIDOC ## GET /v1/positions ### Description Fetch account positions. ### Method GET ### Endpoint /v1/positions ### Parameters #### Query Parameters - **signer** (string) - Optional - Account address - **tokenId** (string) - Optional - Filter by market ### Response #### Success Response (200) - **data** (Position[]) - List of positions - **positions** (Position[]) - List of positions ``` -------------------------------- ### Configure Aggressive Fill Detection Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Settings for shorter cooldowns and faster turnover in active market conditions. ```bash MM_FILL_COOLDOWN_MS=14400000 # 4 hours MM_FILL_BLACKLIST_THRESHOLD=2 MM_FILL_BLACKLIST_DURATION_MS=172800000 # 2 days ``` -------------------------------- ### Configure Trading Mode Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Set the MM_TRADING_MODE environment variable to toggle between conservative and aggressive trading strategies. ```bash MM_TRADING_MODE=conservative # - Orders at 4th level of orderbook # - 3-level front protection # - 6-hour cooldown after fill # - 7-day blacklist on repeated fills ``` ```bash MM_TRADING_MODE=aggressive # - Orders at 3rd level of orderbook # - 2-level front protection # - 4-hour cooldown after fill # - 48-hour blacklist ``` -------------------------------- ### GET /v1/markets/{tokenId} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Retrieve details for a specific market using its unique token ID. ```APIDOC ## GET /v1/markets/{tokenId} ### Description Fetch a single market by token ID. ### Method GET ### Endpoint /v1/markets/{tokenId} ### Parameters #### Path Parameters - **tokenId** (string) - Required - Market token ID ### Response #### Success Response (200) - **data** (Market) - Market details - **market** (Market) - Market details ``` -------------------------------- ### Get Session PnL Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Calculate and retrieve the total unrealized PnL for the current trading session. ```typescript const pnl = mm.getSessionPnL(); console.log(`Session PnL: $${pnl.toFixed(2)}`); ``` -------------------------------- ### Strategy Tuning Parameters Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Advanced configuration for spread control, risk management, and WebSocket connectivity. ```env # Spread control SPREAD=0.02 MIN_SPREAD=0.01 MAX_SPREAD=0.08 # Risk management MM_FILL_RISK_THRESHOLD=50 MM_POSITION_MONITOR_ENABLED=true MM_FILL_COOLDOWN_MS=7200000 # WebSocket tuning MM_WS_ENABLED=true MM_WS_MAX_AGE_MS=5000 MM_WS_FALLBACK_REST=true ``` -------------------------------- ### Project Direct Dependencies Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md List of required production dependencies for the Predict Market Maker bot. ```json { "@predictdotfun/sdk": "^1.0.0", // Predict.fun SDK "@polymarket/clob-client": "^5.2.3", // Polymarket CLOB "@polymarket/order-utils": "^3.0.1", // Polymarket order signing "ethers": "^6.13.0", // Ethereum library "viem": "^2.21.4", // Viem for Web3 "axios": "^1.7.2", // HTTP client "dotenv": "^16.4.5", // .env loading "ws": "^8.17.0" // WebSocket client } ``` -------------------------------- ### Get Position Count Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Retrieve the number of markets where the engine currently holds open positions. ```typescript const posCount = mm.getPositionCount(); console.log(`Positions in ${posCount} markets`); ``` -------------------------------- ### Main Loop Operation Logic Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Outlines the startup, execution, and shutdown phases of the market maker process. ```text STARTUP: 1. Load configuration from .env 2. Connect to API (test connection) 3. Auto-fetch JWT if missing 4. Load/validate wallet 5. Select initial markets (step-by-step pipeline) 6. Initialize MarketMaker with state sync 7. Setup WebSocket feeds (if enabled) 8. Print system status MAIN LOOP (every 2-3 seconds): 1. Update WebSocket health score 2. Sync positions & orders (every 30 seconds) 3. Process dirty markets from WebSocket 4. For each market: a. Fetch current orderbook (WS or REST) b. Calculate dynamic spread & prices c. Validate against risk thresholds d. Place/reprice/cancel orders as needed e. Track fills and PnL 5. Print live status 6. Sleep 2-3 seconds 7. Loop SHUTDOWN: 1. Cancel all open orders 2. Close WebSocket connections 3. Flush metrics to disk 4. Print final P&L ``` -------------------------------- ### API Versioning and Fallback Handling Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Demonstrates explicit versioning and automatic fallback logic for API paths. ```typescript // Force v1 https://api.predict.fun/v1/... // Will try both const paths = ['/v1/...', '/...']; // Tries v1 first, then legacy ``` -------------------------------- ### WebSocket Configuration Reference Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Environment variables for enabling, tuning, and configuring WebSocket connections and fallback behaviors. ```env # Enable WebSocket MM_WS_ENABLED=true # Cache freshness (ms) MM_WS_MAX_AGE_MS=5000 # Fallback behavior MM_WS_FALLBACK_REST=true MM_WS_FALLBACK_MIN_INTERVAL_MS=1000 # Dirty-order processing MM_WS_ONLY_DIRTY=true MM_WS_DIRTY_MAX_BATCH=10 # Connection health MM_WS_GAP_MAX=3 MM_WS_GAP_COOLDOWN_MS=30000 MM_WS_GAP_RECONNECT=true # Predict-specific PREDICT_WS_URL=wss://ws.predict.fun/ws PREDICT_WS_API_KEY=... PREDICT_WS_TOPIC_KEY=token_id PREDICT_WS_STALE_MS=5000 # Polymarket-specific POLYMARKET_WS_ENABLED=true POLYMARKET_WS_URL=wss://clob.polymarket.com/ws POLYMARKET_WS_STALE_MS=5000 ``` -------------------------------- ### Core Trading Parameters Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md Essential settings for order sizing, risk management, and venue selection. ```env ORDER_SIZE=100 # Per order in USD MAX_POSITION=500 # Per market max MAX_DAILY_LOSS=1000 # Stop-loss limit MM_TRADING_MODE=conservative # or aggressive MM_VENUE=predict # or polymarket ``` -------------------------------- ### GET /v1/orderbooks/{tokenId} Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Fetch the current orderbook for a specific market, including bid and ask levels. ```APIDOC ## GET /v1/orderbooks/{tokenId} ### Description Fetch orderbook for a market. ### Method GET ### Endpoint /v1/orderbooks/{tokenId} ### Parameters #### Path Parameters - **tokenId** (string) - Required - Market token ID #### Query Parameters - **depth** (number) - Optional - Number of levels (default 10) ### Response #### Success Response (200) - **data** (Orderbook) - Orderbook data - **orderbook** (Orderbook) - Orderbook data ``` -------------------------------- ### Load configuration in TypeScript Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Use the loadConfig function to initialize application settings from the environment. ```typescript import { loadConfig } from './config.js'; const config = loadConfig(); ``` -------------------------------- ### Get Open Orders Count Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Retrieve the total number of open orders currently managed by the engine. ```typescript const count = mm.getOpenOrdersCount(); console.log(`${count} open orders`); ``` -------------------------------- ### getRewardInfo() Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Fetches current maker rewards configuration. ```APIDOC ## getRewardInfo() ### Description Fetch current maker rewards configuration. ### Returns - **RewardInfo** - Reward rates, thresholds, and eligibility criteria ``` -------------------------------- ### GET /books/{tokenId} Response Schema Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Schema for the orderbook response, returning bids and asks as 2D arrays. ```typescript { bids: Array<[price: string, size: string]>; // 2D array asks: Array<[price: string, size: string]>; } ``` -------------------------------- ### Initialize MarketSelector Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/market-selection-and-filtering.md Instantiate the selector with specific thresholds for liquidity, volume, spread, and orderbook depth. ```typescript const selector = new MarketSelector( 0, // minLiquidity disabled 0, // minVolume disabled 0.06, // Max spread 6% 0 // minOrders disabled ); ``` -------------------------------- ### Authenticate with Level 1 (User Wallet) Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Use a private key and funder address to sign orders directly. ```typescript const api = new PolymarketAPI( 'https://clob.polymarket.com', privateKey, // Sign orders with this key funderAddress ); ``` -------------------------------- ### Get JWT Token for Predict Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/README.md Execute this command to obtain a JWT token, which is specifically required for Predict. This is typically needed for authentication. ```bash npx tsx src/auth-jwt.ts ``` -------------------------------- ### PredictWebSocketFeed Constructor Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Initializes a new instance of the PredictWebSocketFeed with configuration options. ```APIDOC ## Constructor: new PredictWebSocketFeed(config: PredictWebSocketFeedConfig) ### Description Initializes the WebSocket feed client with the specified connection and caching parameters. ### Parameters - **config** (PredictWebSocketFeedConfig) - Required - **url** (string) - Optional - WebSocket endpoint URL - **apiKey** (string) - Optional - API authentication key - **topicKey** ('token_id' | 'condition_id' | 'event_id') - Optional - Subscription key type - **staleTimeoutMs** (number) - Optional - Cache TTL in milliseconds - **resetOnReconnect** (boolean) - Optional - Whether to clear cache on reconnect ``` -------------------------------- ### Place Market and Limit Orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Shows how to configure order types and time-in-force parameters for both aggressive market orders and patient limit orders. ```typescript // Aggressive - buy at market const marketOrder = await api.placeOrder({ token_id: 'token123', side: 'BUY', price: '0.60', // Will execute at best price up to this size: 100, order_type: 'MARKET', time_in_force: 'FOK' // All or nothing }); // Patient maker - sit on limit const limitOrder = await api.placeOrder({ token_id: 'token123', side: 'SELL', price: '0.45', size: 100, order_type: 'LIMIT', time_in_force: 'GTC' // Wait as long as needed }); ``` -------------------------------- ### printStatus() Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-market-maker.md Prints the live trading status to the console. ```APIDOC ## printStatus() ### Description Print live trading status to console. ``` -------------------------------- ### POST /orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Creates a new order, including signature verification. ```APIDOC ## POST /orders ### Description Submits a new order to the market. This process includes signature verification. ### Method POST ### Endpoint /orders ``` -------------------------------- ### PredictAPI Constructor Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-predict-api.md Initializes a new instance of the PredictAPI client with the specified base URL and authentication credentials. ```APIDOC ## Constructor ### Description Initializes the PredictAPI client to handle requests to the Predict.fun REST API. It supports optional API key and JWT token authentication. ### Signature `new PredictAPI(baseUrl: string, apiKey?: string, jwtToken?: string)` ### Parameters - **baseUrl** (string) - Required - The API base URL (e.g., https://api.predict.fun). - **apiKey** (string) - Optional - API key for the x-api-key header. - **jwtToken** (string) - Optional - JWT token for the Authorization: Bearer header. ### Example ```typescript const api = new PredictAPI( 'https://api.predict.fun', 'your-api-key-here', 'your-jwt-token-here' ); ``` ``` -------------------------------- ### Project Development Dependencies Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/README.md List of required development dependencies for the Predict Market Maker bot. ```json { "typescript": "^5.5.0", "tsx": "^4.15.0", // TypeScript executor "electron": "^30.0.0", // Desktop app (lite version) "electron-builder": "^24.13.3" // App packaging } ``` -------------------------------- ### Troubleshoot Order Fill Surprises Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/websocket-integration.md Resolution steps for discrepancies between WebSocket book data and actual order fills. ```text Order filled when WS said book was thick β†’ WS cache was stale, missed the attack β†’ Decrease mmWsMaxAgeMs (more aggressive caching) β†’ Or disable WS, use REST only ``` -------------------------------- ### POST /v1/orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Place a new limit order on the market. ```APIDOC ## POST /v1/orders ### Description Place a limit order. ### Method POST ### Endpoint /v1/orders ### Parameters #### Request Body - **token_id** (string) - Required - Market token ID - **side** ('BUY' | 'SELL') - Required - Buy or sell YES token - **price** (string | number) - Required - Limit price (0.0001-0.9999) - **shares** (string | number) - Required - Number of shares - **order_type** ('LIMIT') - Optional - Always LIMIT - **post_only** (boolean) - Optional - If true, reject if would fill - **client_order_id** (string) - Optional - Idempotency key ### Response #### Success Response (200) - **data** (Order) - Order details - **order** (Order) - Order details - **order_hash** (string) - Unique order ID - **status** ('OPEN' | 'FILLED' | 'CANCELED') - Order status ``` -------------------------------- ### Initialize PredictAPI Client Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-predict-api.md Instantiate the client with a base URL and optional authentication credentials. JWT tokens are automatically normalized. ```typescript const api = new PredictAPI( 'https://api.predict.fun', 'your-api-key-here', 'your-jwt-token-here' ); // JWT token with optional Bearer prefix is auto-normalized const api2 = new PredictAPI(config.apiBaseUrl, config.apiKey, config.jwtToken); ``` -------------------------------- ### Handle Order Placement Errors Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Demonstrates error handling for order placement, specifically checking for common failure reasons like insufficient balance or invalid signatures. ```typescript try { const order = await api.placeOrder({ token_id: 'token123', side: 'BUY', price: '0.50', size: 1000 }); } catch (error) { if (error.message.includes('insufficient balance')) { console.error('Not enough USDC'); } else if (error.message.includes('invalid signature')) { console.error('Private key invalid'); } else if (error.message.includes('invalid price')) { console.error('Price out of range'); } else { console.error('Order placement failed:', error.message); } } ``` -------------------------------- ### POST /orders Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Place a new limit order on the platform. ```APIDOC ## POST /orders ### Description Place a limit order. ### Method POST ### Endpoint /orders ### Parameters #### Request Body - **tokenId** (string) - Required - Token ID - **side** (string) - Required - 'BUY' or 'SELL' - **size** (string|number) - Required - Size in shares - **price** (string|number) - Required - Limit price - **signerAddress** (string) - Required - User's address - **nonce** (string) - Required - Unique nonce - **expiration** (number) - Required - Unix timestamp - **signature** (string) - Required - Order signature - **orderType** (string) - Optional - 'LIMIT' or 'MARKET' - **timeInForce** (string) - Optional - 'GTC', 'FOK', or 'FAK' ### Response #### Success Response (200) - **id** (string) - Order ID - **status** (string) - Order status ``` -------------------------------- ### placeOrder(order: PlaceOrderRequest) Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/api-reference-polymarket-api.md Places a limit order on the Polymarket platform. ```APIDOC ## placeOrder(order: PlaceOrderRequest) ### Description Place a limit order on Polymarket. ### Parameters - **order** (PlaceOrderRequest) - Required - Order details including token_id, side, price, size, and time_in_force. ### Returns - **Order** - Confirmed order with order_id ``` -------------------------------- ### Configure FLATTEN Hedging Mode Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Sets the hedging mode to FLATTEN, which eliminates directional risk by buying both YES and NO shares after a fill. ```bash HEDGE_MODE=FLATTEN # After fill: simultaneously buy YES and NO to return to zero position # Locks in loss but eliminates directional risk ``` -------------------------------- ### API Versioning Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/http-endpoints.md Guidelines for handling API versions and breaking changes. ```APIDOC ## API Versioning ### Description The API supports versioning to ensure stability. Current stable version is v1, with legacy endpoints still supported for fallback. ### Versioning Strategy - **v1**: Current stable API (e.g., https://api.predict.fun/v1/...) - **legacy**: Old endpoints supported for fallback. - **Deprecated endpoints**: Return 301 Moved Permanently with a Location header. ``` -------------------------------- ### MarketSelector Constructor Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/market-selection-and-filtering.md Initializes a new MarketSelector instance with specific market filtering thresholds. ```APIDOC ## constructor(minLiquidity, minVolume24h, maxSpread, minOrders) ### Description Initializes the market selector with safety and profitability thresholds. ### Parameters - **minLiquidity** (number) - Required - Minimum USD liquidity (0 = disabled) - **minVolume24h** (number) - Required - Minimum 24h volume (0 = disabled) - **maxSpread** (number) - Required - Maximum spread % (e.g., 0.06 = 6%) - **minOrders** (number) - Required - Minimum orderbook levels (0 = disabled) ``` -------------------------------- ### Configure Predict.fun Safety and Loss Limits Source: https://github.com/ccjingeth/predict-fun-marketmaker/blob/main/_autodocs/configuration.md Sets custom safety thresholds and pause durations for the market maker, overriding default values. ```bash PREDICT_SAFE_MAX_SPREAD=0.06 PREDICT_FILL_PAUSE_MS=21600000 # 6 hours = conservative mode PREDICT_POSITION_LOSS_LIMIT_ABS=50 ```