Predict API (Beta)
  1. Guides
  • FAQs
  • Deployed Contracts
  • Guides
    • Understanding the Orderbook
    • [TS] How to authenticate your API requests
    • [PY] How to authenticate your API requests
    • How to create or cancel orders
  • WebSocket
    • General Information
    • Request Format
    • Response Format
    • Subscription Topics
    • Heartbeats
    • Client Example
  • Authorization
    • Get auth message
      GET
    • Get JWT with valid signature
      POST
  • Categories
    • Get categories
      GET
    • Get category by slug
      GET
    • Get all tags
      GET
  • Markets
    • Get markets
      GET
    • Get market by ID
      GET
    • Get market statistics
      GET
    • Get market last sale information
      GET
    • Get the orderbook for a market
      GET
    • Get market timeseries
      GET
    • Get latest market timeseries value
      GET
  • Orders
    • Get order by hash
      GET
    • Get orders
      GET
    • Get order match events
      GET
    • Remove orders from the orderbook
      POST
    • Create an order
      POST
    • Remove orders by hash
      POST
  • Accounts
    • Get connected account
      GET
    • Get account activity
      GET
    • Set a referral
      POST
  • Positions
    • Get positions
      GET
    • Get positions by address
      GET
  • Search
    • Search categories and markets
      GET
  • OAuth
    • Finalize a OAuth connection
      POST
    • Get the orders for a OAuth connection
      POST
    • Create an order for a OAuth connection
      POST
    • Cancel the orders for a OAuth connection
      POST
    • Get the positions for a OAuth connection
      POST
  • Schemas
    • AccountData
    • Tag
    • AccountResponse
    • TagsResponse
    • ActivityEvent
    • ActivityEventName
    • ActivityOrderData
    • ActivityResponse
    • AuthMessageData
    • AuthMessageResponse
    • AuthTokenData
    • AuthTokenResponse
    • BulletinBoardUpdate
    • BulletinBoardUpdatesResponse
    • CategoriesResponse
    • CategoryResponse
    • CategorySort
    • CategoryStatsData
    • CategoryStatsResponse
    • CategoryStatus
    • CategoryStatusFilter
    • CategoryTranslationData
    • CategoryTranslationFields
    • CategoryTranslationsResponse
    • CategoryWithStats
    • ContractOrder
    • CreateOrderData
    • CreateOrderRequest
    • CreateOrderResponse
    • CreateOrderResponseData
    • CryptoUpDownVariantData
    • ErrorCode
    • ErrorResponse
    • Fee
    • FeeEventData
    • FeeEventsResponse
    • FeeType
    • LastOrderSettled
    • LastSaleData
    • LastSaleResponse
    • Market
    • MarketResponse
    • MarketRewards
    • MarketSort
    • MarketStatsData
    • MarketStatsResponse
    • OAuthCancelOrdersData
    • MarketStatus
    • OAuthCancelOrdersRequest
    • MarketStatusFilter
    • OAuthCancelOrdersResponse
    • OAuthCreateOrderData
    • MarketTimeseries
    • OAuthCreateOrderRequest
    • MarketTimeseriesLatest
    • MarketTradingStatus
    • OAuthCreateOrderResponse
    • OAuthFinalizeData
    • MarketTranslationData
    • OAuthFinalizeRequest
    • MarketType
    • MarketVariant
    • OAuthFinalizeResponse
    • OAuthOrdersData
    • MarketWithStats
    • MarketsResponse
    • OAuthOrdersRequest
    • MatchData
    • OAuthOrdersResponse
    • MatchesResponse
    • OAuthPositionsData
    • Metric
    • OAuthPositionsRequest
    • OAuthPositionsResponse
    • OrderData
    • OrderFillData
    • OrderResponse
    • OrderStatus
    • OrderStatusFilter
    • OrderStrategy
    • OrderbookData
    • OrderbookResponse
    • OrderbooksResponse
    • OrdersResponse
    • Outcome
    • OutcomeSide
    • OutcomeStatus
    • OutcomeTranslation
    • OutcomeVariantData
    • OutcomeVariantData_SportsTeamOutcomeData
    • PendingYieldData
    • PendingYieldResponse
    • PointsInfo
    • PositionData
    • PositionSort
    • PositionsResponse
    • PostAuthRequest
    • RemoveOrdersData
    • PriceFeedProvider
    • RemoveOrdersRequest
    • RemoveOrdersResponse
    • PriceLevel
    • QuoteType
    • ReferralInfo
    • ReferralStatus
    • RemoveOrdersByHashData
    • RemoveOrdersByHashRequest
    • ReservedBalancePolicy
    • Resolution
    • ResolutionProvider
    • RewardPeriod
    • SearchData
    • SearchResponse
    • SelectTeamsRequest
    • SelfTradePreventionStrategy
    • SetReferralData
    • SetReferralRequest
    • SetReferralResponse
    • SportsDataProvider
    • SportsEventTeam
    • SportsFifaFriendliesVariantData
    • SportsFifaWorldCupVariantData
    • SportsNbaVariantData
    • SportsPropsMarketData
    • SportsTeamOutcomeData
    • Team
    • TeamSide
    • TimeseriesData
    • TimeseriesLatestBatchResponse
    • TimeseriesLatestData
    • TimeseriesLatestResponse
    • TimeseriesPoint
    • TimeseriesResponse
    • TweetCountVariantData
    • VariantData
    • VariantData_CryptoUpDownVariantData
    • VariantData_SportsFifaFriendliesVariantData
    • VariantData_SportsFifaWorldCupVariantData
    • VariantData_SportsNbaVariantData
    • VariantData_SportsPropsMarketData
    • VariantData_TweetCountVariantData
  1. Guides

How to create or cancel orders

This guide will demonstrate how to create orders using the Predict's TypeScript SDK.

Sections:#

How to install the SDK
How to set approvals
How to set scoped approvals (per-operation)
How to use a Predict account
How to create a LIMIT order (recommended)
How to create a MARKET order
How to apply slippage
How to redeem positions
How to merge positions
How to convert positions
How to check USDT balance
How to interface with contracts
How to cancel orders
License

How to install the SDK#

This package has ethers v6 as a peer dependency.
See the OrderBuilder class for more in-depth details on each function.
Tip (faster confirmations): ethers' default provider polling interval is 4000ms, so every tx.wait() the SDK does internally (in setApprovals, runApprovals, cancelOrders, redeemPositions, etc.) can take up to ~4s to notice a mined transaction. On a fast chain like BNB, lower it to ~300ms so confirmations feel near-instant:
The interval lives on the provider, so set it on whatever provider you pass in, including a BrowserProvider (e.g. MetaMask): provider.pollingInterval = 300.

Predict Account#

Predict supports interacting with the protocol using either a traditional Externally Owned Account (EOA) or a Smart Wallet ("Predict Account"). If you use the web app, a Smart Wallet is automatically created for you. To interact with your Smart Wallet programmatically using the SDK, follow the example shown in How to use a Predict account.

How to set approvals#

Before trading, you need to set approvals for ERC-1155 (ConditionalTokens) and ERC-20 (USDT). This can be achieved by sending a transaction to the respective contracts (see the Contracts section) and approving both the CTF_EXCHANGE and the NEG_RISK_CTF_EXCHANGE or via the SDK utils.
Contracts: The current deployed contracts can be found either in the Constants.ts file or in the Deployed Contracts documentation.
The following example demonstrates how to set the necessary approvals using the SDK utils.

How to set scoped approvals (per-operation)#

setApprovals() sets every approval for every market type in a single call. For most apps the scoped-approvals API is the better fit, and is the recommended approach whenever you build an approval UI. It returns only the approvals a given operation needs, as a list of plain, self-describing steps you can render as a checklist, pre-check, run with live progress, and gate on user confirmation.
The mental model is simple: everything produces steps, and one runner runs steps.
1.
Describe what the user is about to do with an ApprovalScope (operation, plus isNegRisk / isYieldBearing, and an optional side to narrow a TRADE).
2.
Turn it into an ordered ApprovalStep[] with getApprovalSteps (one operation) or getAllApprovalSteps (everything). Both are pure (no signer, no network access), so you can render the checklist before the wallet is connected.
3.
Run the steps with runApprovals, or drive them yourself with checkApprovals / setApproval.
isNegRisk and isYieldBearing describe the market and can be fetched from the GET /markets (or GET /categories) endpoint.
getApprovalSteps returns the minimal, ordered set for the operation. The labels below are the SDK's default copy (they match the Predict web app). Operations that need no approval return an empty array. |
A TRADE scope covers both order directions by default. Pass side: Side.BUY for just the collateral allowance, or side: Side.SELL for just the ERC-1155 approval. CONVERT is neg-risk only and throws InvalidApprovalOperationError for a standard market.

The ApprovalStep shape#

Each step is plain data, safe to render and serialize:
The label/description are sensible English defaults. For custom wording or i18n, key your own copy off the stable id and ignore them.

Build the steps#

You'll typically build the steps from the same signer-backed OrderBuilder you use to check and run them.
getApprovalSteps and getAllApprovalSteps don't touch the chain, so you can also call them on a signer-less builder (OrderBuilder.make(ChainId.BnbMainnet)) to render the checklist before the wallet is connected. You'll need a signer for everything after (checkApprovals, setApproval, runApprovals).

Run them with progress reporting#

runApprovals(steps, opts) runs the steps in order, deduplicating by id (so you can safely pass a union of scopes or a curated subset). Options:
skipSatisfied (default true): pre-check each step on-chain and skip the ones already in place.
stopOnError (default true): stop after the first failed step.
onProgress: a callback invoked as each step transitions, receiving { step, status, transaction? }.
onProgress reports each step through this lifecycle:
StatusMeaning
checkingreading on-chain whether it's already approved (only when skipSatisfied)
skippedalready in place, nothing sent
submittingtransaction sent, awaiting confirmation
confirmedthe transaction succeeded
failedthe transaction reverted or failed
The returned report is { success, steps }, where each entry is { step, status: "skipped" | "confirmed" | "failed", transaction? } (the transaction carries the receipt for submitted steps):

Render a live checklist (the typical UI flow)#

This is the flow behind an in-app "Approvals" modal: render the steps, mark the ones already done, then run the rest with live updates.
For first-time onboarding, swap getApprovalSteps(scope) for getAllApprovalSteps() to approve everything the protocol could need in one pass. That is the per-step, progress-reportable equivalent of setApprovals() (and a slight superset, since it also includes the split allowances).

Or drive each step yourself#

For full control (e.g. gating each step on a user confirmation), use the per-step primitives. checkApprovals batches the on-chain reads (via multicall) so you can render the initial state in one round-trip.

Notes#

Compose freely. Union step lists to cover several operations at once, e.g. to make a market both trade-ready and splittable: runApprovals([...tradeSteps, ...splitSteps]) (duplicates are removed automatically).
Predict accounts (smart wallets) are supported transparently: every step routes through Kernel.execute when a predictAccount is configured.
Signer requirements. getApprovalSteps and getAllApprovalSteps are pure and need no signer. checkApproval / checkApprovals, setApproval, and runApprovals require one and throw MissingSignerError otherwise.
setApprovals() still exists for the fire-and-forget "approve everything" case where you don't need per-step control or reporting.

How to use a Predict account#

Here's an example of how to use a Predict account to create/cancel orders and set approvals.
1.
Initiate the Privy Wallet: The wallet is needed to sign orders. Can be found in the account settings.
2.
Ensure the Privy Wallet has funds: You will need to add some ETH to be able to set approvals and cancel orders, if needed.
3.
Initialize OrderBuilder: Instantiate the OrderBuilder class by calling OrderBuilder.make.
NOTE: Include the predictAccount address, which is also known as the deposit address.
4.
Set Approvals: Ensure the necessary approvals are set (refer to Set Approvals).
5.
Determine Order Amounts: Use getLimitOrderAmounts to calculate order amounts.
6.
Build Order: Use buildOrder to generate a LIMIT strategy order.
NOTE: Fetch the feeRateBps via the GET /markets endpoint on the REST API
NOTE: Set the signer and maker to the predictAccount address, NOT the signer/privy wallet address.
7.
Generate Typed Data: Call buildTypedData to generate typed data for the order.
8.
Sign Order: Obtain a SignedOrder object by calling signTypedDataOrder.
9.
Compute Order Hash: Compute the order hash using buildTypedDataHash.
This will allow you to perform operations via your Predict Account (via the smart wallet).

How to create a LIMIT order (recommended)#

Here's an example of how to use the OrderBuilder to create and sign a LIMIT strategy buy order:
1.
Create Wallet: The wallet is needed to sign orders.
2.
Initialize OrderBuilder: Instantiate the OrderBuilder class by calling OrderBuilder.make.
3.
Set Approvals: Ensure the necessary approvals are set (refer to Set Approvals).
4.
Determine Order Amounts: Use getLimitOrderAmounts to calculate order amounts.
5.
Build Order: Use buildOrder to generate a LIMIT strategy order.
NOTE: Fetch the feeRateBps via the GET /markets endpoint on the REST API
6.
Generate Typed Data: Call buildTypedData to generate typed data for the order.
7.
Sign Order: Obtain a SignedOrder object by calling signTypedDataOrder.
8.
Compute Order Hash: Compute the order hash using buildTypedDataHash.

How to create a MARKET order#

Similarly to the above, here's the flow to create a MARKET sell order:
1.
Create Wallet: The wallet is needed to sign orders.
2.
Initialize OrderBuilder: Instantiate the OrderBuilder class by calling OrderBuilder.make.
3.
Set Approvals: Ensure the necessary approvals are set (refer to Set Approvals).
4.
Fetch Orderbook: Query the Predict API for the latest orderbook for the market.
5.
Determine Order Amounts: Use getMarketOrderAmounts to calculate order amounts.
6.
Build Order: Call buildOrder to generate a MARKET strategy order.
NOTE: Fetch the feeRateBps via the GET /markets endpoint on the REST API
7.
Generate Typed Data: Use buildTypedData to create typed data for the order.
8.
Sign Order: Obtain a SignedOrder object by calling signTypedDataOrder.
9.
Compute Order Hash: Compute the order hash using buildTypedDataHash.

How to apply slippage#

By default, no additional slippage is applied to the order maker/taker amounts. You can specify a slippage tolerance in basis points (1 bps = 0.01%) to adjust the amounts:
BUY orders: set isMinAmountOut: true so that slippage decreases the takerAmount (minimum shares out), while makerAmount equals the expected cost (avg price × shares). This avoids inflating the USD commitment, allowing you to spend your full wallet balance.
SELL orders: slippage decreases the takerAmount (you're willing to receive less collateral)
Note: Slippage will only be applied if you provide the slippageBps and isMinAmountOut values when submitting your order to the REST API.

How to redeem positions#

The OrderBuilder class provides the redeemPositions method to redeem your positions on the Predict protocol. The method supports all market types through the isNegRisk and isYieldBearing options.
1.
Create a Wallet: Initialize a wallet that will be used to sign the redemption transaction.
2.
Initialize OrderBuilder: Instantiate the OrderBuilder class by calling the static make method.
3.
Redeem Positions: Call the redeemPositions method with the appropriate options.
The conditionId and indexSet can be fetched from the GET /positions endpoint.

How to merge positions#

The OrderBuilder class provides the mergePositions method to combine both outcome tokens back into collateral (USDT). This is useful when you hold equal amounts of both YES and NO positions.
1.
Create a Wallet: Initialize a wallet that will be used to sign the merge transaction.
2.
Initialize OrderBuilder: Instantiate the OrderBuilder class by calling the static make method.
3.
Merge Positions: Call the mergePositions method with the appropriate options.
The conditionId can be fetched from the GET /positions endpoint.

How to convert positions#

The OrderBuilder class provides the convertPositions method to convert NO positions in a NegRisk market into the complementary YES positions plus collateral (USDT). Only NegRisk markets support conversions.
For each amount converted, the selected NO positions are burned and you receive:
amount of the YES position for every other market in the category.
amount * (numberOfNoPositions - 1) of collateral (USDT).
If the market has a fee, it is deducted from both the collateral and the YES tokens.
1.
Create a Wallet: Initialize a wallet that will be used to sign the conversion transaction.
2.
Initialize OrderBuilder: Instantiate the OrderBuilder class by calling the static make method.
3.
Convert Positions: Call the convertPositions method with the appropriate options.
The negRiskOnChainId matches the field of the same name returned by the GET /categories endpoint: the category's on-chain NegRisk market ID, a 32-byte hex string. Note that this is not the numeric id the API uses for markets and categories. The indexSet is a bitmask that selects which NO positions to convert: for each one, set the bit at the market's questionIndex (also returned by the GET /categories and GET /positions endpoints).
Conversions move your NO tokens through the NegRisk adapter, which must be approved as an operator first. See How to set scoped approvals (per-operation) and use the CONVERT operation.

How to check USDT balance#

The method balanceOf allows to easily check the current USDT balance of the connected signer.

How to interface with contracts#

To facilitate interactions with Predict's contracts we expose the necessary instances of each contract, including ABIs and types.
Some other useful utils, ABIs and types exposed by the SDK.

How to cancel orders#

Here's an example on how to cancel orders via the SDK
1.
Fetch Orders: Retrieve your open orders using GET /orders.
2.
Group by isNegRisk and isYieldBearing: Separate orders based on the isNegRisk and isYieldBearing properties.
3.
Cancel Orders: Call the cancel function and provide the orders to cancel and the isNegRisk and isYieldBearing properties.
4.
Check Transaction Success: Check to confirm the transaction was successful.

License#

By contributing to this project, you agree that your contributions will be licensed under the project's MIT License.
Modified at 2026-07-28 15:45:56
Previous
[PY] How to authenticate your API requests
Next
General Information
Built with