### Setup .env File for Testing (Bash) Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/private-key-migration.md Follow these steps to set up the .env file for local testing. Copy the example file, then edit it to include your private key. ```bash # 1. 创建 .env 文件 cd packages/poly-sdk cp .env.example .env # 2. 编辑 .env,填入你的私钥 # PRIVATE_KEY=0x... # 3. 运行测试(自动读取 .env) npx tsx scripts/ordermanager/quick-test.ts ``` -------------------------------- ### Deposit Flow Example Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/01-overview.md Example demonstrating how to set up the BridgeClient, get an EVM deposit address, and send native USDC for bridging. ```APIDOC ## Deposit Flow Example ### Description This example shows how to use the `BridgeClient` to get an EVM deposit address and send native USDC to it. The bridge will then convert the USDC to USDC.e on the destination chain. ### Setup ```typescript import { providers, Wallet, Contract, utils } from 'ethers'; import { BridgeClient, BRIDGE_TOKENS } from '@catalyst-team/poly-sdk'; const provider = new providers.JsonRpcProvider('https://polygon-rpc.com'); const wallet = new Wallet(PRIVATE_KEY, provider); const bridge = new BridgeClient(); ``` ### Get EVM Deposit Address ```typescript const depositAddress = await bridge.getEvmDepositAddress(wallet.address); console.log(`Deposit to: ${depositAddress}`); ``` ### Send Native USDC ```typescript const nativeUsdc = new Contract( BRIDGE_TOKENS.POLYGON_NATIVE_USDC, ['function transfer(address to, uint256 amount) returns (bool)'] wallet ); const amount = utils.parseUnits('5.0', 6); // 5 USDC const tx = await nativeUsdc.transfer(depositAddress, amount); await tx.wait(); console.log('Deposit sent! Bridge will convert to USDC.e in 1-5 minutes.'); console.log('Bridge fee: ~0.16%'); ``` ``` -------------------------------- ### Install Polymarket SDK Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/01-overview.md Install the SDK using pnpm. ```bash pnpm add @catalyst-team/poly-sdk ``` -------------------------------- ### Install @catalyst-team/poly-sdk Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Install the SDK using pnpm or npm. ```bash pnpm add @catalyst-team/poly-sdk # or npm install @catalyst-team/poly-sdk ``` -------------------------------- ### Run Poly SDK Examples Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Execute various examples using pnpm commands to test different functionalities of the Poly SDK. ```bash pnpm example:basic # Basic usage pnpm example:smart-money # Smart money analysis pnpm example:trading # Trading orders pnpm example:realtime # WebSocket feeds pnpm example:arb-service # Arbitrage service ``` -------------------------------- ### Initializing and Using the DipArb Strategy with PolySDK Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/strategies/dip-arb-strategy.md Provides a comprehensive example of how to initialize the PolymarketSDK, configure the DipArb strategy with specific parameters, and set up event listeners for signals and execution results. It also shows how to start and enable auto-rotation for the strategy. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; const sdk = new PolymarketSDK({ privateKey: process.env.PRIVATE_KEY, }); // 配置参数 sdk.dipArb.updateConfig({ shares: 20, sumTarget: 0.95, dipThreshold: 0.15, // 15% 跌幅 slidingWindowMs: 3000, // 3 秒窗口 ⚠️ 关键 windowMinutes: 2, autoExecute: true, // 启用自动交易 }); // 监听事件 sdk.dipArb.on('signal', (signal) => { if (signal.type === 'leg1') { console.log(`Leg1 Signal: ${signal.dipSide} dropped ${(signal.dropPercent * 100).toFixed(1)}% in 3s`); } }); sdk.dipArb.on('execution', (result) => { console.log(`Executed: ${result.leg} ${result.success ? '✓' : '✗'}`); }); sdk.dipArb.on('roundComplete', (result) => { console.log(`Round profit: $${result.profit?.toFixed(2)}`); }); // 启动 await sdk.dipArb.findAndStart({ coin: 'ETH', preferDuration: '15m', }); // 启用自动轮转 sdk.dipArb.enableAutoRotate({ underlyings: ['ETH', 'BTC', 'SOL', 'XRP'], preferDuration: '15m', settleStrategy: 'sell', }); ``` -------------------------------- ### PM2 Startup Commands Source: https://github.com/cyl19970726/poly-sdk/blob/main/scripts/dip-arb/README.md Commands to start, save, and set up PM2 for automated trading scripts. Ensure PM2 is installed and the ecosystem.config.js file is in the current directory. ```bash pm2 start ecosystem.config.js pm2 save pm2 startup ``` -------------------------------- ### Basic CTFManager Usage Example Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/ctf-manager-implementation-summary.md Illustrates the basic setup and usage of CTFManager, including instantiation with configuration, starting the manager, listening for 'split_detected' and 'merge_detected' events, and executing split, merge, and redeem operations. ```typescript import { CTFManager } from '@catalyst-team/poly-sdk'; const ctfManager = new CTFManager({ privateKey: process.env.PRIVATE_KEY!, conditionId: '0x...', primaryTokenId: '123...', secondaryTokenId: '456...', debug: true, }); await ctfManager.start(); // 监听事件 ctfManager.on('split_detected', (event) => { console.log('Split detected:', event.amount); }); ctfManager.on('merge_detected', (event) => { console.log('Merge detected:', event.amount); }); // 执行操作(自动追踪) await ctfManager.split('100'); await ctfManager.merge('50'); await ctfManager.redeem(); ``` -------------------------------- ### Quick Start: Get Trending Markets and Orderbook Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/01-overview.md Initialize the SDK and fetch trending markets, then retrieve the orderbook for the first market. Requires an active internet connection. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; const sdk = new PolymarketSDK(); // Get trending markets const markets = await sdk.gammaApi.getTrendingMarkets(10); // Get orderbook for a specific market const orderbook = await sdk.clobApi.getProcessedOrderbook(markets[0].conditionId); console.log('Long arb profit:', orderbook.summary.longArbProfit); ``` -------------------------------- ### DipArbService - Quick Start Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Provides a command-line instruction to start auto trading with the DipArbService. ```APIDOC ## DipArbService Quick Start ### Description Starts the Dip Arbitrage auto-trading process using a single command-line instruction. ### Command ```bash PRIVATE_KEY=0x... npx tsx scripts/dip-arb/auto-trade.ts ``` ### Parameters - **PRIVATE_KEY** (string) - Required - The private key for the trading account. ``` -------------------------------- ### Install @catalyst-team/poly-sdk Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Add the SDK to your project using pnpm, npm, or yarn. ```bash pnpm add @catalyst-team/poly-sdk ``` ```bash npm install @catalyst-team/poly-sdk ``` ```bash yarn add @catalyst-team/poly-sdk ``` -------------------------------- ### Initialize and Start OrderManager Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/guides/order-manager.md Instantiate the OrderManager with your private key and desired mode. Ensure to start the manager before creating orders. Listen for various order events to track their lifecycle. ```typescript import { OrderManager } from '@catalyst-team/poly-sdk'; const orderMgr = new OrderManager({ privateKey: '0x...', mode: 'hybrid', }); // More comprehensive events orderMgr.on('order_filled', (event) => { console.log('Filled:', event.fill); console.log('Full order:', event.order); }); orderMgr.on('order_partially_filled', (event) => { console.log('Partial fill:', event.fill); console.log('Remaining:', event.remainingSize); }); orderMgr.on('transaction_confirmed', (event) => { console.log('On-chain confirmed:', event.transactionHash); }); await orderMgr.start(); // Create order (auto-watches!) const result = await orderMgr.createOrder({ tokenId: '0x...', side: 'BUY', price: 0.52, size: 100, }); // No manual watchOrder needed! ``` -------------------------------- ### CTF Arbitrage Example Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/01-overview.md An example demonstrating how to perform arbitrage using the CTF client and CLOB API. It includes steps for fetching market data, checking for arbitrage opportunities, and executing trades. ```typescript import { CTFClient, ClobApiClient, TokenIds } from '@catalyst-team/poly-sdk'; const ctf = new CTFClient({ privateKey, rpcUrl, chainId: 137 }); const clobApi = new ClobApiClient(rateLimiter, cache); // 1. Get market and token IDs const market = await clobApi.getMarket(conditionId); const tokenIds: TokenIds = { yesTokenId: market.tokens.find(t => t.outcome === 'Yes').tokenId, noTokenId: market.tokens.find(t => t.outcome === 'No').tokenId, }; // 2. Get processed orderbook const ob = await clobApi.getProcessedOrderbook(conditionId); // 3. Check for long arbitrage (buy YES + NO, merge for profit) if (ob.summary.longArbProfit > 0.005) { // Buy YES and NO tokens via CLOB // Then merge const balance = await ctf.getPositionBalanceByTokenIds(conditionId, tokenIds); const minBalance = Math.min( parseFloat(balance.yesBalance), parseFloat(balance.noBalance) ); if (minBalance > 0) { const result = await ctf.merge(conditionId, minBalance); console.log(`Merged ${minBalance}, received ${result.usdcReceived} USDC`); } } // 4. Check for short arbitrage (split, sell YES + NO for profit) if (ob.summary.shortArbProfit > 0.005) { // Split USDC into tokens await ctf.split(conditionId, 10); // Sell tokens via CLOB } ``` -------------------------------- ### Execute Trading Orders Source: https://github.com/cyl19970726/poly-sdk/blob/main/examples/README.md Demonstrates placing and managing various types of orders using the TradingService. This example requires a private key and is authenticated. ```bash POLYMARKET_PRIVATE_KEY=0x... npx tsx examples/08-trading-orders.ts ``` -------------------------------- ### Create Order with Auto-Watch Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/guides/order-manager.md Demonstrates creating an order and automatically starting its lifecycle monitoring. No manual `watchOrder()` call is needed after creation. ```typescript const result = await orderMgr.createOrder({ tokenId: '0x...', side: 'BUY', price: 0.52, size: 100, }); // Order is automatically watched! Events will be emitted. ``` -------------------------------- ### PolymarketSDK Initialization Methods Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Illustrates different ways to initialize the PolymarketSDK, including the recommended static factory method, using start(), and manual step-by-step initialization for full control. Also lists available services and convenience methods. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; // ===== Method 1: Static Factory (Recommended) ===== // One line: new + initialize + connect + waitForConnection const sdk = await PolymarketSDK.create({ privateKey: '0x...', // Optional: for trading chainId: 137, // Optional: Polygon mainnet (default) }); // ===== Method 2: Using start() ===== // const sdk = new PolymarketSDK({ privateKey: '0x...' }); // await sdk.start(); // initialize + connect + waitForConnection // ===== Method 3: Manual Step-by-Step (Full Control) ===== // const sdk = new PolymarketSDK({ privateKey: '0x...' }); // await sdk.initialize(); // Initialize trading service // sdk.connect(); // Connect WebSocket // await sdk.waitForConnection(); // Wait for connection // Access services sdk.tradingService // Trading operations sdk.markets // Market data sdk.wallets // Wallet analysis sdk.realtime // WebSocket real-time data sdk.smartMoney // Smart money tracking & copy trading sdk.dipArb // Dip arbitrage for 15m crypto markets sdk.dataApi // Direct Data API access sdk.gammaApi // Direct Gamma API access sdk.subgraph // On-chain data via Goldsky // Convenience methods await sdk.getMarket(identifier); // Get unified market await sdk.getOrderbook(conditionId); // Get processed orderbook await sdk.detectArbitrage(conditionId); // Detect arb opportunity // Clean up sdk.stop(); // Disconnect all services ``` -------------------------------- ### SDK: Get All Activity with Pagination Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/03-position-activity.md Fetches all user activities, automatically handling pagination. Useful for retrieving a complete history of actions starting from a specific timestamp. ```typescript // 获取所有活动 (自动分页) const allActivity = await sdk.dataApi.getAllActivity(address, { start: dayAgo, }); ``` -------------------------------- ### Environment Configuration Template (.env.example) Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/private-key-migration.md Use a template file for environment configuration that can be committed to Git. This file serves as a guide for setting up the actual .env file. ```bash # Polymarket SDK Test Configuration # Private key for testing (DO NOT commit real private key) PRIVATE_KEY=0xa1c847feeb03315d72a09481edae8e34d3892ae281b6b2291911380490a23459 # Optional: Market configuration for tests # MARKET_CONDITION_ID=0x... # PRIMARY_TOKEN_ID=123... # SECONDARY_TOKEN_ID=456... ``` -------------------------------- ### Configure Private Key with .env Source: https://github.com/cyl19970726/poly-sdk/blob/main/scripts/README.md Create a .env file in the packages/poly-sdk/ directory and add your private key. This method is recommended for security. ```bash cd packages/poly-sdk cp .env.example .env # Edit .env file and add your private key ``` ```dotenv PRIVATE_KEY=0x...your-private-key... ``` -------------------------------- ### SDK: Get Activity within Time Range Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/03-position-activity.md Retrieves user activities within the last 24 hours. Calculates the start timestamp by subtracting 86400 seconds from the current time. ```typescript // 时间范围查询 (过去 24 小时) const dayAgo = Math.floor(Date.now() / 1000) - 86400; const recent = await sdk.dataApi.getActivity(address, { start: dayAgo, limit: 100, }); ``` -------------------------------- ### Initialize PolymarketSDK Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/01-overview.md Instantiate the main SDK class. Configuration options include chain ID, private key for trading, and API credentials. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; const sdk = new PolymarketSDK(config?: PolymarketSDKConfig); ``` -------------------------------- ### Test 'started' Event Emission Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/test/e2e-test-plan.md Verifies that the 'started' event is emitted when the service successfully starts monitoring a market. It checks if the emitted market data matches the provided test market configuration. ```typescript it('should emit started event on start', async () => { service = new ArbitrageService({ enableLogging: false }); const startedPromise = new Promise((resolve) => { service.on('started', resolve); }); await service.start(testMarket); const market = await startedPromise; expect(market.conditionId).toBe(testMarket.conditionId); }, 10000); ``` -------------------------------- ### PolymarketSDK Initialization and Usage Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Demonstrates how to initialize and use the PolymarketSDK for both read-only access and trading functionalities. It covers creating an instance, accessing different services, and managing the SDK lifecycle. ```APIDOC ## PolymarketSDK ### Description The central class that instantiates all services. Use the static `create()` factory for one-line initialization with WebSocket connection, or the constructor for read-only usage. ### Usage Examples **Read-only (no authentication required):** ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; const sdk = new PolymarketSDK(); const market = await sdk.getMarket('will-btc-reach-100k-by-end-of-2024'); const yesToken = market.tokens.find(t => t.outcome === 'Yes'); console.log(`Market: ${market.question}`); console.log(`YES price: ${yesToken?.price}, Volume: $${market.volume}`); ``` **With trading (factory: initialize + connect WebSocket in one call):** ```typescript const sdk2 = await PolymarketSDK.create({ privateKey: process.env.POLYMARKET_PRIVATE_KEY!, chainId: 137, // Polygon mainnet (default) }); // Access all services console.log(sdk2.tradingService); // Order placement and management console.log(sdk2.markets); // Market data and K-lines console.log(sdk2.wallets); // Wallet analysis and leaderboard console.log(sdk2.realtime); // WebSocket real-time data console.log(sdk2.smartMoney); // Smart money tracking and copy trading console.log(sdk2.dipArb); // Dip arbitrage for 15m crypto markets console.log(sdk2.dataApi); // Raw Data API access console.log(sdk2.gammaApi); // Raw Gamma API access console.log(sdk2.subgraph); // On-chain Goldsky subgraph // Cleanup sdk2.stop(); ``` **Manual lifecycle (full control):** ```typescript const sdk3 = new PolymarketSDK({ privateKey: '0x...' }); await sdk3.initialize(); // Derive CLOB API credentials sdk3.connect(); // Connect WebSocket await sdk3.waitForConnection(10000); // ... use sdk3 ... sdk3.stop(); ``` **Detect arbitrage via top-level convenience method:** ```typescript const arb = await sdk.detectArbitrage('0xconditionId...'); if (arb) { console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit * 100).toFixed(2)}% profit`); console.log(arb.action); // e.g. "Buy YES @ 0.4900 + Buy NO @ 0.4900, merge for 1 USDC" } ``` **Cache management:** ```typescript sdk.clearCache(); sdk.invalidateMarketCache('0xconditionId...'); ``` ``` -------------------------------- ### ArbitrageService - Find and Start Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Finds the best arbitrage opportunity in the market and starts monitoring it. ```APIDOC ## findAndStart ### Description Identifies the best arbitrage opportunity across all markets and begins actively monitoring it for execution. ### Method `arbService.findAndStart(minProfitPercent?: number)` ### Parameters - **minProfitPercent** (number) - Optional - Minimum profit percentage to consider when finding the best opportunity. ### Request Example ```typescript const best = await arbService.findAndStart(0.005); console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`); ``` ### Response - Returns an object containing the best market and its profit percentage. ``` -------------------------------- ### RealtimeServiceV2 Initialization and Connection Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Demonstrates how to initialize the RealtimeServiceV2 client with custom options and establish a WebSocket connection. ```APIDOC ## RealtimeServiceV2 Initialization and Connection ### Description Initializes the RealtimeServiceV2 client with optional configuration for auto-reconnect, ping interval, and debug mode, then establishes a WebSocket connection. ### Method ```typescript new RealtimeServiceV2({ autoReconnect?: boolean, pingInterval?: number, debug?: boolean }) connect() ``` ### Parameters #### Constructor Options - **autoReconnect** (boolean) - Optional - If true, the client will attempt to reconnect automatically upon disconnection. - **pingInterval** (number) - Optional - The interval in milliseconds to send ping frames to keep the connection alive. - **debug** (boolean) - Optional - If true, enables debug logging. #### Method Parameters `connect()`: No parameters. ### Request Example ```typescript import { RealtimeServiceV2 } from '@catalyst-team/poly-sdk'; const realtime = new RealtimeServiceV2({ autoReconnect: true, pingInterval: 5000, debug: false, }); realtime.connect(); ``` ``` -------------------------------- ### Initialize PolymarketSDK (Manual Lifecycle) Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Manually initialize, connect, and manage the SDK lifecycle for full control. Requires a private key. ```typescript // Manual lifecycle (full control) const sdk3 = new PolymarketSDK({ privateKey: '0x...' }); await sdk3.initialize(); // Derive CLOB API credentials sdk3.connect(); // Connect WebSocket await sdk3.waitForConnection(10000); // ... use sdk3 ... sdk3.stop(); ``` -------------------------------- ### Start Monitoring Markets Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Find and start monitoring a specific market for arbitrage opportunities using the DipArbService. ```APIDOC ## sdk.dipArb.findAndStart ### Description Finds a suitable market and starts monitoring it for Dip Arbitrage opportunities. ### Method `await sdk.dipArb.findAndStart(options: FindMarketOptions): Promise` ### Parameters #### Request Body - **coin** (string) - Required - The cryptocurrency to monitor (e.g., 'BTC', 'ETH'). - **preferDuration** (string) - Required - The preferred market duration (e.g., '15m', '5m'). ### Response #### Success Response (200) - **market** (object) - The market object that is being monitored. ``` -------------------------------- ### Run Quick Test for Verification (Bash) Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/private-key-migration.md Execute a quick test to verify that the private key configuration is correct. This command will automatically read the .env file. If the private key is not configured, a clear error message will be displayed. ```bash # 确保 .env 文件存在且包含 PRIVATE_KEY npx tsx scripts/ordermanager/quick-test.ts ``` -------------------------------- ### Start DipArbService Monitoring Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Initiate monitoring for a specific cryptocurrency and market duration. This function finds and starts tracking the relevant market. ```typescript // ── Start monitoring ─────────────────────────────────────────────────────────── const market = await sdk.dipArb.findAndStart({ coin: 'BTC', preferDuration: '15m', }); console.log(`Monitoring: ${market.conditionId}`); ``` -------------------------------- ### Initialize PolymarketSDK with Trading (Factory) Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Use the static `create()` factory to initialize the SDK with trading capabilities, including WebSocket connection. Requires a private key and chain ID. ```typescript // With trading (factory: initialize + connect WebSocket in one call) const sdk2 = await PolymarketSDK.create({ privateKey: process.env.POLYMARKET_PRIVATE_KEY!, chainId: 137, // Polygon mainnet (default) }); // Access all services sdk2.tradingService // Order placement and management sdk2.markets // Market data and K-lines sdk2.wallets // Wallet analysis and leaderboard sdk2.realtime // WebSocket real-time data sdk2.smartMoney // Smart money tracking and copy trading sdk2.dipArb // Dip arbitrage for 15m crypto markets sdk2.dataApi // Raw Data API access sdk2.gammaApi // Raw Gamma API access sdk2.subgraph // On-chain Goldsky subgraph // Cleanup sdk2.stop(); ``` -------------------------------- ### Get Test Market Data Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/test/e2e-test-plan.md Fetches active market data and token IDs from Polymarket APIs. Use this to get necessary IDs for testing. ```typescript import { describe } from 'vitest'; /** * Get a liquid test market from Polymarket */ export async function getTestMarket(): Promise<{ conditionId: string; yesTokenId: string; noTokenId: string; question: string; }> { const response = await fetch( 'https://gamma-api.polymarket.com/markets?active=true&limit=1&order=volume24hr&ascending=false' ); const markets = await response.json(); if (markets.length === 0) { throw new Error('No active markets found'); } const conditionId = markets[0].conditionId; const question = markets[0].question; const clobResponse = await fetch( `https://clob.polymarket.com/markets/${conditionId}` ); const market = await clobResponse.json(); return { conditionId, yesTokenId: market.tokens.find((t: any) => t.outcome === 'Yes').token_id, noTokenId: market.tokens.find((t: any) => t.outcome === 'No').token_id, question, }; } ``` -------------------------------- ### PolymarketSDK - Initialization and Service Access Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Demonstrates different ways to initialize the PolymarketSDK and access its various services. ```APIDOC ## PolymarketSDK ### Description The main SDK class that integrates all services. ### Initialization Methods #### Method 1: Static Factory (Recommended) ```typescript const sdk = await PolymarketSDK.create({ privateKey: '0x...', // Optional: for trading chainId: 137, // Optional: Polygon mainnet (default) }); ``` #### Method 2: Using start() ```typescript const sdk = new PolymarketSDK({ privateKey: '0x...' }); await sdk.start(); // initialize + connect + waitForConnection ``` #### Method 3: Manual Step-by-Step (Full Control) ```typescript const sdk = new PolymarketSDK({ privateKey: '0x...' }); await sdk.initialize(); // Initialize trading service sdk.connect(); // Connect WebSocket await sdk.waitForConnection(); // Wait for connection ``` ### Accessing Services ```typescript // Access services sdk.tradingService // Trading operations sdk.markets // Market data sdk.wallets // Wallet analysis sdk.realtime // WebSocket real-time data sdk.smartMoney // Smart money tracking & copy trading sdk.dipArb // Dip arbitrage for 15m crypto markets sdk.dataApi // Direct Data API access sdk.gammaApi // Direct Gamma API access sdk.subgraph // On-chain data via Goldsky ``` ### Convenience Methods ```typescript await sdk.getMarket(identifier); // Get unified market await sdk.getOrderbook(conditionId); // Get processed orderbook await sdk.detectArbitrage(conditionId); // Detect arb opportunity ``` ### Cleanup ```typescript // Clean up sdk.stop(); // Disconnect all services ``` ``` -------------------------------- ### Find and Start Monitoring a Market Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Automatically find the best market to monitor based on a profit threshold and start the monitoring process. Logs the name of the market being monitored and its initial profit percentage. ```typescript // 2. Start monitoring the best market (auto-selects) const best = await arbService.findAndStart(0.005); console.log(`Monitoring: ${best.market.name} — initial profit ${best.profitPercent.toFixed(2)}%`); ``` -------------------------------- ### Basic Usage (Read-Only) with PolymarketSDK Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Demonstrates how to initialize the SDK without authentication for read operations like fetching market data and orderbooks. Also shows how to detect arbitrage opportunities. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; // No authentication needed for read operations const sdk = new PolymarketSDK(); // Get market by slug or condition ID const market = await sdk.getMarket('will-trump-win-2024'); console.log(`${market.question}`); console.log(`YES: ${market.tokens.find(t => t.outcome === 'Yes')?.price}`); console.log(`NO: ${market.tokens.find(t => t.outcome === 'No')?.price}`); // Get processed orderbook with analytics const orderbook = await sdk.getOrderbook(market.conditionId); console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`); console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`); // Detect arbitrage opportunities const arb = await sdk.detectArbitrage(market.conditionId); if (arb) { console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit * 100).toFixed(2)}% profit`); console.log(arb.action); } ``` -------------------------------- ### Get Statistics Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieve performance statistics for the DipArbService. ```APIDOC ## sdk.dipArb.getStats ### Description Retrieves the performance statistics of the Dip Arbitrage strategy. ### Method `sdk.dipArb.getStats(): DipArbStats` ### Response #### Success Response (200) - **signalsDetected** (number) - Total number of arbitrage signals detected. - **leg1Filled** (number) - Number of first legs successfully filled. - **leg2Filled** (number) - Number of second legs successfully filled. - **roundsCompleted** (number) - Number of completed arbitrage rounds. - **totalProfit** (number) - Total profit generated by the strategy. ``` -------------------------------- ### Initialize PolymarketSDK Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Creates an instance of the PolymarketSDK. Requires a private key for authenticated operations. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; const sdk = await PolymarketSDK.create({ privateKey: '0x...' }); ``` -------------------------------- ### Get Address Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves the public address of the authenticated user. ```APIDOC ## getAddress ### Description Retrieves the public address of the authenticated user. ### Method `trading.getAddress()` ### Response #### Success Response (200) - **address** (string) - The user's public address. ### Request Example ```typescript console.log('Address:', trading.getAddress()); ``` ``` -------------------------------- ### Initialize and Use SmartMoneyService Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Initialize the Polymarket SDK with a private key to access smart money features. This includes fetching smart money lists, checking if an address is smart money, and subscribing to smart money trades. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; // One line to get started (recommended) const sdk = await PolymarketSDK.create({ privateKey: '0x...' }); // SDK is initialized and WebSocket connected // Get smart money wallets const wallets = await sdk.smartMoney.getSmartMoneyList(50); // Check if address is smart money const isSmartMoney = await sdk.smartMoney.isSmartMoney('0x...'); // Subscribe to smart money trades const sub = sdk.smartMoney.subscribeSmartMoneyTrades( (trade) => { console.log(`${trade.traderName} ${trade.side} ${trade.outcome} @ $${trade.price}`); }, { filterAddresses: ['0x...'], minSize: 10 } ); ``` -------------------------------- ### Get Market Reward Config Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves the reward configuration for a specific market. ```APIDOC ## getMarketRewardConfig ### Description Retrieves the reward configuration for a specific market. ### Method `trading.getMarketRewardConfig(conditionId)` ### Parameters #### Path Parameters - **conditionId** (string) - Required - The market condition ID for which to retrieve the reward configuration. ### Response #### Success Response (200) - Returns a reward configuration object, including `isActive` and `maxSpread`. ### Request Example ```typescript const rewardConfig = await trading.getMarketRewardConfig('0xconditionId...'); ``` ``` -------------------------------- ### Get Current Rewards Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves information about the user's current rewards. ```APIDOC ## getCurrentRewards ### Description Retrieves information about the user's current rewards. ### Method `trading.getCurrentRewards()` ### Response #### Success Response (200) - Returns an object containing current reward information. ### Request Example ```typescript const rewards = await trading.getCurrentRewards(); ``` ``` -------------------------------- ### Get Order Progress Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves the fill progress percentage for a specific order. ```APIDOC ## getOrderProgress ### Description Retrieves the fill progress percentage for a specific order. ### Method `trading.getOrderProgress(orderId)` ### Parameters #### Path Parameters - **orderId** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **progress** (number) - The fill progress percentage (0-100). ### Request Example ```typescript const progress = await trading.getOrderProgress('0xorderId...'); console.log(`${progress?.toFixed(1)}% filled`); ``` ``` -------------------------------- ### Analyze Trader Activity with Polymarket SDK Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/api/03-position-activity.md This example demonstrates how to use the Polymarket SDK to retrieve and display a trader's financial activity. It covers fetching account overview, sorting and displaying current positions by PNL, listing closed positions by realized PNL, showing recent activity within the last 24 hours, and identifying redeemable positions. Ensure the SDK is initialized before use. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; async function analyzeTrader(address: string) { const sdk = new PolymarketSDK(); // 1. 账户总览 const { value } = await sdk.dataApi.getAccountValue(address); console.log(` === 账户总览 ===`); console.log(`总价值: $${value.toFixed(2)}`); // 2. 当前持仓 (按盈亏排序) const positions = await sdk.dataApi.getPositions(address, { sortBy: 'CASHPNL', sortDirection: 'DESC', limit: 5, }); console.log(` === Top 5 持仓 (按盈亏) ===`); positions.forEach((p, i) => { console.log(`${i + 1}. ${p.title} (${p.outcome})`); console.log(` 持仓: ${p.size.toFixed(2)} @ $${p.avgPrice.toFixed(3)}`); console.log(` 盈亏: $${p.cashPnl?.toFixed(2)} (${(p.percentPnl || 0).toFixed(1)}%)`); }); // 3. 已平仓位 (按盈亏排序) const closed = await sdk.dataApi.getClosedPositions(address, { sortBy: 'REALIZEDPNL', sortDirection: 'DESC', limit: 5, }); console.log(` === Top 5 已平仓位 ===`); closed.forEach((p, i) => { console.log(`${i + 1}. ${p.title} (${p.outcome})`); console.log(` 已实现盈亏: $${p.realizedPnl.toFixed(2)}`); }); // 4. 最近活动 const dayAgo = Math.floor(Date.now() / 1000) - 86400; const activity = await sdk.dataApi.getActivity(address, { start: dayAgo, limit: 10, }); console.log(` === 过去 24h 活动 ===`); activity.forEach((a) => { const time = new Date(a.timestamp).toLocaleTimeString(); console.log(`[${time}] ${a.type} ${a.side} ${a.size.toFixed(2)} @ $${a.price.toFixed(3)}`); console.log(` ${a.title} (${a.outcome})`); }); // 5. 可赎回持仓 const redeemable = await sdk.dataApi.getPositions(address, { redeemable: true, }); if (redeemable.length > 0) { console.log(` === 可赎回持仓 (${redeemable.length}) ===`); redeemable.forEach((p) => { console.log(`- ${p.title}: ${p.size.toFixed(2)} tokens`); }); } } analyzeTrader('0x...'); ``` -------------------------------- ### Get Order Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves details for a specific order using its order ID. ```APIDOC ## getOrder ### Description Retrieves details for a specific order using its order ID. ### Method `trading.getOrder(orderId)` ### Parameters #### Path Parameters - **orderId** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - Returns an order object with details such as `status`, `filledSize`, `originalSize`, etc. - **status** (string) - The current status of the order ('pending', 'open', 'partially_filled', 'filled', 'cancelled', 'expired', 'rejected'). - **filledSize** (number) - The number of shares already filled. - **originalSize** (number) - The original number of shares requested for the order. ### Request Example ```typescript const order = await trading.getOrder('0xorderId...'); console.log(`Filled: ${order?.filledSize} / ${order?.originalSize}`); ``` ``` -------------------------------- ### Test Environment Configuration Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/arb/test-results.md Details the environment setup for testing, including platform, Node.js version, network, and RPC URL. Also lists initial wallet balances. ```text Platform: macOS Darwin 24.1.0 Node.js: v22.x (with experimental ESM support) Network: Polygon Mainnet RPC URL: https://polygon-rpc.com Test Wallet Balances (Initial): USDC.e Balance: $1.99 (insufficient for $5 test amount) Native USDC: $4.26 MATIC (gas): 94.69 ``` -------------------------------- ### DataApiClient - Market Holders Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Get a list of wallets holding positions in a specific market. ```APIDOC ## DataApiClient - Market Holders ### Description Get a list of wallets holding positions in a specific market. ### Method `getHolders(params: { conditionId: string, limit?: number })` ### Parameters - **conditionId** (string) - Required - The condition ID of the market. - **limit** (number) - Optional - The maximum number of holders to return. ### Response Example ```json [ { "proxyWallet": "string", "size": "string", "price": "string", "value": "string", "outcome": "string" } ] ``` ``` -------------------------------- ### Initialize OnchainService Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Instantiate the OnchainService with necessary credentials and network configuration. Ensure POLY_PRIVKEY is set in your environment variables. The rpcUrl is optional and defaults to a public RPC. ```typescript import { OnchainService } from '@catalyst-team/poly-sdk'; const onchain = new OnchainService({ privateKey: process.env.POLY_PRIVKEY!, rpcUrl: 'https://polygon-rpc.com', // optional, defaults to public RPC gasPriceMultiplier: 1.2, }); ``` -------------------------------- ### Get Rewards Summary Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves a summary of total earnings for a specified date range. ```APIDOC ## getRewardsSummary ### Description Retrieves a summary of total earnings for a specified date range. ### Method `trading.getRewardsSummary(startDate, endDate)` ### Parameters #### Path Parameters - **startDate** (string) - Required - The start date of the period (YYYY-MM-DD). - **endDate** (string) - Required - The end date of the period (YYYY-MM-DD). ### Response #### Success Response (200) - **totalEarnings** (number) - The total earnings within the specified period. ### Request Example ```typescript const summary = await trading.getRewardsSummary('2024-12-01', '2024-12-31'); ``` ``` -------------------------------- ### Authenticated Trading with PolymarketSDK Source: https://github.com/cyl19970726/poly-sdk/blob/main/README.md Shows how to initialize the SDK with private key authentication for trading operations. Includes placing limit orders, retrieving open orders, and cleaning up the SDK instance. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; // Recommended: Use static factory method (one line to get started) const sdk = await PolymarketSDK.create({ privateKey: process.env.POLYMARKET_PRIVATE_KEY!, }); // Ready to trade - SDK is initialized and WebSocket connected // Place a limit order const order = await sdk.tradingService.createLimitOrder({ tokenId: yesTokenId, side: 'BUY', price: 0.45, size: 10, orderType: 'GTC', }); console.log(`Order placed: ${order.id}`); // Get open orders const openOrders = await sdk.tradingService.getOpenOrders(); console.log(`Open orders: ${openOrders.length}`); // Clean up when done sdk.stop(); ``` -------------------------------- ### Initialize PolymarketSDK (Read-only) Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Instantiate the SDK for read-only operations without authentication. Retrieves market data and token information. ```typescript import { PolymarketSDK } from '@catalyst-team/poly-sdk'; // Read-only (no authentication required) const sdk = new PolymarketSDK(); const market = await sdk.getMarket('will-btc-reach-100k-by-end-of-2024'); const yesToken = market.tokens.find(t => t.outcome === 'Yes'); console.log(`Market: ${market.question}`); console.log(`YES price: ${yesToken?.price}, Volume: $${market.volume}`); ``` -------------------------------- ### Get Trades Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves a list of trades executed for a specific market condition ID. ```APIDOC ## getTrades ### Description Retrieves a list of trades executed for a specific market condition ID. ### Method `trading.getTrades(conditionId)` ### Parameters #### Path Parameters - **conditionId** (string) - Required - The market condition ID to filter trades. ### Response #### Success Response (200) - Returns an array of trade objects, each containing `id`, `tokenId`, `side`, `price`, `size`, `fee`, and `timestamp`. ### Request Example ```typescript const trades = await trading.getTrades('0xconditionId...'); ``` ``` -------------------------------- ### Migration Example: Before (FillDetector) Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/guides/order-manager.md Illustrates the old approach using the deprecated FillDetector for monitoring fills and manually watching orders after creation via TradingService. This serves as a reference for migrating to OrderManager. ```typescript import { FillDetector } from '@catalyst-team/earning-engine/infrastructure'; const detector = new FillDetector({ privateKey: '0x...', market: { conditionId: '0x...', yesTokenId: '0x...', noTokenId: '0x...', }, mode: 'hybrid', }); detector.on('fill', (fill) => { console.log('Filled:', fill); }); await detector.start(); // Create order via TradingService const result = await tradingService.createLimitOrder({ ... }); // Manually watch order if (result.orderId) { detector.watchOrder(result.orderId, tokenId, 'BUY', price, size); } ``` -------------------------------- ### Get Watched Orders Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/guides/order-manager.md Retrieves a list of all orders currently being watched by the Order Manager. ```APIDOC ## Get Watched Orders ### Description Retrieves a list of all orders that the OrderManager is currently monitoring. This allows you to check the status and details of active orders. ### Method `orderMgr.getWatchedOrders()` ### Returns An array of `Order` objects, each representing an order being watched. ### Example Usage ```typescript const watchedOrders = orderMgr.getWatchedOrders(); console.log(`Watching ${watchedOrders.length} orders`); for (const order of watchedOrders) { console.log(`- ${order.id}: ${order.status}`); } ``` ``` -------------------------------- ### Cancel an Order Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/guides/order-manager.md Provides an example of how to cancel an existing order using its ID and handling the result. ```typescript const result = await orderMgr.cancelOrder(orderId); if (result.success) { console.log('Order cancelled'); } else { console.error('Cancellation failed:', result.errorMsg); } ``` -------------------------------- ### Configure and Run Rebalancer Source: https://github.com/cyl19970726/poly-sdk/blob/main/docs/arb/test-plan.md Initializes the ArbitrageService with rebalancer enabled and specific ratio targets. The rebalancer automatically adjusts portfolio to meet target USDC ratios. Requires private key and rebalancer configuration. ```typescript const service = new ArbitrageService({ privateKey: process.env.PRIVATE_KEY, enableRebalancer: true, minUsdcRatio: 0.2, maxUsdcRatio: 0.8, targetUsdcRatio: 0.5, }); // Create imbalanced state (e.g., split all USDC) // Then let rebalancer run // Verify: // - Rebalance event is emitted // - Balance moves toward target ratio ``` -------------------------------- ### Get Balances Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves the balances of all supported tokens, including USDC.e, MATIC, and native USDC. ```APIDOC ## getBalances ### Description Retrieves the balances of all supported tokens, including USDC.e, MATIC, and native USDC. ### Method `onchain.getBalances()` ### Parameters None ### Request Example ```typescript const balancesAll = await onchain.getBalances(); // { usdcE: '42.50', matic: '15.3', usdc: '0.0' } ``` ### Response #### Success Response (200) - **usdcE** (string) - Balance of USDC.e. - **matic** (string) - Balance of MATIC. - **usdc** (string) - Balance of native USDC. #### Response Example ```json { "usdcE": "42.50", "matic": "15.3", "usdc": "0.0" } ``` ``` -------------------------------- ### Get Balance Allowance Source: https://context7.com/cyl19970726/poly-sdk/llms.txt Retrieves the user's balance and allowance for a specified collateral type. ```APIDOC ## getBalanceAllowance ### Description Retrieves the user's balance and allowance for a specified collateral type. ### Method `trading.getBalanceAllowance(collateralType)` ### Parameters #### Path Parameters - **collateralType** (string) - Required - The type of collateral (e.g., 'COLLATERAL'). ### Response #### Success Response (200) - **balance** (number) - The user's balance of the collateral. - **allowance** (number) - The user's allowance for the collateral. ### Request Example ```typescript const { balance, allowance } = await trading.getBalanceAllowance('COLLATERAL'); ``` ```