### JavaScript WebSocket Example Source: https://docs.polynode.dev/llms.txt Demonstrates how to connect to the Polynode WebSocket API and subscribe to events using JavaScript. This example shows basic connection and message handling. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api.polymarket.com'); ws.on('open', () => { console.log('Connected to Polynode WebSocket'); // Example: Subscribe to trade events ws.send(JSON.stringify({ "op": "subscribe", "args": ["trade"] })); }); ws.on('message', (data) => { console.log('Received message:', data); }); ws.on('error', (error) => { console.error('WebSocket error:', error); }); ws.on('close', () => { console.log('Disconnected from Polynode WebSocket'); }); ``` -------------------------------- ### Get Gas Oracle Data (RPC) Source: https://docs.polynode.dev/llms.txt Example of how to query the PolyNode Gas Oracle for real-time gas price intelligence. This is useful for optimizing transaction positioning. ```bash curl -X POST --data '{"jsonrpc":"2.0","method":"polynode_gasOracle","params":[],"id":1}' https://rpc.polynode.xyz/YOUR_API_KEY ``` -------------------------------- ### Python WebSocket Example Source: https://docs.polynode.dev/llms.txt Provides an example of connecting to the Polynode WebSocket API and subscribing to events using Python. This snippet illustrates establishing a connection and processing incoming messages. ```python import websocket import json def on_message(ws, message): print(f"Received: {message}") def on_error(ws, error): print(f"Error: {error}") def on_close(ws, close_status_code, close_msg): print("### closed ###") def on_open(ws): print("Connected to Polynode WebSocket") # Example: Subscribe to trade events ws.send(json.dumps({ "op": "subscribe", "args": ["trade"] })) if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://api.polymarket.com", on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) ws.run_forever() ``` -------------------------------- ### WebSocket API Examples and Usage Source: https://docs.polynode.dev/llms.txt This section provides links to examples and general usage information for the Polynode WebSocket API, including how to subscribe to events and filter data. ```APIDOC ## WebSocket API Usage ### Examples **Description:** Access complete WebSocket examples in JavaScript, Python, and wscat. **Link:** [https://polynode.mintlify.app/websocket/examples.md](https://polynode.mintlify.app/websocket/examples.md) ### Overview **Description:** Understand how to get real-time Polymarket settlements, up to 5 seconds before on-chain confirmation. **Link:** [https://polynode.mintlify.app/websocket/overview.md](https://polynode.mintlify.app/websocket/overview.md) ### Subscriptions & Filters **Description:** Learn about available subscription types, filter options, and how event matching works. **Link:** [https://polynode.mintlify.app/websocket/subscribing.md](https://polynode.mintlify.app/websocket/subscribing.md) ``` -------------------------------- ### wscat WebSocket Example Source: https://docs.polynode.dev/llms.txt Illustrates using the wscat command-line tool to connect to the Polynode WebSocket API and subscribe to events. This is useful for quick testing and debugging. ```bash # Connect and subscribe to trade events wscat -c wss://api.polymarket.com -x '{"op": "subscribe", "args": ["trade"]}' # Connect and subscribe to all events wscat -c wss://api.polymarket.com -x '{"op": "subscribe", "args": ["*"]}' ``` -------------------------------- ### Local Cache with SQLite Source: https://docs.polynode.dev/llms.txt Example demonstrating the use of the PolyNode local cache, backed by SQLite. This allows for offline queries and fast backfilling of wallet history. ```python from polynode_sdk.local_cache import LocalCache cache = LocalCache(db_path='polynode.db') # Backfill wallet history cache.backfill_wallet_history('0x123...') # Query local positions positions = cache.get_positions('0x123...') print(positions) # Stream live updates (example) # cache.stream_updates() ``` -------------------------------- ### WebSocket Streaming with Compression Source: https://docs.polynode.dev/llms.txt Example demonstrating how to use the PolyNode WebSocket streaming client with zlib compression enabled to reduce bandwidth usage. ```javascript import { WebSocketStream } from '@polynode/sdk'; const stream = new WebSocketStream({ apiKey: 'YOUR_API_KEY', compress: true // Enable zlib compression }); stream.on('blockEvent', (event) => { console.log('New Block Event:', event); }); stream.connect(); ``` -------------------------------- ### GET /system/health-check Source: https://docs.polynode.dev/llms.txt Performs a liveness probe to verify if the PolyNode server is operational. ```APIDOC ## GET /system/health-check ### Description Checks if the API server is currently running and responsive. ### Method GET ### Endpoint /system/health-check ### Response #### Success Response (200) - **status** (string) - Returns 'OK' when the server is healthy. #### Response Example { "status": "OK" } ``` -------------------------------- ### Connect to Orderbook Stream (Python) Source: https://docs.polynode.dev/llms.txt Example code for connecting to the PolyNode Orderbook Stream using Python. This enables real-time retrieval of orderbook data for Polymarket markets. ```python import websocket import json ws = websocket.WebSocketApp("wss://stream.polynode.xyz", on_open = lambda ws: ws.send(json.dumps({ "type": "subscribe", "channels": ["orderbook"], "markets": ["0x123..."] # Replace with actual market address })), on_message = lambda ws, message: print(json.loads(message)), on_error = lambda ws, error: print(f"Error: {error}"), on_close = lambda ws, close_status_code, close_msg: print("### closed ###")) ws.run_forever() ``` -------------------------------- ### Fetch Wallet Positions (REST API) Source: https://docs.polynode.dev/llms.txt Example of how to fetch a wallet's current positions and P&L breakdown using the PolyNode REST API. Requires an API key for authentication. ```bash curl -X GET "https://api.polynode.xyz/v1/wallets/positions?address=0x123..." \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Track Transaction Status (RPC) Source: https://docs.polynode.dev/llms.txt Example of how to track a transaction's block position and confirmation status using the PolyNode RPC endpoint. Requires your API key. ```bash curl -X POST --data '{"jsonrpc":"2.0","method":"polynode_txTracking","params":["0x..."],"id":1}' https://rpc.polynode.xyz/YOUR_API_KEY ``` -------------------------------- ### Redemption Watcher Notifications Source: https://docs.polynode.dev/llms.txt Example of setting up push notifications using the Redemption Watcher SDK when Polymarket positions become redeemable. This helps in timely actions. ```python from polynode_sdk.redemption_watcher import RedemptionWatcher watcher = RedemptionWatcher(api_key='YOUR_API_KEY') # Subscribe to notifications for a specific market watcher.subscribe_to_market('0x123...') watcher.on_redeemable(lambda position: print(f"Position redeemable: {position}")) watcher.start() ``` -------------------------------- ### Short-Form Market Streams Source: https://docs.polynode.dev/llms.txt Example of subscribing to auto-rotating streams for short-form crypto prediction markets (5-min, 15-min, hourly) using the PolyNode SDK. ```javascript import { ShortFormStream } from '@polynode/sdk'; const stream = new ShortFormStream({ apiKey: 'YOUR_API_KEY', marketTypes: ['5m', '15m', '1h'] // Specify market durations }); stream.on('marketUpdate', (data) => { console.log('Short-Form Market Update:', data); }); stream.connect(); ``` -------------------------------- ### GET /wallets/resolve Source: https://docs.polynode.dev/llms.txt Resolves a wallet address, EOA, or username to its canonical form. ```APIDOC ## GET /wallets/resolve ### Description Instantly resolve any Polymarket wallet address, EOA, or username to verify identity. ### Method GET ### Endpoint /wallets/resolve ### Parameters #### Query Parameters - **identifier** (string) - Required - The address, EOA, or username to resolve. ### Response #### Success Response (200) - **resolved_address** (string) - The canonical wallet address. #### Response Example { "resolved_address": "0x1234567890abcdef1234567890abcdef12345678" } ``` -------------------------------- ### GET /markets/market-by-slug Source: https://docs.polynode.dev/llms.txt Retrieves detailed market information using the unique URL slug of the market. ```APIDOC ## GET /markets/market-by-slug ### Description Looks up a market by its URL slug to return full metadata, token IDs, and current outcome prices. ### Method GET ### Endpoint /markets/market-by-slug ### Parameters #### Query Parameters - **slug** (string) - Required - The URL slug of the market. ### Response #### Success Response (200) - **id** (string) - The market ID. - **question** (string) - The market question. - **tokens** (array) - List of outcome tokens with prices. #### Response Example { "id": "12345", "question": "Will it rain today?", "tokens": [{"id": "A", "price": 0.5}, {"id": "B", "price": 0.5}] } ``` -------------------------------- ### Connect to Orderbook Stream (JavaScript) Source: https://docs.polynode.dev/llms.txt Example code for connecting to the PolyNode Orderbook Stream using JavaScript. This allows real-time access to orderbook data for Polymarket markets. ```javascript import WebSocket from 'ws'; const socket = new WebSocket('wss://stream.polynode.xyz'); socket.onopen = () => { console.log('Connected to Orderbook Stream'); // Example: Subscribe to a market socket.send(JSON.stringify({ "type": "subscribe", "channels": ["orderbook"], "markets": ["0x123..."] // Replace with actual market address })); }; socket.onmessage = (event) => { const data = JSON.parse(event.data); console.log(data); }; socket.onclose = () => { console.log('Disconnected from Orderbook Stream'); }; socket.onerror = (error) => { console.error('WebSocket Error:', error); }; ``` -------------------------------- ### GET /orderbook/order-book Source: https://docs.polynode.dev/llms.txt Fetches the full order book for a specific token, including bid and ask levels. ```APIDOC ## GET /orderbook/order-book ### Description Returns the full order book for a token, including all bid and ask price levels and PolyNode metadata. ### Method GET ### Endpoint /orderbook/order-book ### Parameters #### Query Parameters - **token_id** (string) - Required - The ID of the token. ### Response #### Success Response (200) - **bids** (array) - List of bid price levels. - **asks** (array) - List of ask price levels. #### Response Example { "bids": [{"price": 0.45, "size": 100}], "asks": [{"price": 0.46, "size": 100}] } ``` -------------------------------- ### GET /wallets/trades Source: https://docs.polynode.dev/llms.txt Fetches recent trade history for a wallet, enriched with market metadata. ```APIDOC ## GET /wallets/trades ### Description Returns recent trades for a wallet, enriched with PolyNode market metadata. Each trade includes side (BUY/SELL), price, size, outcome, and transaction hash. ### Method GET ### Endpoint /wallets/trades ### Parameters #### Query Parameters - **wallet_address** (string) - Required - The wallet address to fetch trades for. ### Response #### Success Response (200) - **trades** (array) - List of recent trade objects. #### Response Example { "trades": [ { "side": "BUY", "price": 0.55, "size": 100, "outcome": "Yes", "tx_hash": "0xabc..." } ] } ``` -------------------------------- ### Handle Oracle Event (WebSocket) Source: https://docs.polynode.dev/llms.txt Example code for subscribing to and processing 'oracle' events from the PolyNode WebSocket stream. These events cover UMA Optimistic Oracle actions on Polymarket. ```javascript import { WebSocketStream } from '@polynode/sdk'; const stream = new WebSocketStream({ apiKey: 'YOUR_API_KEY' }); stream.on('oracleEvent', (event) => { console.log(`Oracle Event Type: ${event.eventType}`); console.log(` Market: ${event.marketAddress}`); console.log(` Timestamp: ${event.timestamp}`); // Log specific details based on eventType }); stream.connect(); ``` -------------------------------- ### Fetch Wallet Trade History (REST API) Source: https://docs.polynode.dev/llms.txt Example of how to retrieve a wallet's recent trade history using the PolyNode REST API. Includes market metadata enrichment. Requires an API key. ```bash curl -X GET "https://api.polynode.xyz/v1/wallets/trades?address=0x123..." \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Handle Deposit Event (WebSocket) Source: https://docs.polynode.dev/llms.txt Example code for subscribing to and processing 'deposit' events from the PolyNode WebSocket stream. These events track USDC deposits and withdrawals on Polymarket. ```javascript import { WebSocketStream } from '@polynode/sdk'; const stream = new WebSocketStream({ apiKey: 'YOUR_API_KEY' }); stream.on('deposit', (event) => { console.log(`USDC ${event.type} detected:`); console.log(` Tx Hash: ${event.transactionHash}`); console.log(` Amount: ${event.amount}`); console.log(` Wallet: ${event.walletAddress}`); }); stream.connect(); ``` -------------------------------- ### Orderbook Streaming SDK Source: https://docs.polynode.dev/llms.txt Example of using the PolyNode SDK for real-time orderbook data with local state management. Supports filtered views and efficient data handling. ```javascript import { OrderbookStream } from '@polynode/sdk'; const stream = new OrderbookStream({ apiKey: 'YOUR_API_KEY', markets: ['0x123...'] // Optional: filter by market }); stream.on('orderbookUpdate', (data) => { console.log('Orderbook Update:', data); }); stream.on('error', (err) => { console.error('Stream Error:', err); }); stream.connect(); ``` -------------------------------- ### GET /wallets/positions Source: https://docs.polynode.dev/llms.txt Retrieves all current positions for a specific wallet, including a detailed P&L breakdown. ```APIDOC ## GET /wallets/positions ### Description Returns all current positions for a wallet with full P&L breakdown, including unrealized cash P&L, realized P&L, percent P&L, average entry price, current value, and initial value. ### Method GET ### Endpoint /wallets/positions ### Parameters #### Query Parameters - **wallet_address** (string) - Required - The wallet address, EOA, or username to query. ### Response #### Success Response (200) - **positions** (array) - List of active positions for the wallet. #### Response Example { "positions": [ { "market_id": "0x123...", "unrealized_pnl": 15.50, "realized_pnl": 2.00, "percent_pnl": 0.15, "avg_entry_price": 0.50, "current_value": 115.50, "initial_value": 100.00 } ] } ``` -------------------------------- ### Resolve Wallet Address (REST API) Source: https://docs.polynode.dev/llms.txt Example of how to resolve any Polymarket wallet address, EOA, or username using the PolyNode REST API. Requires an API key. ```bash curl -X GET "https://api.polynode.xyz/v1/wallets/resolve?identifier=vitalik.eth" \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Handle Position Change Event (WebSocket) Source: https://docs.polynode.dev/llms.txt Example code for subscribing to and processing 'positionChange' events from the PolyNode WebSocket stream. These events track Polymarket position transfers between wallets. ```javascript import { WebSocketStream } from '@polynode/sdk'; const stream = new WebSocketStream({ apiKey: 'YOUR_API_KEY' }); stream.on('positionChange', (event) => { console.log(`Position change detected:`); console.log(` From: ${event.fromWallet}`); console.log(` To: ${event.toWallet}`); console.log(` Amount: ${event.amount}`); console.log(` Market: ${event.marketAddress}`); }); stream.connect(); ``` -------------------------------- ### Handle Block Event (WebSocket) Source: https://docs.polynode.dev/llms.txt Example code for subscribing to and processing 'blockEvent' messages from the PolyNode WebSocket stream. These events contain Polymarket-specific statistics for new Polygon blocks. ```javascript import { WebSocketStream } from '@polynode/sdk'; const stream = new WebSocketStream({ apiKey: 'YOUR_API_KEY' }); stream.on('blockEvent', (event) => { console.log(`New block ${event.blockNumber} detected.`); console.log(`Market activity: ${event.marketActivityCount}`); console.log(`Total volume: ${event.totalVolumeUsd}`); }); stream.connect(); ``` -------------------------------- ### Rust SDK Usage Source: https://docs.polynode.dev/llms.txt Illustrates how to use the PolyNode Rust SDK to interact with the API. This SDK offers a robust way to integrate PolyNode data into Rust applications. ```rust use polynode_client::PolyNodeClient; #[tokio::main] async fn main() -> Result<(), Box> { let api_key = "YOUR_API_KEY"; let client = PolyNodeClient::new(api_key); let positions = client.wallets.get_positions("0x123...").await?; println!("{:?}", positions); Ok(()) } ``` -------------------------------- ### TypeScript SDK Usage Source: https://docs.polynode.dev/llms.txt Demonstrates basic usage of the PolyNode TypeScript SDK for interacting with the API. This SDK provides typed methods for REST endpoints. ```typescript import { PolyNodeClient } from '@polynode/client'; const client = new PolyNodeClient({ apiKey: 'YOUR_API_KEY' }); async function getWalletPositions() { try { const positions = await client.wallets.getPositions({ address: '0x123...' }); console.log(positions); } catch (error) { console.error('Error fetching positions:', error); } } getWalletPositions(); ``` -------------------------------- ### WebSocket Events Overview Source: https://docs.polynode.dev/llms.txt This section provides an overview of the different event types available through the Polynode WebSocket API, including their descriptions and links to detailed documentation. ```APIDOC ## WebSocket Events ### Position Merge Event **Description:** Outcome tokens merged back into collateral on Polymarket. ### Position Split Event **Description:** Collateral split into outcome tokens on Polymarket. ### Price Feed Event **Description:** Real-time Chainlink Data Streams price updates for assets like BTC/USD. ### Settlement Event **Description:** Polymarket settlement events, indicating pending (pre-chain) or confirmed (on-chain) settlements. ### Status Update Event **Description:** Notifications when a pending settlement confirms on-chain. ### Trade Event **Description:** Confirmed on-chain trade executions from Polymarket exchange contracts. ``` -------------------------------- ### OpenAPI Specification Source: https://docs.polynode.dev/llms.txt Provides the OpenAPI specification file for the Polynode API, which can be used for generating documentation or client libraries. ```APIDOC ## OpenAPI Specification **Link:** [https://polynode.mintlify.app/openapi.json](https://polynode.mintlify.app/openapi.json) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.