### Quick Start Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md A basic example demonstrating how to initialize the SDK, fetch markets, and retrieve positions. API key is loaded from environment variables. ```python import asyncio import os from limitless_sdk.api import HttpClient from limitless_sdk.markets import MarketFetcher from limitless_sdk.portfolio import PortfolioFetcher async def main(): # Setup - API key automatically loaded from LIMITLESS_API_KEY env variable http_client = HttpClient(base_url="https://api.limitless.exchange") try: # Get markets market_fetcher = MarketFetcher(http_client) markets = await market_fetcher.get_active_markets() print(f"Found {markets.total_markets_count} markets") # Fetch specific market (caches venue data for orders) market = await market_fetcher.get_market("bitcoin-2024") print(f"Market: {market.title}") # Get positions (requires authentication) portfolio_fetcher = PortfolioFetcher(http_client) positions = await portfolio_fetcher.get_positions() print(f"CLOB positions: {len(positions['clob'])}") finally: await http_client.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Complete Limitless SDK Setup Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the setup of all major Limitless SDK clients, including HTTP client, order client, portfolio fetcher, and WebSocket client, along with logger and account configuration. ```python import os from eth_account import Account from limitless_sdk.api import HttpClient from limitless_sdk.markets import MarketFetcher from limitless_sdk.orders import OrderClient from limitless_sdk.portfolio import PortfolioFetcher from limitless_sdk.websocket import WebSocketClient, WebSocketConfig from limitless_sdk import ConsoleLogger, LogLevel # Setup logger logger = ConsoleLogger(level=LogLevel.DEBUG) # Setup HTTP client http_client = HttpClient( base_url=os.getenv("LIMITLESS_API_URL", "https://api.limitless.exchange"), api_key=os.getenv("LIMITLESS_API_KEY"), timeout=60, logger=logger ) # Setup account account = Account.from_key(os.getenv("PRIVATE_KEY")) # Setup market fetcher (for venue caching) market_fetcher = MarketFetcher(http_client, logger=logger) # Setup order client order_client = OrderClient( http_client=http_client, wallet=account, market_fetcher=market_fetcher, # Share for performance logger=logger ) # Setup portfolio fetcher portfolio_fetcher = PortfolioFetcher(http_client, logger=logger) # Setup WebSocket client ws_config = WebSocketConfig( api_key=os.getenv("LIMITLESS_API_KEY"), auto_reconnect=True, reconnect_delay=1.0 ) ws_client = WebSocketClient(config=ws_config, logger=logger) # Use in async function async def main(): async with http_client: # Get markets markets = await market_fetcher.get_active_markets() # Create order order = await order_client.create_order( token_id="123", side=Side.BUY, order_type=OrderType.GTC, market_slug="bitcoin-2024", price=0.65, size=100.0 ) # Get portfolio positions = await portfolio_fetcher.get_positions() # WebSocket await ws_client.connect() await ws_client.subscribe("subscribe_positions") import asyncio asyncio.run(main()) ``` -------------------------------- ### Token Approval Setup Guide Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Provides a guide for setting up token approvals, essential for interacting with smart contracts. ```Python Complete token approval setup guide ``` -------------------------------- ### Token Approval Setup Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example demonstrating how to set up token approvals. ```python 00_setup_approvals.py ``` -------------------------------- ### Install Limitless SDK with Development Dependencies Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Clone the repository and install the SDK with development dependencies using pip. ```bash git clone https://github.com/limitless-labs-group/limitless-exchange-ts-sdk.git cd limitless-sdk pip install -e ".[dev]" ``` -------------------------------- ### Install Limitless SDK and Set Environment Variables Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/examples/README.md Install the SDK using pip and set necessary environment variables for API key, private key, market slug, and partner API tokens. ```bash pip install limitless-sdk export LIMITLESS_API_KEY="sk_live_..." # For authenticated endpoints export PRIVATE_KEY="0x..." # For order signing (EIP-712) export MARKET_SLUG="your-market-slug" # For order examples export LIMITLESS_IDENTITY_TOKEN="..." # For partner api-token v3 examples export LIMITLESS_API_TOKEN_ID="..." # For partner HMAC examples export LIMITLESS_API_TOKEN_SECRET="..." # For partner HMAC examples ``` -------------------------------- ### Install Limitless SDK Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Install the Limitless SDK using pip. Ensure you have Python 3.8 or higher. ```bash pip install limitless-sdk ``` -------------------------------- ### Minimal Example: Fetch Market Data Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md A minimal example demonstrating how to initialize the HTTP client and market fetcher to retrieve active markets and specific market details. The HTTP client should be managed within an async context manager. ```python import asyncio from limitless_sdk.api import HttpClient from limitless_sdk.markets import MarketFetcher async def main(): http_client = HttpClient() market_fetcher = MarketFetcher(http_client) async with http_client: # Get active markets response = await market_fetcher.get_active_markets() print(f"Found {len(response.data)} markets") # Get specific market market = await market_fetcher.get_market("bitcoin-2024") print(f"Market: {market.title}") asyncio.run(main()) ``` -------------------------------- ### Run Authentication Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/examples/README.md Execute the Python script for API key authentication and portfolio data access. ```bash python examples/01_authentication.py ``` -------------------------------- ### Web3 Integration Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Demonstrates how to integrate with Web3 functionalities, such as token approvals and contract interactions. ```Python Web3 integration examples ``` -------------------------------- ### Basic OrderClient Setup Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/configuration.md Initializes OrderClient with essential HTTP client and wallet account. This is the minimum configuration required. ```python from eth_account import Account from limitless_sdk.api import HttpClient from limitless_sdk.orders import OrderClient account = Account.from_key("0x...") http_client = HttpClient(api_key="your-api-key") order_client = OrderClient( http_client=http_client, wallet=account ) ``` -------------------------------- ### Manual Token Approval Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Manually approves USDC and Conditional Tokens (CTF) for exchange contracts. This is a one-time setup per wallet and is crucial before placing orders. ```python from web3 import Web3 from eth_account import Account from limitless_sdk.markets import MarketFetcher from limitless_sdk.utils.constants import get_contract_address # 1. Fetch market to get venue addresses market = await market_fetcher.get_market('market-slug') # 2. Initialize Web3 and wallet w3 = Web3(Web3.HTTPProvider('https://mainnet.base.org')) account = Account.from_key(private_key) # 3. Get contract addresses usdc_address = get_contract_address("USDC", 8453) ctf_address = get_contract_address("CTF", 8453) # 4. Create contract instances usdc = w3.eth.contract(address=usdc_address, abi=ERC20_APPROVE_ABI) ctf = w3.eth.contract(address=ctf_address, abi=ERC1155_APPROVAL_ABI) # 5. Approve USDC for BUY orders max_uint256 = 2**256 - 1 tx = usdc.functions.approve(venue.exchange, max_uint256).build_transaction({...}) signed_tx = account.sign_transaction(tx) w3.eth.send_raw_transaction(signed_tx.raw_transaction) # 6. Approve CT for SELL orders tx = ctf.functions.setApprovalForAll(venue.exchange, True).build_transaction({...}) signed_tx = account.sign_transaction(tx) w3.eth.send_raw_transaction(signed_tx.raw_transaction) # 7. For NegRisk SELL orders, also approve adapter if market.neg_risk_request_id: tx = ctf.functions.setApprovalForAll(venue.adapter, True).build_transaction({...}) signed_tx = account.sign_transaction(tx) w3.eth.send_raw_transaction(signed_tx.raw_transaction) ``` -------------------------------- ### Complete WebSocket Client Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Demonstrates how to initialize, connect, subscribe to channels, and handle events using the WebSocketClient. Includes auto-reconnect configuration. ```python import asyncio from limitless_sdk.websocket import WebSocketClient, WebSocketConfig async def main(): # Create config with auto-reconnect config = WebSocketConfig( url="wss://ws.limitless.exchange", api_key="your-api-key", # Or from LIMITLESS_API_KEY env auto_reconnect=True, reconnect_delay=1.0 ) client = WebSocketClient(config=config) # Register event handlers def on_orderbook(data): print(f"Orderbook: {data['marketSlug']}") print(f"Midpoint: {data['orderbook']['adjustedMidpoint']}") def on_price(data): print(f"Market: {data['marketAddress']}") for price in data['updatedPrices']: print(f" YES={price['yesPrice']}, NO={price['noPrice']}") def on_order_event(event): print(f"Order {event['orderId']}: {event['type']}") client.on("orderbookUpdate", on_orderbook) client.on("newPriceData", on_price) client.on("orderEvent", on_order_event) try: # Connect and subscribe await client.connect() print(f"Connected! State: {client.get_state().value}") # Subscribe to public channel await client.subscribe( "subscribe_market_prices", options={"marketSlugs": ["bitcoin-2024", "ethereum-2024"]} ) # Subscribe to auth-required channel await client.subscribe("subscribe_positions") # Keep connection alive while client.is_connected(): await asyncio.sleep(1) except KeyboardInterrupt: print("Shutting down...") finally: await client.disconnect() print("Disconnected!") asyncio.run(main()) ``` -------------------------------- ### NewPriceData Event Handler Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Example of a callback function to process new price data updates, printing market addresses and prices. ```python def on_price(data: NewPriceData): print(f"Market: {data['marketAddress']}") print(f"Block: {data['blockNumber']}") for price in data['updatedPrices']: print(f"Market {price['marketId']}: YES={price['yesPrice']}, NO={price['noPrice']}") client.on("newPriceData", on_price) ``` -------------------------------- ### Setup WebSocket Client Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Configures and initializes the WebSocket client for real-time data subscriptions. Supports automatic reconnection. ```python from limitless_sdk.websocket import WebSocketClient, WebSocketConfig # Setup WebSocket config = WebSocketConfig( url="wss://ws.limitless.exchange", auto_reconnect=True, reconnect_delay=1.0 ) ws_client = WebSocketClient(config=config) ``` -------------------------------- ### WebSocketConfig Example Usage Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Demonstrates how to instantiate the WebSocketConfig class with custom parameters for a WebSocket connection. ```python from limitless_sdk.websocket import WebSocketConfig config = WebSocketConfig( url="wss://ws.limitless.exchange", api_key="your-api-key", auto_reconnect=True, reconnect_delay=2.0, timeout=30.0 ) ``` -------------------------------- ### OrderEvent Handler Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Example function to process incoming OrderEvent data. It prints common fields and specific details for settlement events. ```python def on_order_event(event: OrderEvent): print(f"Order ID: {event['orderId']}") print(f"Side: {event['side']}") print(f"Type: {event['type']}") print(f"Source: {event['source']}") # Handle settlement events if event.get('source') == 'SETTLEMENT': print(f"Tx Hash: {event['txHash']}") if event.get('makerMatches'): for match in event['makerMatches']: print(f" Matched: {match['matchedSize']} @ {match['price']}") client.on("orderEvent", on_order_event) ``` -------------------------------- ### Complete Example: Managing Partner Accounts with Limitless SDK Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-partner-services.md Demonstrates a full workflow including creating partner accounts, deriving API tokens with specific scopes, listing accounts, and performing wallet redemptions. Ensure API keys are handled securely and sensitive data like token secrets are stored appropriately. ```python import asyncio from limitless_sdk.api import HttpClient from limitless_sdk import ( PartnerAccountService, ApiTokenService, DelegatedOrderService, ServerWalletService, ) async def manage_partner_accounts(): http_client = HttpClient(api_key="parent-api-key") # Services partner_service = PartnerAccountService(http_client) token_service = ApiTokenService(http_client) delegated_service = DelegatedOrderService(http_client) wallet_service = ServerWalletService(http_client) async with http_client: # Step 1: Create a partner account from limitless_sdk import CreatePartnerAccountInput account_input = CreatePartnerAccountInput( parent_address="0x...", child_address="0x..." ) account = await partner_service.create_account(account_input) print(f"Account created: {account.id}") # Step 2: Derive a scoped API token for the child from limitless_sdk import DeriveApiTokenInput token_input = DeriveApiTokenInput( parent_api_key="parent-api-key", scopes=["trading"], account=account.child_address ) token_response = await token_service.derive_token(token_input) print(f"Token created: {token_response.token_id}") # Save token_response.secret securely! # Step 3: List accounts accounts = await partner_service.list_accounts() print(f"Total accounts: {len(accounts.accounts)}") # Step 4: Create delegated order (parent signs for child) # ... (order creation logic) # Step 5: Redeem positions from server wallet from limitless_sdk import RedeemServerWalletInput redeem_input = RedeemServerWalletInput( account="0x...", positions=["token-id"], destination="0x..." ) redeem_response = await wallet_service.redeem(redeem_input) print(f"Redemption tx: {redeem_response.transaction_envelope.tx_hash}") asyncio.run(manage_partner_accounts()) ``` -------------------------------- ### Create FAK BUY Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example for creating a Fill-And-Kill (FAK) BUY order. ```python 10_create_buy_fak_order.py ``` -------------------------------- ### get() Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Performs a GET request to the specified API path with optional query parameters and headers. ```APIDOC ## GET ### Description Performs a GET request to the specified API path with optional query parameters and headers. ### Method GET ### Endpoint `/{path}` ### Parameters #### Path Parameters - **path** (str) - Yes - Request path (e.g., `/markets`) #### Query Parameters - **params** (Dict[str, Any]) - No - Query parameters #### Request Body None ### Request Example ```python # Fetch markets markets = await http_client.get("/markets") # With query parameters active = await http_client.get( "/markets/active", params={"limit": 10, "sortBy": "lp_rewards"} ) # Fetch specific market market = await http_client.get("/markets/bitcoin-2024") ``` ### Response #### Success Response (200) - **data** (Any) - Response data as parsed JSON ### Errors - `APIError`: Generic API error - `ValidationError`: 400 Bad Request - `AuthenticationError`: 401/403 authentication failures - `RateLimitError`: 429 rate limit exceeded - `ConflictError`: 409 conflict error ``` -------------------------------- ### OrderbookUpdate Event Handler Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Example of a callback function to process incoming order book updates, printing market details and best bid. ```python def on_orderbook(data: OrderbookUpdate): print(f"Market: {data['marketSlug']}") print(f"Token ID: {data['orderbook']['tokenId']}") print(f"Midpoint: {data['orderbook']['adjustedMidpoint']}") if data['orderbook']['bids']: best_bid = data['orderbook']['bids'][0] print(f"Best bid: {best_bid['price']} @ {best_bid['size']}") client.on("orderbookUpdate", on_orderbook) ``` -------------------------------- ### API Key Authentication with Portfolio Data Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example showing API key authentication and retrieval of portfolio data. ```python 01_authentication.py ``` -------------------------------- ### Create FOK BUY Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example for creating a Fill-Or-Kill (FOK) BUY order. ```python 05_create_buy_fok_order.py ``` -------------------------------- ### Real-time WebSocket Events Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example for handling real-time events via WebSockets. ```python 08_websocket_events.py ``` -------------------------------- ### Python: Complete Order Creation and Cancellation Example Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-orders.md This snippet demonstrates the full lifecycle of creating and then cancelling an order using the Limitless SDK. Ensure you have set up your account, HTTP client, and market fetcher before running. ```python import asyncio from eth_account import Account from limitless_sdk.api import HttpClient from limitless_sdk.orders import OrderClient from limitless_sdk.markets import MarketFetcher from limitless_sdk.types import Side, OrderType async def main(): # Setup account = Account.from_key("0x...") http_client = HttpClient(api_key="your-api-key") market_fetcher = MarketFetcher(http_client) async with http_client: client = OrderClient( http_client=http_client, wallet=account, market_fetcher=market_fetcher ) # Cache venue data first market = await market_fetcher.get_market("bitcoin-2024") # Create order (user data auto-fetched) order = await client.create_order( token_id="123456", side=Side.BUY, order_type=OrderType.GTC, market_slug="bitcoin-2024", price=0.65, size=100.0 ) print(f"Order created: {order.order.id}") # Cancel if needed await client.cancel(order.order.id) asyncio.run(main()) ``` -------------------------------- ### Perform GET Request Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Use the get() method to fetch data from the API. Supports optional query parameters and custom headers. ```python # Fetch markets markets = await http_client.get("/markets") # With query parameters active = await http_client.get( "/markets/active", params={"limit": 10, "sortBy": "lp_rewards"} ) # Fetch specific market market = await http_client.get("/markets/bitcoin-2024") ``` -------------------------------- ### Custom Retry Logic Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example demonstrating custom retry logic implementation. ```python 06_retry_handling.py ``` -------------------------------- ### Create Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Example of creating a limit order with specific parameters. Ensure venue caching is implemented for performance. ```python order = await order_client.create_order( token_id="123456", side=Side.BUY, order_type=OrderType.GTC, market_slug="bitcoin-2024", price=0.65, size=100.0 ) ``` -------------------------------- ### Type Hinting for Market and Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Illustrates the use of type hints for IDE autocompletion and type checking. Shows examples for fetching a market and creating an order. ```python # mypy compatible from limitless_sdk import Market, OrderResponse async def get_market(slug: str) -> Market: return await market_fetcher.get_market(slug) async def create_order(...) -> OrderResponse: return await order_client.create_order(...) ``` -------------------------------- ### Fetch User Profile, Positions, and History Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-portfolio.md Demonstrates how to initialize the SDK, fetch the current user profile, retrieve all CLOB and AMM positions, and access paginated trade history. Ensure you have a valid API key and have installed the necessary SDK components. ```python import asyncio from limitless_sdk.api import HttpClient from limitless_sdk.portfolio import PortfolioFetcher async def main(): http_client = HttpClient(api_key="your-api-key") fetcher = PortfolioFetcher(http_client) async with http_client: # Get current user profile profile = await fetcher.get_current_profile() print(f"User ID: {profile['id']}") print(f"Account: {profile['account']}") print(f"Fee Rate: {profile['rank']['feeRateBps'] / 100}% ") # Get all positions positions = await fetcher.get_positions() print(f"CLOB Positions: {len(positions['clob'])}") print(f"AMM Positions: {len(positions['amm'])}") # Detail on CLOB positions for pos in positions['clob']: market = pos['market'] yes_pnl = pos['positions']['yes']['unrealizedPnl'] no_pnl = pos['positions']['no']['unrealizedPnl'] print(f"\n{market['title']}") print(f" YES P&L: {yes_pnl}") print(f" NO P&L: {no_pnl}") # Get trade history (paginated) page1 = await fetcher.get_user_history(limit=10) print(f"\n\nRecent trades: {len(page1['data'])} entries") for entry in page1['data']: print(f" {entry['strategy']} {entry.get('market', {}).get('slug')} @ {entry.get('price')}") # Continue to next page if available if page1.get('nextCursor'): page2 = await fetcher.get_user_history( cursor=page1['nextCursor'], limit=10 ) print(f"\nNext page: {len(page2['data'])} entries") asyncio.run(main()) ``` -------------------------------- ### Create GTC BUY Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example for creating a Good-Til-Cancelled (GTC) BUY order. ```python 02_create_buy_gtc_order.py ``` -------------------------------- ### Auto-Retry Patterns with RetryableClient Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example showcasing auto-retry patterns using the RetryableClient. ```python 07_auto_retry_second_sample.py ``` -------------------------------- ### Run API Token Examples Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/examples/api_key_v3/README.md Execute Python scripts to test various API functionalities. These scripts utilize the configured environment variables to interact with the Limitless API. ```bash python examples/api_key_v3/api_tokens.py ``` ```bash python examples/api_key_v3/partner_account.py ``` ```bash python examples/api_key_v3/partner_account_allowances.py ``` ```bash python examples/api_key_v3/delegated_order.py ``` ```bash python examples/api_key_v3/delegated_fok_order.py ``` ```bash python examples/api_key_v3/server_wallet_redeem_withdraw.py ``` ```bash python examples/api_key_v3/e2e_flow.py ``` ```bash python examples/api_key_v3/websocket_hmac.py ``` -------------------------------- ### Setup Token Approvals Script Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Executes a script to configure wallet approvals for tokens required by exchange contracts. Ensure your wallet is configured in .env before running. ```bash # Configure your wallet in .env python examples/00_setup_approvals.py ``` -------------------------------- ### Create and Submit an Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Example of creating and submitting a limit order (GTC). It requires wallet account, HTTP client, market fetcher, and order client. Fetching the market first is recommended for venue caching. ```python from eth_account import Account from limitless_sdk.api import HttpClient from limitless_sdk.orders import OrderClient from limitless_sdk.markets import MarketFetcher from limitless_sdk.types import Side, OrderType async def create_order(): account = Account.from_key("0x...") http_client = HttpClient(api_key="your-api-key") market_fetcher = MarketFetcher(http_client) async with http_client: order_client = OrderClient( http_client=http_client, wallet=account, market_fetcher=market_fetcher ) # Fetch market to cache venue market = await market_fetcher.get_market("bitcoin-2024") # Create order order = await order_client.create_order( token_id="123456", side=Side.BUY, order_type=OrderType.GTC, market_slug="bitcoin-2024", price=0.65, size=100.0 ) print(f"Order created: {order.order.id}") asyncio.run(create_order()) ``` -------------------------------- ### Set Required Environment Variables Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/examples/api_key_v3/README.md Configure the necessary environment variables for API authentication and market identification. These are essential for running the provided examples. ```bash export LIMITLESS_IDENTITY_TOKEN="..." export LIMITLESS_API_TOKEN_ID="..." export LIMITLESS_API_TOKEN_SECRET="..." export MARKET_SLUG="your-market-slug" ``` -------------------------------- ### Create GTC SELL Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example for creating a Good-Til-Cancelled (GTC) SELL order. ```python 04_create_sell_gtc_order.py ``` -------------------------------- ### Get Property Keys and Options Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Retrieves all available property keys and then fetches details and options for a specific property key. Useful for understanding market metadata. ```python property_keys = await page_fetcher.get_property_keys() if property_keys: key = await page_fetcher.get_property_key(property_keys[0].id) options = await page_fetcher.get_property_options(key.id) ``` -------------------------------- ### Configure Environment Variables for API Key Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example of setting environment variables for API authentication and custom API URLs. Place the .env file in your project root. ```bash # Required for authenticated endpoints LIMITLESS_API_KEY=sk_live_your_api_key_here # Optional: Custom API URL (defaults to production) # LIMITLESS_API_URL=https://api.limitless.exchange ``` -------------------------------- ### Authentication Setup Environment Variables Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Set environment variables for API key, custom API endpoint, and chain ID to authenticate and configure the SDK. The chain ID is used for order signing. ```bash # Set API key export LIMITLESS_API_KEY=your-api-key-here # Optional: Set custom API endpoint export LIMITLESS_API_URL=https://api.limitless.exchange # Optional: Set chain ID for order signing export CHAIN_ID=8453 # Base mainnet ``` -------------------------------- ### Python SDK: Fetching Market Data Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Demonstrates how to use the MarketFetcher to retrieve active markets, specific market details, orderbook information, and cached venue data. Ensure you have initialized the HttpClient and MarketFetcher correctly. This example uses asyncio for asynchronous operations. ```python import asyncio from limitless_sdk.api import HttpClient from limitless_sdk.markets import MarketFetcher from limitless_sdk.types import ActiveMarketsParams async def main(): http_client = HttpClient() fetcher = MarketFetcher(http_client) async with http_client: # Get active markets response = await fetcher.get_active_markets( ActiveMarketsParams( limit=8, page=1, sort_by="lp_rewards" ) ) print(f"Found {len(response.data)} markets (total: {response.total_markets_count})") # Fetch specific market market = await fetcher.get_market("bitcoin-2024") print(f"\nMarket: {market.title}") print(f"Status: {market.status}") print(f"Expiration: {market.expiration_date}") # Get orderbook orderbook = await fetcher.get_orderbook("bitcoin-2024") print(f"\nOrderbook for {orderbook.token_id}") print(f"Midpoint: {orderbook.adjusted_midpoint}") print(f"Best bid: {orderbook.bids[0] if orderbook.bids else 'None'}") print(f"Best ask: {orderbook.asks[0] if orderbook.asks else 'None'}") # Get cached venue venue = fetcher.get_venue("bitcoin-2024") if venue: print(f"\nVenue:") print(f" Exchange: {venue.exchange}") print(f" Adapter: {venue.adapter}") asyncio.run(main()) ``` -------------------------------- ### Get Active Markets with Pagination and Sorting Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Retrieve a paginated list of active markets, with options to sort by various criteria like LP rewards or expiration. Useful for discovering available markets. ```python from limitless_sdk.types import ActiveMarketsParams # Get first page with 8 markets sorted by LP rewards response = await fetcher.get_active_markets( ActiveMarketsParams( limit=8, page=1, sort_by="lp_rewards" ) ) print(f"Found {len(response.data)} markets") print(f"Total available: {response.total_markets_count}") # Get next page page2 = await fetcher.get_active_markets( ActiveMarketsParams(limit=8, page=2, sort_by="lp_rewards") ) ``` -------------------------------- ### Perform GET Request with Identity Token Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Use get_with_identity to make a GET request authenticated with a bearer token. Ensure the identity_token is not empty to avoid a ValueError. ```python async def get_with_identity( path: str, identity_token: str, params: Optional[Dict[str, Any]] = None, ) -> Any: # ... implementation details ... pass ``` ```python # Use with third-party identity tokens data = await http_client.get_with_identity( "/user/profile", identity_token="eyJhbGciOi..." ) ``` -------------------------------- ### Perform Raw GET Request Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Use get_raw to perform a GET request and retrieve the raw response, including status and headers. This is useful when you need to inspect the full response details. ```python async def get_raw( path: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, allow_redirects: bool = True, accepted_statuses: Optional[Set[int]] = None, ) -> HttpRawResponse: # ... implementation details ... pass ``` ```python raw = await http_client.get_raw("/markets/bitcoin-2024") print(raw.status) # 200 print(raw.headers) # {'content-type': 'application/json', ...} print(raw.data) # Parsed response data ``` -------------------------------- ### Initialize PortfolioFetcher Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-portfolio.md Instantiate the PortfolioFetcher with an authenticated HttpClient. This is the first step to accessing portfolio data. ```python from limitless_sdk.api import HttpClient from limitless_sdk.portfolio import PortfolioFetcher http_client = HttpClient(api_key="your-api-key") fetcher = PortfolioFetcher(http_client) ``` -------------------------------- ### Get Venue Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Retrieves information about the venue associated with a specific market. ```APIDOC ## GET /markets/{market_id}/venue ### Description Retrieves information about the venue associated with a specific market. ### Method GET ### Endpoint /markets/{market_id}/venue ### Parameters #### Path Parameters - **market_id** (string) - Required - The unique identifier of the market. ### Response #### Success Response (200) - **exchange** (string) - The name of the exchange. - **adapter** (string) - The adapter used by the venue. ### Response Example ```json { "exchange": "ExampleExchange", "adapter": "ExampleAdapter" } ``` ``` -------------------------------- ### Minimal HttpClient Configuration (Environment Variables) Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/configuration.md Initializes HttpClient using environment variables for API key and URL. Ensure LIMITLESS_API_KEY and LIMITLESS_API_URL are set. ```python from limitless_sdk.api import HttpClient # Reads from LIMITLESS_API_KEY and LIMITLESS_API_URL http_client = HttpClient() ``` -------------------------------- ### Basic Authentication with API Key Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Demonstrates different ways to initialize the HttpClient with an API key, including automatic loading from environment variables, explicit key provision, and custom base URLs. ```python import os from limitless_sdk.api import HttpClient # Option 1: Automatic from environment variable (recommended) # Set LIMITLESS_API_KEY in your .env file or environment http_client = HttpClient() # Option 2: Explicit API key http_client = HttpClient( api_key=os.getenv("LIMITLESS_API_KEY") ) # Option 3: Custom base URL (for dev/staging) http_client = HttpClient( base_url="https://staging.api.limitless.exchange", api_key="sk_test_..." ) # All requests automatically include X-API-Key header ``` -------------------------------- ### Cancel GTC Order Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Example demonstrating how to cancel a Good-Til-Cancelled (GTC) order. ```python 03_cancel_gtc_order.py ``` -------------------------------- ### Get Orderbook Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Retrieves the orderbook for a specific market, showing current bids and asks. ```APIDOC ## GET /markets/{market_id}/orderbook ### Description Retrieves the orderbook for a specific market, showing current bids and asks. ### Method GET ### Endpoint /markets/{market_id}/orderbook ### Parameters #### Path Parameters - **market_id** (string) - Required - The unique identifier of the market. ### Response #### Success Response (200) - **token_id** (string) - The ID of the token for the market. - **adjusted_midpoint** (float) - The adjusted midpoint price. - **bids** (array) - A list of bid orders. - **asks** (array) - A list of ask orders. ### Response Example ```json { "token_id": "bitcoin-2024", "adjusted_midpoint": 65000.50, "bids": [ { "price": 64990.00, "size": 1.5 } ], "asks": [ { "price": 65011.00, "size": 2.0 } ] } ``` ``` -------------------------------- ### Initialize WebSocketClient Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Demonstrates how to initialize the WebSocketClient for both default public and authenticated connections. ```python from limitless_sdk.websocket import WebSocketClient, WebSocketConfig # Default public connection (no auth) client = WebSocketClient() # Authenticated connection config = WebSocketConfig( url="wss://ws.limitless.exchange", api_key="your-api-key", # From environment: LIMITLESS_API_KEY auto_reconnect=True ) client = WebSocketClient(config=config) ``` -------------------------------- ### Get Specific Market Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Fetches detailed information for a specific market identified by its ID. ```APIDOC ## GET /markets/{market_id} ### Description Fetches detailed information for a specific market identified by its ID. ### Method GET ### Endpoint /markets/{market_id} ### Parameters #### Path Parameters - **market_id** (string) - Required - The unique identifier of the market. ### Response #### Success Response (200) - **id** (string) - The market ID. - **title** (string) - The market title. - **status** (string) - The current status of the market. - **expiration_date** (string) - The expiration date of the market. ### Response Example ```json { "id": "bitcoin-2024", "title": "Bitcoin 2024", "status": "active", "expiration_date": "2024-12-31T00:00:00Z" } ``` ``` -------------------------------- ### OrderClient Constructor Parameters Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/configuration.md Details the parameters for initializing OrderClient, including an HTTP client, wallet account, signing configuration, market fetcher, and logger. ```python from limitless_sdk.orders import OrderClient from limitless_sdk.api import HttpClient from eth_account import Account account = Account.from_key(private_key) http_client = HttpClient(api_key="your-api-key") order_client = OrderClient( http_client=http_client, wallet=account, signing_config: Optional[OrderSigningConfig] = None, market_fetcher: Optional[MarketFetcher] = None, logger: Optional[ILogger] = None, ) ``` -------------------------------- ### Initialize MarketFetcher Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Instantiate the MarketFetcher with an HTTP client. This is the primary entry point for market data operations. ```python from limitless_sdk.api import HttpClient from limitless_sdk.markets import MarketFetcher http_client = HttpClient() fetcher = MarketFetcher(http_client) ``` -------------------------------- ### Get Signer Ethereum Address Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-orders.md Retrieves the Ethereum address of the configured signer. This is a property accessor. ```python print(f"Signer address: {signer.address}") ``` -------------------------------- ### Import Paths for Limitless SDK Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Demonstrates the import paths for various components of the Limitless SDK, including the main entry point and sub-modules. This helps in structuring your project and accessing specific functionalities. ```python # Main entry point (re-exports everything) from limitless_sdk import ( HttpClient, OrderClient, OrderBuilder, OrderSigner, MarketFetcher, MarketPageFetcher, PortfolioFetcher, WebSocketClient, ApiTokenService, PartnerAccountService, DelegatedOrderService, ServerWalletService, ) # Sub-modules from limitless_sdk.api import HttpClient, RetryConfig, APIError from limitless_sdk.orders import OrderClient, OrderBuilder, OrderSigner from limitless_sdk.markets import MarketFetcher from limitless_sdk.portfolio import PortfolioFetcher from limitless_sdk.websocket import WebSocketClient from limitless_sdk.types import Side, OrderType, Market, OrderBook ``` -------------------------------- ### Initialize OrderSigner Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-orders.md Create an instance of OrderSigner to sign unsigned orders using EIP-712. Pass an eth_account.Account instance containing the private key and an optional logger for debugging. ```python from eth_account import Account from limitless_sdk.orders import OrderSigner account = Account.from_key("0x...") signer = OrderSigner(account) ``` -------------------------------- ### Initialize OrderBuilder Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-orders.md Create an instance of OrderBuilder to construct unsigned orders. Specify the maker's address, fee rate in basis points, and the price tick for granularity. ```python from limitless_sdk.orders import OrderBuilder from limitless_sdk.types import Side builder = OrderBuilder( maker_address="0x1234567890123456789012345678901234567890", fee_rate_bps=300, # 3% price_tick=0.001 # 0.1% granularity ) ``` -------------------------------- ### Get User Profile by Address Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-portfolio.md Retrieve the profile information for a specific wallet address. Ensure the address is 0x-prefixed. ```python profile = await fetcher.get_profile("0x1234567890123456789012345678901234567890") print(f"User ID: {profile['id']}") print(f"Account: {profile['account']}") print(f"Fee Rate: {profile['rank']['feeRateBps'] / 100}%") ``` -------------------------------- ### Good: Reuse HTTP Client Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/README.md Demonstrates the recommended practice of reusing an HttpClient instance for multiple SDK clients to improve efficiency. ```python http_client = HttpClient(api_key="key") market_fetcher = MarketFetcher(http_client) order_client = OrderClient(http_client=http_client, wallet=account) ``` -------------------------------- ### Get Active Markets Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-markets.md Retrieves a paginated list of active markets. Supports sorting and filtering by various parameters. ```APIDOC ## GET /markets ### Description Retrieves a paginated list of active markets. Supports sorting and filtering by various parameters. ### Method GET ### Endpoint /markets ### Parameters #### Query Parameters - **limit** (int) - Optional - The maximum number of markets to return per page. - **page** (int) - Optional - The page number to retrieve. - **sort_by** (string) - Optional - The field to sort the markets by (e.g., "lp_rewards"). ### Response #### Success Response (200) - **data** (array) - A list of market objects. - **total_markets_count** (int) - The total number of markets available. ### Response Example ```json { "data": [ { "id": "bitcoin-2024", "title": "Bitcoin 2024", "status": "active", "expiration_date": "2024-12-31T00:00:00Z" } ], "total_markets_count": 100 } ``` ``` -------------------------------- ### connect() Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Establishes a connection to the WebSocket server. This method should be called before any other operations that require an active connection. ```APIDOC ## connect() ### Description Connects to the WebSocket server. This method should be awaited before performing any operations that require an active connection. ### Method `async def connect(self) -> None` ### Parameters None ### Raises - `Exception`: If the connection fails. ### Request Example ```python await client.connect() print("Connected!") ``` ``` -------------------------------- ### Initialize OrderClient Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-orders.md Initializes the OrderClient with necessary dependencies like an HTTP client and an Ethereum wallet. A MarketFetcher is recommended for caching venue data. ```python from eth_account import Account from limitless_sdk.api import HttpClient from limitless_sdk.orders import OrderClient from limitless_sdk.markets import MarketFetcher account = Account.from_key(private_key) http_client = HttpClient(api_key="your-api-key") market_fetcher = MarketFetcher(http_client) # Recommended for venue caching client = OrderClient( http_client=http_client, wallet=account, market_fetcher=market_fetcher ) ``` -------------------------------- ### Initialize HttpClient Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Instantiate the HttpClient class. It can auto-load credentials from environment variables or be explicitly configured with base URL, API key, and timeout. ```python import os from limitless_sdk.api import HttpClient # Auto-load from environment variables http_client = HttpClient() # Explicit configuration http_client = HttpClient( base_url="https://api.limitless.exchange", api_key=os.getenv("LIMITLESS_API_KEY"), timeout=60 ) # With custom headers http_client = HttpClient( additional_headers={ "X-Custom-Header": "value" } ) ``` -------------------------------- ### Get Orderbook Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Fetches the orderbook for a given market slug. Allows access to bids and asks for analyzing market liquidity. ```python orderbook = await market_fetcher.get_orderbook("market-slug") # Access bids/asks for order in orderbook.get('orders', []): print(f"Price: {order['price']}, Size: {order['size']}") ``` -------------------------------- ### Get WebSocket Connection State Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Retrieves the current state of the WebSocket connection. The state is returned as a WebSocketState enum value. ```python state = client.get_state() print(f"State: {state.value}") # "connected", "disconnected", etc. ``` -------------------------------- ### Get HMAC Credentials Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Use get_hmac_credentials to retrieve the current HMAC credentials. A copy of the credentials is returned, which can be safely modified. ```python def get_hmac_credentials(self) -> Optional[HMACCredentials]: # ... implementation details ... pass ``` -------------------------------- ### Get Owner ID Property Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-orders.md Retrieve the owner ID from the user profile. Returns None if the profile data has not yet been loaded. ```python @property def owner_id(self) -> Optional[int] ``` -------------------------------- ### get_with_identity() Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-http-client.md Performs a GET request with bearer token authentication. This method is suitable for accessing resources that require user identity verification. ```APIDOC ## GET /path ### Description Perform GET request with bearer token authentication. ### Method GET ### Endpoint /path ### Parameters #### Query Parameters - **params** (Dict[str, Any]) - Optional - Query parameters #### Path Parameters - **path** (str) - Required - Request path - **identity_token** (str) - Required - Bearer token value ### Raises: - `ValueError`: If identity_token is empty ### Request Example ```python # Use with third-party identity tokens data = await http_client.get_with_identity( "/user/profile", identity_token="eyJhbGciOi..." ) ``` ``` -------------------------------- ### Get Only AMM Positions Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-portfolio.md Fetch only the AMM (Automated Market Maker) positions for the authenticated user. This is a convenience method for filtering positions. ```python amm = await fetcher.get_amm_positions() for pos in amm: market = pos['market'] unrealized = pos['unrealizedPnl'] print(f"{market['title']}: Unrealized P&L = {unrealized}") ``` -------------------------------- ### Fetch Navigation Tree and Market Page by Path Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/README.md Demonstrates fetching the site's navigation tree and resolving a specific market page using its URL path. Handles manual 301 redirects internally. ```python from limitless_sdk.api import HttpClient from limitless_sdk.market_pages import MarketPageFetcher http_client = HttpClient(base_url="https://api.limitless.exchange") page_fetcher = MarketPageFetcher(http_client) # 1) Navigation tree navigation = await page_fetcher.get_navigation() # 2) Resolve page by path (manual 301 handled internally) page = await page_fetcher.get_market_page_by_path("/crypto") ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-websocket.md Establishes a connection to the Limitless Exchange WebSocket server. Ensure the client is initialized before calling this method. ```python await client.connect() print("Connected!") ``` -------------------------------- ### Get User History with Pagination Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-portfolio.md Fetches user history data with support for cursor-based pagination. Use the 'nextCursor' from the response for subsequent requests. ```python async def get_user_history( cursor: Optional[str] = None, limit: int = 20, ) -> dict: # ... function body ... ``` ``` ```python # Get first page response = await fetcher.get_user_history(limit=20) print(f"Found {len(response['data'])} entries") # Process entries for entry in response['data']: print(f"\nStrategy: {entry['strategy']}") print(f"Market: {entry.get('market', {}).get('slug')}") print(f"Timestamp: {entry.get('timestamp')}") # Get next page if available if response.get('nextCursor'): page2 = await fetcher.get_user_history( cursor=response['nextCursor'], limit=20 ) print(f"Next page: {len(page2['data'])} entries") # Continue pagination cursor = page2.get('nextCursor') while cursor: page = await fetcher.get_user_history(cursor=cursor, limit=20) print(f"Page: {len(page['data'])} entries") cursor = page.get('nextCursor') ``` -------------------------------- ### Get Only CLOB Positions Source: https://github.com/limitless-labs-group/limitless-sdk/blob/main/_autodocs/api-reference-portfolio.md Fetch only the CLOB (Central Limit Order Book) positions for the authenticated user. This is a convenience method for filtering positions. ```python clob = await fetcher.get_clob_positions() for pos in clob: market = pos['market'] yes_balance = pos['positions']['yes']['balance'] no_balance = pos['positions']['no']['balance'] print(f"{market['title']}: YES={yes_balance}, NO={no_balance}") ```