### Install the Go SDK Source: https://docs.limitless.exchange/developers/sdk/go/getting-started Use the go get command to add the SDK to your project dependencies. ```bash go get github.com/limitless-labs-group/limitless-exchange-go-sdk@latest ``` -------------------------------- ### Install the SDK Source: https://docs.limitless.exchange/developers/sdk/typescript/getting-started Commands to install the SDK using common package managers. ```bash npm install @limitless-exchange/sdk ``` ```bash yarn add @limitless-exchange/sdk ``` ```bash pnpm add @limitless-exchange/sdk ``` -------------------------------- ### Install the Python SDK Source: https://docs.limitless.exchange/developers/sdk/python/getting-started Install the package using pip. ```bash pip install limitless-sdk ``` -------------------------------- ### Clone and Install Dependencies Source: https://docs.limitless.exchange/developers/cross-market-market-making Initializes the agent starter repository and sets up the environment configuration. ```bash git clone https://github.com/limitless-labs-group/agents-starter.git cd agents-starter && npm install cp .env.example .env && chmod 600 .env # set PRIVATE_KEY (any dedicated EOA), LMTS_TOKEN_ID, LMTS_TOKEN_SECRET. Leave DRY_RUN=true. ``` -------------------------------- ### Install Dependencies Source: https://docs.limitless.exchange/developers/quickstart/nodejs Install the required packages for the Limitless Exchange integration using your preferred package manager. ```bash pnpm add socket.io-client cross-fetch ethers viem ``` ```bash npm install socket.io-client cross-fetch ethers viem ``` ```bash yarn add socket.io-client cross-fetch ethers viem ``` -------------------------------- ### Order ID Input Examples Source: https://docs.limitless.exchange/api-reference/trading/batch-cancel Format examples for order identifier arrays. ```json ["6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203"] ``` ```json ["partner-order-001", "partner-order-002"] ``` -------------------------------- ### Install Python dependencies Source: https://docs.limitless.exchange/developers/quickstart/python Install the required packages for EIP-712 signing, HTTP requests, and Web3 utilities. ```bash pip install eth-account requests web3 ``` -------------------------------- ### Initialize the HTTP client Source: https://docs.limitless.exchange/developers/sdk/typescript/getting-started Basic setup for the HTTP client instance. ```typescript import { HttpClient } from '@limitless-exchange/sdk'; const httpClient = new HttpClient({ baseURL: 'https://api.limitless.exchange', }); ``` -------------------------------- ### Install SDK dependencies Source: https://docs.limitless.exchange/developers/sdk/rust/getting-started Add the SDK and Tokio runtime to your Cargo.toml file. ```toml [dependencies] limitless-exchange-rust-sdk = "1.1.0" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` -------------------------------- ### Provisional Match Event Structure Source: https://docs.limitless.exchange/developers/websocket-events Example of a MATCHED event emitted by the matching engine before on-chain settlement occurs. ```json { "source": "SETTLEMENT", "type": "MATCHED", "eventId": "matched:77985c10…:d45b884d…", "tradeEventId": "77985c10…", "orderId": "d45b884d…", "takerOrderId": "d45b884d…", "marketSlug": "will-abc-happen-by-2026", "tokenId": "27102822276156300166...", "token": "NO", "side": "BUY", "price": "0.53", "amountContracts": "25", "amountCollateral": "13.25", "configuredFeeRateBps": 30, "effectiveFeeBps": 27, "feeAmountContracts": "0.0675", "isEstimate": true, "timestamp": "2026-04-20T10:15:40.000Z", "matchedAt": "2026-04-20T10:15:40.000Z", "occurredAt": "2026-04-20T10:15:40.000Z", "publishedAt": "2026-04-20T10:15:40.050Z" } ``` -------------------------------- ### OME Lifecycle Event JSON Structure Source: https://docs.limitless.exchange/developers/websocket-events Example payload for a PLACEMENT event. Note that price and remainingSize are sent as unquoted JSON numbers. ```json { "source": "OME", "type": "PLACEMENT", "eventId": 1234567, "orderId": "550e8400-e29b-41d4-a716-446655440000", "clientOrderId": "client-order-001", "userId": 42, "marketId": "17", "token": "87893014956437093847...", "side": "BUY", "price": 0.53, "remainingSize": 100, "timestamp": "2026-04-20T10:15:30.000Z", "occurredAt": "2026-04-20T10:15:30.000Z", "publishedAt": "2026-04-20T10:15:30.042Z" } ``` -------------------------------- ### Complete WebSocket Client Implementation Source: https://docs.limitless.exchange/developers/sdk/go/websocket A full example demonstrating client initialization, event handler registration, connection management, and channel subscription. ```go package main import ( "context" "fmt" "log" "os" "os/signal" "syscall" limitless "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" ) func main() { ws := limitless.NewWebSocketClient( limitless.WithAutoReconnect(true), limitless.WithWebSocketLogger(limitless.NewConsoleLogger(limitless.LogLevelInfo)), ) // Register typed event handlers before connecting ws.OnOrderbookUpdate(func(update limitless.OrderbookUpdate) { fmt.Printf("[%s] Orderbook: %d bids, %d asks, midpoint %.3f\n", update.MarketSlug, len(update.Orderbook.Bids), len(update.Orderbook.Asks), update.Orderbook.AdjustedMidpoint) }) // Connect ctx := context.Background() if err := ws.Connect(ctx); err != nil { log.Fatal(err) } defer ws.Disconnect() // Orderbook updates are delivered through the market-price subscription if err := ws.Subscribe(ctx, limitless.ChannelSubscribeMarketPrices, limitless.SubscriptionOptions{ MarketSlugs: []string{"btc-above-100k-march-2025"}, }); err != nil { log.Fatal(err) } fmt.Println("Listening for updates... Press Ctrl+C to exit.") // Block until interrupt sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) <-sigCh } ``` -------------------------------- ### OpenAPI Maintenance Status Definition Source: https://docs.limitless.exchange/api-reference/system/maintenance-status The OpenAPI specification for the GET /maintenance/status endpoint, including schema definitions and example responses for normal and restricted states. ```yaml openapi: 3.0.0 info: title: Limitless Exchange API description: >- Production-ready REST API for prediction market trading, portfolio management, and market data on Limitless Exchange (Base L2). version: '1.0' contact: name: API Support url: https://limitless.exchange email: help@limitless.network servers: - url: https://api.limitless.exchange description: Production API security: [] tags: - name: Authentication description: User authentication and session management - name: Markets description: Browse, search, and analyze prediction markets - name: Market Navigation description: Navigation tree, market pages, and property filters - name: Trading description: Create, manage, and cancel orders - name: Portfolio description: Position tracking, trade history, and performance - name: API Tokens description: Scoped API token management for partner integrations - name: Partner Accounts description: Sub-account creation and allowance recovery for partner integrations - name: System description: Public API state and availability information - name: Referral description: Referral program earnings, referred users, and leaderboards paths: /maintenance/status: get: tags: - System summary: Get maintenance status description: >- Returns active and scheduled maintenance information. Use this endpoint to detect temporary trading restrictions and planned maintenance notices. operationId: MaintenanceController_getStatus parameters: - name: target in: query required: false description: >- Optional maintenance target filter. Use `trading` to return only trading-related maintenance effects. schema: type: string enum: - trading responses: '200': description: Maintenance status returned successfully content: application/json: schema: $ref: '#/components/schemas/MaintenanceStatus' examples: normal: summary: No active or scheduled maintenance value: active: [] scheduled: [] tradingRestricted: summary: >- Trading currently cancel-only with a scheduled post-only stage value: active: - startsAt: '2026-06-22T15:00:00.000Z' endsAt: '2026-06-22T18:00:00.000Z' publicMessage: Trading is temporarily limited to cancellations. effects: - target: trading mode: cancel_only scheduled: - startsAt: '2026-06-22T18:00:00.000Z' endsAt: '2026-06-22T19:00:00.000Z' publicMessage: >- Trading will be post-only during the next maintenance stage. effects: - target: trading mode: post_only components: schemas: MaintenanceStatus: type: object description: Current and scheduled maintenance information. properties: active: type: array description: Maintenance effects currently in force. items: $ref: '#/components/schemas/MaintenanceWindow' scheduled: type: array description: Future maintenance notices. items: $ref: '#/components/schemas/MaintenanceWindow' required: - active - scheduled MaintenanceWindow: type: object description: A maintenance window or notice. properties: startsAt: type: string format: date-time description: When the maintenance window starts. endsAt: type: string format: date-time description: When the maintenance window ends, if known. publicMessage: type: string ``` -------------------------------- ### Complete Order Lifecycle Example Source: https://docs.limitless.exchange/developers/sdk/go/orders Demonstrates client initialization, market fetching, placing GTC, FAK, and FOK orders, and cancelling all orders for a market. ```go package main import ( "context" "errors" "fmt" "log" "os" limitless "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" ) func main() { client := limitless.NewHttpClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: os.Getenv("LMTS_TOKEN_ID"), Secret: os.Getenv("LMTS_TOKEN_SECRET"), }), ) marketFetcher := limitless.NewMarketFetcher(client) ctx := context.Background() orderClient, err := limitless.NewOrderClient(client, "0xYOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } fmt.Println("Wallet:", orderClient.WalletAddress()) // Fetch market (caches venue automatically) market, err := marketFetcher.GetMarket(ctx, "btc-above-100k-march-2025") if err != nil { log.Fatal(err) } // Place a GTC BUY order for 10 YES shares at $0.65 result, err := orderClient.CreateOrder(ctx, limitless.CreateOrderParams{ OrderType: limitless.OrderTypeGTC, MarketSlug: "btc-above-100k-march-2025", Args: limitless.GTCOrderArgs{ TokenID: market.Tokens.Yes, Side: limitless.SideBuy, Price: 0.65, Size: 10.0, }, }) if err != nil { var apiErr *limitless.APIError if errors.As(err, &apiErr) { log.Fatalf("API error — status %d: %s", apiErr.Status, apiErr.Message) } log.Fatal(err) } fmt.Printf("GTC order placed: %+v\n", result.Order) // Place a FAK BUY order for 10 YES shares at $0.45 fakResult, err := orderClient.CreateOrder(ctx, limitless.CreateOrderParams{ OrderType: limitless.OrderTypeFAK, MarketSlug: "btc-above-100k-march-2025", Args: limitless.FAKOrderArgs{ TokenID: market.Tokens.Yes, Side: limitless.SideBuy, Price: 0.45, Size: 10.0, }, }) if err != nil { log.Fatal(err) } fmt.Printf("FAK order placed: %+v\n", fakResult.Order) // Place a FOK BUY order spending 5 USDC fokResult, err := orderClient.CreateOrder(ctx, limitless.CreateOrderParams{ OrderType: limitless.OrderTypeFOK, MarketSlug: "btc-above-100k-march-2025", Args: limitless.FOKOrderArgs{ TokenID: market.Tokens.Yes, Side: limitless.SideBuy, MakerAmount: 5.0, }, }) if err != nil { log.Fatal(err) } fmt.Printf("FOK order placed: %+v\n", fokResult.Order) // Cancel all orders on this market msg, err := orderClient.CancelAll(ctx, "btc-above-100k-march-2025") if err != nil { log.Fatal(err) } fmt.Println("Cancelled:", msg) } ``` -------------------------------- ### Market Resolved Event Payload Source: https://docs.limitless.exchange/developers/websocket-events Example JSON payload emitted when a market resolves, sent to market lifecycle and specific market room subscribers. ```json { "slug": "btc-above-110k-apr-2026", "type": "CLOB", "winningOutcome": "YES", "winningIndex": 0, "resolutionDate": "2026-04-05T14:00:00.000Z" } ``` -------------------------------- ### FAK/FOK Terminal Event JSON Structure Source: https://docs.limitless.exchange/developers/websocket-events Example of the JSON payload emitted when a FAK or FOK order reaches a terminal state. ```json { "source": "OME", "type": "EXECUTION", "status": "FILLED", "eventId": "terminal:550e8400-e29b-41d4-a716-446655440000", "orderId": "550e8400-e29b-41d4-a716-446655440000", "userId": 42, "marketId": "17", "token": "87893014956437093847...", "side": "BUY", "price": 0.53, "remainingSize": 0, "timestamp": "2026-04-20T10:15:40.000Z", "occurredAt": "2026-04-20T10:15:40.000Z", "publishedAt": "2026-04-20T10:15:40.031Z" } ``` -------------------------------- ### Cancel Order Request Examples Source: https://docs.limitless.exchange/api-reference/trading/cancel-order Examples of how to send a DELETE request to the orders endpoint using different programming languages. All examples require the 'lmts-api-key' header for authentication. ```curl curl --request DELETE \ --url https://api.limitless.exchange/orders/{orderId} \ --header 'lmts-api-key: ' ``` ```python import requests url = "https://api.limitless.exchange/orders/{orderId}" headers = {"lmts-api-key": ""} response = requests.delete(url, headers=headers) print(response.text) ``` ```javascript const options = {method: 'DELETE', headers: {'lmts-api-key': ''}}; fetch('https://api.limitless.exchange/orders/{orderId}', options) .then(res => res.json()) .then(res => console.log(res)) .catch(err => console.error(err)); ``` ```php "https://api.limitless.exchange/orders/{orderId}", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_HTTPHEADER => [ "lmts-api-key: " ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ``` ```go package main import ( "fmt" "net/http" "io" ) func main() { url := "https://api.limitless.exchange/orders/{orderId}" req, _ := http.NewRequest("DELETE", url, nil) req.Header.Add("lmts-api-key", "") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` ```java HttpResponse response = Unirest.delete("https://api.limitless.exchange/orders/{orderId}") .header("lmts-api-key", "") .asString(); ``` ```ruby require 'uri' require 'net/http' url = URI("https://api.limitless.exchange/orders/{orderId}") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Delete.new(url) request["lmts-api-key"] = '' response = http.request(request) puts response.read_body ``` -------------------------------- ### Initialize OrderClient and Prerequisites Source: https://docs.limitless.exchange/developers/sdk/python/orders Setup the required clients and account instance needed to authenticate and place orders. ```python import asyncio import os from eth_account import Account from limitless_sdk.api import HttpClient from limitless_sdk import HMACCredentials from limitless_sdk.markets import MarketFetcher from limitless_sdk.orders import OrderClient from limitless_sdk.types import Side, OrderType # Authenticate with a scoped API token (token ID + secret) http_client = HttpClient( hmac_credentials=HMACCredentials( token_id=os.environ["LMTS_TOKEN_ID"], secret=os.environ["LMTS_TOKEN_SECRET"], ), ) account = Account.from_key("0xYOUR_PRIVATE_KEY") market_fetcher = MarketFetcher(http_client) order_client = OrderClient(http_client, account) ``` -------------------------------- ### Pagination Metadata Example Source: https://docs.limitless.exchange/api-reference/markets/browse-active-category Example of the totalMarketsCount field used for pagination. ```yaml totalMarketsCount: type: number description: Total number of active markets available for pagination example: 150 ``` -------------------------------- ### Terminal Settlement Event JSON Structure Source: https://docs.limitless.exchange/developers/websocket-events Example of a MINED settlement event payload emitted when a trade settles on-chain. ```json { "source": "SETTLEMENT", "type": "MINED", "eventId": "settlement:1b3a…:550e8400-e29b-41d4-a716-446655440000", "tradeEventId": "1b3a…", "orderId": "550e8400-e29b-41d4-a716-446655440000", "clientOrderId": "client-order-001", "takerOrderId": "e4c3…", "takerAccount": "0xAbC…123", "makerMatches": [ { "account": "0xDeF…456", "orderId": "cb12…", "matchedSize": "25", "price": "0.53" } ], "marketSlug": "will-abc-happen-by-2026", "tokenId": "87893014956437093847...", "side": "BUY", "price": "0.53", "amountContracts": "25", "amountCollateral": "13.25", "configuredFeeRateBps": 0, "effectiveFeeBps": 0, "feeAmountContracts": "0", "txHash": "0xabc…", "timestamp": "2026-04-20T10:15:40.000Z", "matchedAt": "2026-04-20T10:15:40.000Z", "occurredAt": "2026-04-20T10:15:41.180Z", "publishedAt": "2026-04-20T10:15:41.205Z" } ``` -------------------------------- ### Complete market page integration example in Go Source: https://docs.limitless.exchange/developers/sdk/go/market-pages A full implementation showing client initialization, navigation browsing, page resolution, market filtering, and property key exploration. ```go package main import ( "context" "fmt" "log" "os" limitless "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" ) func intPtr(i int) *int { return &i } func main() { client := limitless.NewHttpClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: os.Getenv("LMTS_TOKEN_ID"), Secret: os.Getenv("LMTS_TOKEN_SECRET"), }), ) pageFetcher := limitless.NewMarketPageFetcher(client) ctx := context.Background() // Browse the navigation tree navigation, err := pageFetcher.GetNavigation(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Top-level categories: %d\n", len(navigation)) // Resolve a page page, err := pageFetcher.GetMarketPageByPath(ctx, "/crypto") if err != nil { log.Fatal(err) } fmt.Printf("\nPage: %s\n", page.Name) // Fetch markets with filters result, err := pageFetcher.GetMarkets(ctx, page.ID, &limitless.MarketPageMarketsParams{ Limit: intPtr(5), Sort: limitless.MarketPageSortNewest, Filters: map[string]any{"ticker": []string{"btc", "eth"}}, }) if err != nil { log.Fatal(err) } for _, market := range result.Data { fmt.Printf(" %s — %s\n", market.Slug, market.Title) } // Explore property keys keys, err := pageFetcher.GetPropertyKeys(ctx) if err != nil { log.Fatal(err) } for _, key := range keys { fmt.Printf("\n%s (%s)\n", key.Name, key.Type) options, _ := pageFetcher.GetPropertyOptions(ctx, key.ID, nil) for i, opt := range options { if i >= 5 { break } fmt.Printf(" %s\n", opt.Label) } } } ``` -------------------------------- ### Complete Market Pages Example Source: https://docs.limitless.exchange/developers/sdk/python/market-pages Demonstrates the full workflow of initializing the client, fetching navigation, resolving market pages, applying filters, and retrieving property metadata. ```python import asyncio from limitless_sdk.api import HttpClient from limitless_sdk.market_pages import MarketPageFetcher async def main(): http_client = HttpClient(base_url="https://api.limitless.exchange") page_fetcher = MarketPageFetcher(http_client) # Browse the navigation tree navigation = await page_fetcher.get_navigation() print(f"Top-level categories: {len(navigation)}") # Resolve a page page = await page_fetcher.get_market_page_by_path("/crypto") print(f"\nPage: {page.name}") print(f"Available filters: {[fg.name for fg in page.filter_groups]}") # Fetch markets with filters result = await page_fetcher.get_markets(page.id, { "limit": 5, "sort": "-updatedAt", "filters": {"ticker": ["btc", "eth"]}, }) for market in result.data: print(f" {market.slug} — {market.title}") # Explore property keys keys = await page_fetcher.get_property_keys() for key in keys: print(f"\n{key.name} ({key.type}):") options = await page_fetcher.get_property_options(key.id) for opt in options[:5]: print(f" {opt.label}") await http_client.close() asyncio.run(main()) ``` -------------------------------- ### Complete portfolio integration example Source: https://docs.limitless.exchange/developers/sdk/python/portfolio A full script demonstrating initialization, fetching positions, and iterating through market data. ```python import asyncio import os from limitless_sdk.api import HttpClient from limitless_sdk import HMACCredentials from limitless_sdk.portfolio import PortfolioFetcher async def main(): http_client = HttpClient( hmac_credentials=HMACCredentials( token_id=os.environ["LMTS_TOKEN_ID"], secret=os.environ["LMTS_TOKEN_SECRET"], ), ) portfolio = PortfolioFetcher(http_client) positions = await portfolio.get_positions() clob_positions = positions.get("clob", []) amm_positions = positions.get("amm", []) print(f"CLOB positions: {len(clob_positions)}") for pos in clob_positions: print(f" {pos['market']['title']} — size: {pos['size']}") print(f"\nAMM positions: {len(amm_positions)}") for pos in amm_positions: print(f" {pos['market']['title']} — size: {pos['size']}") points = positions.get("accumulativePoints", {}) print(f"\nAccumulative points: {points}") await http_client.close() asyncio.run(main()) ``` -------------------------------- ### Response Canceled Array Example Source: https://docs.limitless.exchange/api-reference/trading/cancel-batch Example of the canceled field in a successful response. ```json ["611badac-8dfc-48a0-b09e-59654adea1c5"] ``` -------------------------------- ### Install WebSocket dependencies Source: https://docs.limitless.exchange/developers/quickstart/websocket Install the necessary Python packages for WebSocket communication and authentication. ```bash pip install "python-socketio[asyncio]" eth-account==0.10.0 requests ``` -------------------------------- ### Initialize the Trading Agent Environment Source: https://docs.limitless.exchange/developers/build-a-trading-agent Clone the starter repository and prepare the environment configuration file. ```bash git clone https://github.com/limitless-labs-group/agents-starter.git cd agents-starter npm install cp .env.example .env chmod 600 .env # Edit .env, fill in PRIVATE_KEY (your dedicated wallet) + a Limitless scoped HMAC token ``` -------------------------------- ### Initialize client and fetch portfolio data in Go Source: https://docs.limitless.exchange/developers/sdk/go/portfolio Demonstrates initializing the HTTP client with HMAC credentials and fetching both positions and trading history. ```go package main import ( "context" "fmt" "log" "os" limitless "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" ) func main() { client := limitless.NewHttpClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: os.Getenv("LMTS_TOKEN_ID"), Secret: os.Getenv("LMTS_TOKEN_SECRET"), }), ) portfolio := limitless.NewPortfolioFetcher(client) ctx := context.Background() // Fetch all positions positions, err := portfolio.GetPositions(ctx) if err != nil { log.Fatal(err) } fmt.Printf("CLOB positions: %d\n", len(positions.CLOB)) for _, pos := range positions.CLOB { fmt.Printf(" %s — yes: %s, no: %s\n", pos.Market.Title, pos.TokensBalance.Yes, pos.TokensBalance.No) } fmt.Printf("\nAMM positions: %d\n", len(positions.AMM)) for _, pos := range positions.AMM { fmt.Printf(" %s — unrealized PnL: %s\n", pos.Market.Title, pos.UnrealizedPnl) } // Fetch trading history (cursor-based; empty cursor = first page) history, err := portfolio.GetUserHistory(ctx, "", 10) if err != nil { log.Fatal(err) } fmt.Printf("\nRecent trades: %d\n", len(history.Data)) } ``` -------------------------------- ### Initialize OrderClient and Dependencies Source: https://docs.limitless.exchange/developers/sdk/go/orders Setup the HttpClient, MarketFetcher, and OrderClient required to interact with the exchange. Ensure the LMTS_TOKEN_ID and LMTS_TOKEN_SECRET environment variables are set. ```go import ( "context" "log" "os" limitless "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" ) client := limitless.NewHttpClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: os.Getenv("LMTS_TOKEN_ID"), Secret: os.Getenv("LMTS_TOKEN_SECRET"), }), ) marketFetcher := limitless.NewMarketFetcher(client) orderClient, err := limitless.NewOrderClient( client, "0xYOUR_PRIVATE_KEY", // hex-encoded private key (with or without "0x" prefix) ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Total Markets Count Example Source: https://docs.limitless.exchange/api-reference/markets/browse-active Example value for the total number of active markets available for pagination. ```json 150 ``` -------------------------------- ### OpenAPI Specification for Get Trades Source: https://docs.limitless.exchange/api-reference/portfolio/trades Defines the GET /portfolio/trades endpoint, its required HMAC authentication, and the HistoryTradeDto schema. ```yaml openapi: 3.0.0 info: title: Limitless Exchange API description: >- Production-ready REST API for prediction market trading, portfolio management, and market data on Limitless Exchange (Base L2). version: '1.0' contact: name: API Support url: https://limitless.exchange email: help@limitless.network servers: - url: https://api.limitless.exchange description: Production API security: [] tags: - name: Authentication description: User authentication and session management - name: Markets description: Browse, search, and analyze prediction markets - name: Market Navigation description: Navigation tree, market pages, and property filters - name: Trading description: Create, manage, and cancel orders - name: Portfolio description: Position tracking, trade history, and performance - name: API Tokens description: Scoped API token management for partner integrations - name: Partner Accounts description: Sub-account creation and allowance recovery for partner integrations - name: System description: Public API state and availability information - name: Referral description: Referral program earnings, referred users, and leaderboards paths: /portfolio/trades: get: tags: - Portfolio summary: Get Trades description: Retrieve all AMM trades executed by the authenticated user operationId: PortfolioController_getTrades parameters: [] responses: '200': description: List of user trades with details content: application/json: schema: type: array items: $ref: '#/components/schemas/HistoryTradeDto' '401': description: Unauthorized security: - HmacAuth: [] components: schemas: HistoryTradeDto: type: object description: An AMM trade executed by the user properties: blockTimestamp: type: string description: Timestamp of the block containing the trade example: '2025-09-01T11:30:31.000Z' collateralAmount: type: string description: Collateral amount traded (in token decimals) example: '5000000' market: type: object description: Market details for the trade properties: conditionId: type: string example: 0x812f578437dc... expirationDate: type: string example: Sep 1, 2025 id: type: string example: 0x76d3e2098Be6... slug: type: string example: doge-above-021-sep-1 title: type: string example: $DOGE above $0.21652 on Sep 1? outcomeIndex: type: number description: Index of the outcome traded (0 = YES, 1 = NO) example: 0 outcomeTokenAmount: type: string description: Amount of outcome tokens traded example: '10000000' outcomeTokenAmounts: type: array description: Collateral per outcome token items: type: string example: - '5000000' - '0' outcomeTokenNetCost: type: string description: Net cost of the outcome tokens example: '4950000' outcomeTokenPrice: type: string description: Price of the outcome token at trade time example: '0.50' strategy: type: string description: Trade direction enum: - Buy - Sell example: Buy transactionHash: type: string description: On-chain transaction hash example: 0xabc123... required: - blockTimestamp - market - outcomeIndex - outcomeTokenAmounts - outcomeTokenNetCost - transactionHash securitySchemes: HmacAuth: type: apiKey in: header name: lmts-api-key description: >- Scoped API token with HMAC-SHA256 signing. Requires three headers: lmts-api-key (token ID), lmts-timestamp (ISO-8601), lmts-signature (Base64-encoded HMAC). See Authentication docs for details. ``` -------------------------------- ### Initialize and use WebSocket client Source: https://docs.limitless.exchange/developers/sdk/python/websocket Demonstrates configuring the WebSocket client, registering event handlers, and maintaining the connection loop. ```python import asyncio from limitless_sdk.websocket import WebSocketClient, WebSocketConfig async def main(): config = WebSocketConfig( url="wss://ws.limitless.exchange", auto_reconnect=True, reconnect_delay=5, ) ws_client = WebSocketClient(config) @ws_client.on("connect") async def on_connect(): print("Connected") await ws_client.subscribe( "subscribe_market_prices", {"marketSlugs": ["btc-above-100k-march-2025"]}, ) @ws_client.on("orderbookUpdate") async def on_orderbook(data): slug = data.get("marketSlug", "unknown") bids = len(data.get("bids", [])) asks = len(data.get("asks", [])) print(f"[{slug}] Orderbook: {bids} bids, {asks} asks") @ws_client.on("newPriceData") async def on_price(data): slug = data.get("marketSlug", "unknown") price = data.get("price", "N/A") print(f"[{slug}] Price: {price}") # Connect, then keep the client alive to receive events await ws_client.connect() await asyncio.Event().wait() # runs until interrupted (Ctrl+C) asyncio.run(main()) ``` -------------------------------- ### Cancel Batch Orders Request Examples Source: https://docs.limitless.exchange/api-reference/trading/cancel-batch Examples of how to perform a batch cancellation request across various programming languages. ```python import requests url = "https://api.limitless.exchange/orders/cancel-batch" payload = { "orderIds": ["6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203", "9e31c452-8a2b-42d1-b327-65f18d07dc96"] } headers = { "lmts-api-key": "", "Content-Type": "application/json" } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` ```javascript const options = { method: 'POST', headers: {'lmts-api-key': '', 'Content-Type': 'application/json'}, body: JSON.stringify({ orderIds: ['6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203', '9e31c452-8a2b-42d1-b327-65f18d07dc96'] }) }; fetch('https://api.limitless.exchange/orders/cancel-batch', options) .then(res => res.json()) .then(res => console.log(res)) .catch(err => console.error(err)); ``` ```php "https://api.limitless.exchange/orders/cancel-batch", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode([ 'orderIds' => [ '6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203', '9e31c452-8a2b-42d1-b327-65f18d07dc96' ] ]), CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "lmts-api-key: " ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ``` ```go package main import ( "fmt" "strings" "net/http" "io" ) func main() { url := "https://api.limitless.exchange/orders/cancel-batch" payload := strings.NewReader("{\n \"orderIds\": [\n \"6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203\",\n \"9e31c452-8a2b-42d1-b327-65f18d07dc96\"\n ]\n}") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("lmts-api-key", "") req.Header.Add("Content-Type", "application/json") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` ```java HttpResponse response = Unirest.post("https://api.limitless.exchange/orders/cancel-batch") .header("lmts-api-key", "") .header("Content-Type", "application/json") .body("{\n \"orderIds\": [\n \"6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203\",\n \"9e31c452-8a2b-42d1-b327-65f18d07dc96\"\n ]\n}") .asString(); ``` ```ruby require 'uri' require 'net/http' url = URI("https://api.limitless.exchange/orders/cancel-batch") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Post.new(url) request["lmts-api-key"] = '' request["Content-Type"] = 'application/json' request.body = "{\n \"orderIds\": [\n \"6f52b6d2-6c9e-4a5c-8a4f-28ab4b7ff203\",\n \"9e31c452-8a2b-42d1-b327-65f18d07dc96\"\n ]\n}" response = http.request(request) puts response.read_body ``` -------------------------------- ### Complete Order Management Example Source: https://docs.limitless.exchange/developers/sdk/python/orders Demonstrates initializing the HTTP client, placing different order types, and cleaning up resources. Ensure the HTTP client is closed after operations to prevent resource leaks. ```python import asyncio import os from eth_account import Account from limitless_sdk.api import HttpClient, APIError from limitless_sdk import HMACCredentials from limitless_sdk.markets import MarketFetcher from limitless_sdk.orders import OrderClient from limitless_sdk.types import Side, OrderType async def main(): http_client = HttpClient( hmac_credentials=HMACCredentials( token_id=os.environ["LMTS_TOKEN_ID"], secret=os.environ["LMTS_TOKEN_SECRET"], ), ) account = Account.from_key("0xYOUR_PRIVATE_KEY") market_fetcher = MarketFetcher(http_client) order_client = OrderClient(http_client, account) try: # Fetch market (caches venue automatically) market = await market_fetcher.get_market("btc-above-100k-march-2025") # Place a GTC BUY order for 10 YES shares at $0.65 result = await order_client.create_order( token_id=market.tokens.yes, price=0.65, size=10.0, side=Side.BUY, order_type=OrderType.GTC, market_slug="btc-above-100k-march-2025", ) print("GTC order placed:", result) # Place a FAK BUY order for 10 YES shares at $0.45 fak_result = await order_client.create_order( token_id=market.tokens.yes, price=0.45, size=10.0, side=Side.BUY, order_type=OrderType.FAK, market_slug="btc-above-100k-march-2025", ) print("FAK order placed:", fak_result) # Place a FOK BUY order spending 5 USDC fok_result = await order_client.create_order( token_id=market.tokens.yes, maker_amount=5.0, side=Side.BUY, order_type=OrderType.FOK, market_slug="btc-above-100k-march-2025", ) print("FOK order placed:", fok_result) # Cancel all orders on this market await order_client.cancel_all(market_slug="btc-above-100k-march-2025") print("All orders cancelled") except APIError as e: print(f"API error — status {e.status_code}: {e.message}") finally: await http_client.close() asyncio.run(main()) ``` -------------------------------- ### Active Market Response Example Source: https://docs.limitless.exchange/api-reference/markets/browse-active Example of a market feed event response containing trade details and user information. ```yaml slug: dollardoge-above-dollar021652-on-sep-1-1200-utc-1756724413009 feedEvents: - eventType: NEW_TRADE timestamp: '2025-09-01T11:30:31.000Z' user: id: 7080 account: '0xea27f6788F083e6070961d3E52A2e596367E04CC' name: GG rankName: Bronze points: '0.00000000' data: title: $DOGE above $0.21652 on Sep 1, 12:00 UTC? address: '0x76d3e2098Be66Aa7E15138F467390f0Eb7349B9b' strategy: Buy outcome: 'NO' contracts: '9.071313' tradeAmount: '5' tradeAmountUSD: '4.999525' marketId: 7495 ``` -------------------------------- ### Initialize Partner Account Client Source: https://docs.limitless.exchange/developers/sdk/go/partner-accounts Configure the client using HMAC credentials with the account_creation scope. ```go import "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" client := limitless.NewClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: tokenID, Secret: secret, }), ) // Use client.PartnerAccounts.* ``` -------------------------------- ### Initialize Root Client with HMAC Credentials Source: https://docs.limitless.exchange/developers/sdk/go/getting-started Use the recommended HMAC credentials for secure authentication with the root client. ```go client := limitless.NewClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: os.Getenv("LMTS_TOKEN_ID"), Secret: os.Getenv("LMTS_TOKEN_SECRET"), }), ) // client.Markets, client.Portfolio, client.Pages, // client.ApiTokens, client.PartnerAccounts, client.DelegatedOrders ``` -------------------------------- ### Complete Market Data Retrieval Example Source: https://docs.limitless.exchange/developers/sdk/go/markets Demonstrates initializing the client, listing active markets, retrieving specific market details, and fetching the orderbook. ```go package main import ( "context" "fmt" "log" "os" limitless "github.com/limitless-labs-group/limitless-exchange-go-sdk/limitless" ) func main() { client := limitless.NewHttpClient( limitless.WithHMACCredentials(limitless.HMACCredentials{ TokenID: os.Getenv("LMTS_TOKEN_ID"), Secret: os.Getenv("LMTS_TOKEN_SECRET"), }), ) marketFetcher := limitless.NewMarketFetcher(client) ctx := context.Background() // List active markets active, err := marketFetcher.GetActiveMarkets(ctx, &limitless.ActiveMarketsParams{Limit: 5}) if err != nil { log.Fatal(err) } for _, m := range active.Data { fmt.Printf("%s — %s\n", m.Title, m.Slug) } // Get a specific market slug := active.Data[0].Slug market, err := marketFetcher.GetMarket(ctx, slug) if err != nil { log.Fatal(err) } fmt.Printf("\nMarket: %s\n", market.Title) fmt.Printf("YES token: %s\n", market.Tokens.Yes) fmt.Printf("NO token: %s\n", market.Tokens.No) // Fetch the orderbook orderbook, err := marketFetcher.GetOrderBook(ctx, slug) if err != nil { log.Fatal(err) } fmt.Printf("\nOrderbook — %d bids, %d asks\n", len(orderbook.Bids), len(orderbook.Asks)) } ```