> ## Documentation Index
> Fetch the complete documentation index at: https://docs.foresight.now/llms.txt
> Use this file to discover all available pages before exploring further.

# Foresight API Swagger

> This section provides developers with interactive API documentation to explore and test Foresight’s endpoints. It is intended for building integrations, automating workflows, and accessing platform data programmatically.

The core Trade API endpoints are:

**GET** `/trade/markets` - Get all active markets and details (public)

**POST** `/trade/quote` - To get price and number of shares to purchase based on amount to bet (public)

**POST** `/trade` - Create a trade intent and get calldata (AMM) or EIP-712 typed data (CLOB). **Requires a platform API key.**

**POST** `/trade/save` - Send the transaction hash after broadcasting a trade for origin attribution (requires a platform API key)

**GET** `/trade/positions` - Fetch active or resolved positions for a wallet (public)

**POST** `/trade/redeem` - Generate redeem calldata for a resolved market. **Requires a platform API key.**

> **Authentication.** `/trade/markets`, `/trade/quote`, and `/trade/positions` are public. `/trade` and `/trade/redeem` require a platform API key, sent as the `X-Platform-API-Key` header (or `Authorization: Bearer <apiKey>`). Iframe partner tokens are additionally gated on the `trade` / `redeem` capability.

> **`chainId`.** Trading endpoints accept an optional `chainId`; when omitted the API resolves the market's chain automatically and falls back to the default chain for legacy markets. `/trade/complete` (deprecated) requires `chainId`.

Below is the Swagger API yaml for reference:

```yaml theme={null}
openapi: 3.0.3
info:
  title: Trade API
  description: API to enable trading on Foresight
  version: 1.0.0
  contact:
    name: Foresight Team
servers:
  - url: http://localhost:3000
    description: Development server
  - url: https://api.foresight.now
    description: Production server

paths:
  /trade/markets:
    get:
      tags:
        - Trade
      summary: Gets all active markets and details that are available/active for trading
      description: Retrieve all markets available for trading, with details such as marketAddress, outcomePrices (outcome1 for YES, outcome0 for NO), marketEndDate, the marketQuestion, and trading-activity metadata (volume in human USD, transactionCount, createdAt).
      operationId: getTradeableMarkets
      parameters:
        - name: chainId
          in: query
          required: false
          description: Optional chain network id. If omitted, tradeable markets default to the legacy default chain.
          schema:
            type: integer
            minimum: 1
            example: 8453
      responses:
        '200':
          description: Returns list of active markets with details
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/MarketInfoResponseDTO'

  /trade/quote:
    post:
      tags:
        - Trade
      summary: Generates a quote based on the given marketAddress, outcome to bet on (1 for YES, 0 for NO) and amount(USDC). Returns the estimated shares bought for the given amount
      description: Generates a quote based on the given marketAddress, outcome and amount(USDC), with details such as the estimateReturn amount based on the input amount, and the estimatedPricePerShare.
      operationId: getTradeQuote
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TradeDTO'
      responses:
        '200':
          description: Quote generated based on the given marketAddress, outcome and amount(USDC).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradeQuoteResponseDTO'

  /trade:
    post:
      tags:
        - Trade
      summary: Create a trade intent and return execution data. Requires a platform API key.
      description: >
        Reads the market's model (AMM vs CLOB), creates a TransactionIntent, and returns
        the data needed to execute. For AMM markets the response includes an encoded `tx`
        block to sign and send; for CLOB markets it includes an EIP-712 `typedData` block
        to sign. Requires the `X-Platform-API-Key` header (or `Authorization: Bearer <apiKey>`).
      operationId: prepareExecuteTrade
      security:
        - PlatformApiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TradeExecuteDTO'
      responses:
        '201':
          description: Intent created. AMM responses include a `tx` block; CLOB responses include a `typedData` block.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradeIntentResponseDTO'
        '401':
          description: Missing or invalid platform API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestError'
        '404':
          description: Market not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFoundError'

  /trade/redeem:
    post:
      tags:
        - Trade
      summary: Generates redeem calldata necessary for executing a redeem transaction based on given arguments. Requires a platform API key.
      description: "Generates the calldata necessary to execute a redeem transaction for a given resolved market, and the expected return amount in base units. Requires the `X-Platform-API-Key` header (or `Authorization: Bearer <apiKey>`)."
      operationId: prepareExecuteRedeem
      security:
        - PlatformApiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RedeemExecuteDTO'
      responses:
        '201':
          description: Returns the expected return amount in base units and the calldata necessary to execute a redeem transaction for a given resolved market
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RedeemExecuteResponseDTO'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestError'
        '401':
          description: Missing or invalid platform API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestError'
        '404':
          description: Market not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFoundError'

  /trade/save:
    post:
      tags:
        - Trade
      summary: Save a broadcast trade's transaction hash
      description: |
        Send the transaction hash here right after broadcasting a trade. You do not need to wait for the transaction receipt.
      operationId: saveTrade
      parameters:
        - name: X-Platform-API-Key
          in: header
          required: true
          description: Your platform API key
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TradeSaveRequestDTO'
      responses:
        '201':
          description: Trade saved
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TradeSaveResponseDTO'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestError'
        '401':
          description: Missing or invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestError'

  /trade/positions:
    get:
      tags:
        - Trade
      summary: Get positions for a given user, with pagination support
      description: Retrieve user positions (active or resolved) with pagination support.
      operationId: getUserPositions
      parameters:
        - name: walletAddress
          in: query
          required: true
          description: User wallet address
          schema:
            type: string
            pattern: '^0x[a-fA-F0-9]{40}$'
            example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        - name: type
          in: query
          required: true
          description: Filter positions by market status
          schema:
            type: string
            enum: [active, resolved]
            example: 'active'
        - name: pg
          in: query
          required: false
          description: Page number (default 1)
          schema:
            type: integer
            minimum: 1
            default: 1
            example: 1
        - name: ps
          in: query
          required: false
          description: Page size (default 20)
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
            example: 20
      responses:
        '200':
          description: Returns the positions and details for a given user, with pagination support
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserPositionsResponseDTO'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequestError'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InternalServerError'

components:
  schemas:
    TradeType:
      type: string
      enum:
        - Buy
        - Sell
      description: Type of trade operation

    TradeDTO:
      type: object
      required:
        - market
        - amount
        - outcome
        - type
      properties:
        market:
          type: string
          description: Market address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
          pattern: '^0x[a-fA-F0-9]{40}$'
        amount:
          type: string
          description: Amount in USDC in base units
          example: '100000000'
          pattern: '^[0-9]+$'
        outcome:
          type: integer
          description: Outcome selection
          example: 1
          enum: [0, 1]
        type:
          $ref: '#/components/schemas/TradeType'
        chainId:
          type: integer
          description: Optional chain network id. If omitted, the API resolves the market chain automatically and falls back to the default chain for legacy markets.
          minimum: 1
          example: 8453

    TradeExecuteDTO:
      allOf:
        - $ref: '#/components/schemas/TradeDTO'
        - type: object
          required:
            - account
          properties:
            account:
              type: string
              description: User Address
              example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
              pattern: '^0x[a-fA-F0-9]{40}$'

    TradeQuoteResponseDTO:
      type: object
      required:
        - market
        - tokenAddress
        - amount
        - outcome
        - type
        - estimatedReturn
        - estimatedPricePerShare
      properties:
        market:
          type: string
          description: Market address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        tokenAddress:
          type: string
          description: Address of token to call approval on (setApprovalForAll for sell since our market shares are ERC1155)
          example: '0x9F42B4e7A1C16DAF7c09A0ad8F47CF8206C5b9A3'
        amount:
          type: string
          format: bigint
          description: Amount in USDC in base units
          example: '100'
        outcome:
          type: integer
          description: Outcome selection
          example: 1
          enum: [0, 1]
        type:
          $ref: '#/components/schemas/TradeType'
        estimatedReturn:
          type: string
          format: bigint
          description: Estimated return (shares for buy, USDC for sell)
          example: '95.5'
        estimatedPricePerShare:
          type: number
          format: float
          description: Estimated price per share
          example: '0.24'

    TransactionDetailsDTO:
      type: object
      required:
        - to
        - data
        - account
        - value
      properties:
        to:
          type: string
          description: Contract address to send transaction to
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        data:
          type: string
          description: Encoded function call data
          example: '0x1234567890abcdef...'
        account:
          type: string
          description: Account address executing the trade
          example: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6'
        value:
          type: string
          description: Value in wei sent with this transaction (typically 0 for USDC trades)
          example: '0'

    TradeExecuteResponseDTO:
      allOf:
        - $ref: '#/components/schemas/TradeQuoteResponseDTO'
        - type: object
          required:
            - tx
          properties:
            tx:
              $ref: '#/components/schemas/TransactionDetailsDTO'

    TradeSaveRequestDTO:
      type: object
      required:
        - txHash
        - chainId
      properties:
        txHash:
          type: string
          description: Transaction hash from broadcast
          example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'
          pattern: '^0x[a-fA-F0-9]{64}$'
        chainId:
          type: integer
          description: EVM chain id the transaction was sent on
          example: 8453

    TradeSaveResponseDTO:
      type: object
      required:
        - ok
      properties:
        ok:
          type: boolean
          description: Always true
          example: true

    MarketInfoResponseDTO:
      type: object
      required:
        - address
        - question
        - marketType
        - outcome1Price
        - outcome0Price
        - endDate
        - volume
        - transactionCount
        - createdAt
      properties:
        address:
          type: string
          description: Market address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        question:
          type: string
          description: Market question
          example: 'Will Bitcoin reach $100,000 by end of 2024?'
        marketType:
          type: string
          enum: ['AMM', 'CLOB']
          description: >-
            Trading model for this market. AMM → execute via POST /trade
            (returns tx). CLOB → sign the EIP-712 order. A chain can host both,
            so callers must branch on this.
          example: 'AMM'
        outcome1Price:
          type: number
          format: float
          description: Current price for YES outcome
          example: 0.65
        outcome0Price:
          type: number
          format: float
          description: Current price for NO outcome
          example: 0.35
        endDate:
          type: string
          format: date-time
          description: Market group end date
          example: '2024-12-31T23:59:59Z'
        volume:
          type: number
          description: >-
            All-time cumulative trading volume in human USD, already normalized
            by the chain's collateral decimals (raw / 10^chainDecimals) — do NOT
            divide again client-side.
          example: 12345.67
        transactionCount:
          type: integer
          description: All-time cumulative number of trades on this market.
          example: 421
        createdAt:
          type: string
          format: date-time
          description: When this market instance became tradeable on its chain (ISO 8601).
          example: '2024-01-15T08:30:00Z'

    RedeemExecuteDTO:
      type: object
      required:
        - market
        - account
      properties:
        market:
          type: string
          description: Market address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
          pattern: '^0x[a-fA-F0-9]{40}$'
        account:
          type: string
          description: User Address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
          pattern: '^0x[a-fA-F0-9]{40}$'
        chainId:
          type: integer
          description: Optional chain network id. If omitted, the API resolves the market chain automatically and falls back to the default chain for legacy markets.
          minimum: 1
          example: 8453

    RedeemExecuteResponseDTO:
      type: object
      required:
        - tx
        - expectedReturn
        - market
      properties:
        tx:
          $ref: '#/components/schemas/TransactionDetailsDTO'
        expectedReturn:
          type: string
          format: bigint
          description: Expected return amount in base units
          example: '100'
        market:
          type: string
          description: Market address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'

    UserPositionDTO:
      type: object
      required:
        - market
        - tokenAddress
        - amountInvested
        - outcome
        - totalShareAmount
        - question
        - resolutionOutcome
        - marketEndDate
      properties:
        market:
          type: string
          description: Market address
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        tokenAddress:
          type: string
          description: Token address for the market shares
          example: '0x9F42B4e7A1C16DAF7c09A0ad8F47CF8206C5b9A3'
        amountInvested:
          type: number
          description: Amount invested in collateral token (in base units)
          example: 100.5
        outcome:
          type: integer
          description: Outcome index bought (0 for NO, 1 for YES)
          enum: [0, 1]
          example: 1
        totalShareAmount:
          type: number
          description: Total share amount held (in base units)
          example: 95.5
        question:
          type: string
          description: Market question
          example: 'Will Bitcoin reach $100,000 by end of 2024?'
        resolutionOutcome:
          type: integer
          nullable: true
          description: Resolution outcome (0 for NO, 1 for YES, -1 for DRAW/TIE; null if market not resolved)
          enum: [-1, 0, 1]
          example: 1
        marketEndDate:
          type: string
          format: date-time
          nullable: true
          description: Market end date
          example: '2024-12-31T23:59:59Z'

    UserPositionsResponseDTO:
      type: object
      required:
        - positions
        - page
        - pageSize
        - hasPrevious
        - hasNext
        - totalCount
      properties:
        positions:
          type: array
          items:
            $ref: '#/components/schemas/UserPositionDTO'
        page:
          type: integer
          description: Current page number
          example: 1
        pageSize:
          type: integer
          description: Number of items per page
          example: 20
        hasPrevious:
          type: boolean
          description: Whether there is a previous page
          example: false
        hasNext:
          type: boolean
          description: Whether there is a next page
          example: true
        totalCount:
          type: integer
          description: Total number of positions for a given user
          example: 45

    BadRequestError:
      type: object
      required:
        - message
      properties:
        message:
          type: string
          description: Error message
          example: 'Bad request'
        statusCode:
          type: integer
          description: HTTP status code
          example: 400
        error:
          type: string
          description: Error type
          example: 'Bad Request'

    NotFoundError:
      type: object
      required:
        - message
      properties:
        message:
          type: string
          description: Error message
          example: 'Market not found'
        statusCode:
          type: integer
          description: HTTP status code
          example: 404
        error:
          type: string
          description: Error type
          example: 'Not Found'

    InternalServerError:
      type: object
      required:
        - message
      properties:
        message:
          type: string
          description: Error message
          example: 'Failed to get trade quote'
        statusCode:
          type: integer
          description: HTTP status code
          example: 500
        error:
          type: string
          description: Error type
          example: 'Internal Server Error'

    IntentTxDTO:
      type: object
      required:
        - to
        - data
        - value
        - chainId
      properties:
        to:
          type: string
          description: Contract address to send the transaction to (the market address for AMM trades)
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        data:
          type: string
          description: Encoded function call data
          example: '0x1234567890abcdef...'
        value:
          type: string
          description: Value in wei sent with this transaction (typically '0' for USDC trades)
          example: '0'
        chainId:
          type: integer
          description: Chain id the transaction must be submitted on
          example: 8453

    TradeIntentResponseDTO:
      type: object
      required:
        - intentId
        - marketType
        - market
        - outcome
        - amount
        - estimatedReturn
        - price
      properties:
        intentId:
          type: string
          description: ID of the TransactionIntent created for this trade
          example: 'clx1a2b3c4d5e6f7g8h9'
        marketType:
          type: string
          enum: [AMM, CLOB]
          description: Market model. AMM responses carry a `tx` block; CLOB responses carry a `typedData` block.
          example: 'AMM'
        market:
          type: string
          description: Market address (echoed from the request)
          example: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
        outcome:
          type: integer
          enum: [0, 1]
          description: Outcome selection (echoed from the request)
          example: 1
        amount:
          type: string
          description: Amount in USDC base units (echoed from the request)
          example: '100000000'
        estimatedReturn:
          type: string
          format: bigint
          description: Estimated return (shares for buy, USDC for sell) in base units
          example: '95500000'
        price:
          type: number
          format: float
          description: Estimated price per share
          example: 0.24
        tx:
          description: AMM only — encoded transaction to sign and send. Absent for CLOB markets.
          allOf:
            - $ref: '#/components/schemas/IntentTxDTO'
        typedData:
          type: object
          additionalProperties: true
          description: CLOB only — EIP-712 typed data to sign. Absent for AMM markets.

  securitySchemes:
    PlatformApiKey:
      type: apiKey
      in: header
      name: X-Platform-API-Key
      description: "Platform API key. May also be supplied as `Authorization: Bearer <apiKey>`."

tags:
  - name: Trade
    description: Trading endpoints for Foresight. Includes endpoints for getting active markets, generating quotes for trades and getting calldata to execute a trade
```
