clob

package
v1.1.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package clob provides a Go client for the Polymarket CLOB v2 API.

Overview

The CLOB (Central Limit Order Book) v2 API is the primary trading interface for Polymarket. It supports market data queries, order management, position tracking, and RFQ (Request for Quote) workflows.

Authentication Levels

Endpoints require one of three authentication levels:

AuthNone (0) — Public endpoints (market data, orderbook, prices)
AuthL1   (1) — EIP-712 wallet signature (CreateAPIKey, DeriveAPIKey)
AuthL2   (2) — API key + HMAC secret + wallet signature (orders, trades, positions)

Creating a Client

Read-only (public data):

client := clob.NewClient("")
client := clob.NewClient(clob.V2Host)

With full trading access:

client := clob.NewClient("",
    clob.WithCredentials(clob.Credentials{
        Key:        "your-api-key",
        Secret:     "your-api-secret",
        Passphrase: "your-passphrase",
    }),
    clob.WithSigner(polyauth.NewSigner(privateKey)),
    clob.WithChainID(clob.PolygonChainID),
)

The OrderBuilder handles price/size conversion, tick-size validation, neg-risk detection, and EIP-712 signing automatically:

b := clob.NewOrderBuilder(client)

// Limit order — auto-fetches tickSize and negRisk
resp, err := b.CreateAndPostOrderForToken(ctx, clob.OrderArgsV2{
    TokenID: "token-id", Price: "0.50", Size: "10.0", Side: clob.SideBuy,
}, clob.GTC, nil)

// Market order — Amount is USDC for BUY, shares for SELL
resp, err := b.CreateAndPostMarketOrderForToken(ctx, clob.MarketOrderArgsV2{
    TokenID: "token-id", Price: "0.50", Amount: "100", Side: clob.SideBuy,
}, clob.FOK, nil)

The *ForToken methods automatically call GetMarketOptions to retrieve tickSize and negRisk from the CLOB API. For manual control, use:

b.BuildOrder(args, clob.CreateOrderOptions{TickSize: "0.01", NegRisk: false})

OrderBuilder constructs, validates, signs, and optionally submits orders. It does not check balance, allowance, or reserved open order capacity.

Low-Level PostOrder

PostOrder requires a pre-built SignedOrder and auth headers:

client.PostOrder(ctx, clob.PostOrderRequest{Order: signed, Owner: addr, OrderType: clob.GTC})

Market Data (No Auth Required)

market := clob.ClobMarketInfo{ConditionID: "0xabc123"}
client.GetClobMarketInfo(ctx, &market)
book := clob.OrderBookSummary{AssetID: "token-id"}
client.GetOrderBook(ctx, &book)
var mid clob.MidpointResponse
client.GetMidpoint(ctx, "token-id", &mid)
var price clob.PriceResponse
client.GetPrice(ctx, "token-id", clob.Buy, &price)
var tick clob.TickSizeResponse
client.GetTickSize(ctx, "token-id", &tick)

Orders & Trading (AuthL2 Required)

client.PostOrder(ctx, clob.PostOrderRequest{...})
client.PostOrders(ctx, []clob.PostOrderRequest{...}, false, false)
client.CancelOrder(ctx, "order-id")
client.GetOpenOrders(ctx, clob.OpenOrderParams{Market: "0x..."})
client.GetTrades(ctx, clob.TradeParams{...})

RFQ (Request for Quote)

client.CreateRFQRequest(ctx, clob.CreateRFQRequest{...})
client.CreateRFQQuote(ctx, clob.CreateRFQQuoteRequest{...})
client.AcceptRFQRequest(ctx, "request-id")

Rewards & Builder APIs

client.GetEarningsForUserForDay(ctx, date, sigType, "")
client.GetCurrentRewards(ctx, "")
client.GetBuilderFeeRate(ctx, "builder-code")

See README.md for the full endpoint reference.

Index

Constants

View Source
const (
	// ContractAddressCTFExchange is the CTF Exchange V2 contract.
	//
	// Used for normal CLOB order EIP-712 domain separation and settlement of
	// standard, non-negative-risk Polymarket markets.
	ContractAddressCTFExchange = "0xE111180000d2663C0091e4f400237545B87B996B"

	// ContractAddressNegRiskCTFExchange is the negative-risk CTF Exchange V2 contract.
	//
	// Used as the EIP-712 verifying contract when signing orders for negative-risk
	// markets.
	ContractAddressNegRiskCTFExchange = "0xe2222d279d744050d28e00520010520000310F59"

	// ContractAddressNegRiskAdapter is the negative-risk adapter contract.
	//
	// Used by neg-risk conversion/redemption helpers, especially
	// BuildRedeemNegRiskTx and RedeemNegRiskWithDepositWallet.
	ContractAddressNegRiskAdapter = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"

	// ContractAddressConditionalTokens is the Gnosis Conditional Tokens Framework
	// contract used by Polymarket.
	//
	// Used for CTF splitPosition, mergePositions, redeemPositions, collection ID,
	// and ERC-1155 conditional-token flows.
	ContractAddressConditionalTokens = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"
)
View Source
const (
	// ContractAddressPUSD is the pUSD collateral token proxy.
	//
	// Use this address as the collateral token in CTF split/merge/redeem calldata.
	// This is also the token address relevant for collateral balance/allowance
	// checks and deposit-wallet approvals.
	ContractAddressPUSD = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"

	// ContractAddressPUSDImplementation is the pUSD implementation contract.
	//
	// This is mostly useful for audits, debugging, and contract verification. SDK
	// callers should usually interact with ContractAddressPUSD, the proxy address.
	ContractAddressPUSDImplementation = "0x6bBCef9f7ef3B6C592c99e0f206a0DE94Ad0925f"

	// ContractAddressCollateralOnramp is the collateral onramp contract.
	//
	// Used by Polymarket's collateral onboarding/deposit infrastructure. Most CLOB
	// trading flows do not call this contract directly.
	ContractAddressCollateralOnramp = "0x93070a847efEf7F70739046A929D47a521F5B8ee"

	// ContractAddressCollateralOfframp is the collateral offramp contract.
	//
	// Used by Polymarket's collateral withdrawal/offboarding infrastructure. Most
	// CLOB trading flows do not call this contract directly.
	ContractAddressCollateralOfframp = "0x2957922Eb93258b93368531d39fAcCA3B4dC5854"

	// ContractAddressPermissionedRamp is the permissioned ramp contract.
	//
	// Used by Polymarket ramp infrastructure. It is included for completeness and
	// should not be used for normal order signing or CTF split/merge/redeem calls.
	ContractAddressPermissionedRamp = "0xebC2459Ec962869ca4c0bd1E06368272732BCb08"

	// ContractAddressCTFCollateralAdapter is the collateral adapter for standard
	// CTF flows.
	//
	// Included for integrations that need to inspect or interact with collateral
	// adapter flows directly. Normal CTF split/merge/redeem helpers use
	// ConditionalTokens and pUSD instead.
	ContractAddressCTFCollateralAdapter = "0xAdA100Db00Ca00073811820692005400218FcE1f"

	// ContractAddressNegRiskCTFCollateralAdapter is the collateral adapter for
	// negative-risk CTF flows.
	//
	// Included for integrations that need low-level negative-risk collateral
	// adapter access. Normal neg-risk redemption helpers use NegRiskAdapter.
	ContractAddressNegRiskCTFCollateralAdapter = "0xadA2005600Dec949baf300f4C6120000bDB6eAab"
)
View Source
const (
	// ContractAddressGnosisSafeFactory is Polymarket's Gnosis Safe factory.
	//
	// Used by legacy SAFE wallet onboarding and SAFE relayer flows. New API users
	// should prefer deposit wallets when applicable.
	ContractAddressGnosisSafeFactory = "0xaacfeea03eb1561c4e67d661e40682bd20e3541b"

	// ContractAddressPolymarketProxyFactory is Polymarket's proxy wallet factory.
	//
	// Used by legacy PROXY wallet onboarding and PROXY relayer flows.
	ContractAddressPolymarketProxyFactory = "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"

	// ContractAddressDepositWalletFactory is the deposit wallet factory for Polygon
	// mainnet.
	//
	// Used as the "to" address for relayer WALLET-CREATE requests and as the
	// factory address for deterministic deposit wallet derivation. This address is
	// documented in the deposit wallet migration guide, not in the resources/contracts
	// page.
	ContractAddressDepositWalletFactory = "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"
)
View Source
const (
	// ContractAddressUMAAdapter is Polymarket's UMA adapter.
	//
	// Used as the oracle address when deriving CTF condition IDs from question IDs.
	ContractAddressUMAAdapter = "0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74"

	// ContractAddressUMAOptimisticOracle is UMA's Optimistic Oracle contract used
	// in Polymarket resolution infrastructure.
	//
	// Included for integrations that need resolution/audit context. Most SDK callers
	// should use UMAAdapter for condition ID derivation.
	ContractAddressUMAOptimisticOracle = "0xCB1822859cEF82Cd2Eb4E6276C7916e692995130"
)
View Source
const (
	MainnetHost = "https://clob.polymarket.com"
	V2Host      = "https://clob-v2.polymarket.com"
	AmoyHost    = "https://clob-v2.polymarket.com"

	// PolygonChainID is Polygon mainnet, the only chain currently listed by
	// Polymarket's official contract-address documentation.
	PolygonChainID = 137
	AmoyChainID    = 80002

	ZeroBytes32 = "0x0000000000000000000000000000000000000000000000000000000000000000"
	ZeroAddress = "0x0000000000000000000000000000000000000000"
)

Variables

This section is empty.

Functions

func BinaryPartition

func BinaryPartition() []*big.Int

BinaryPartition returns the standard CTF partition for binary Polymarket markets.

The official CTF docs define index set 1 as the first outcome and index set 2 as the second outcome, so split and merge calls for binary markets use [1, 2].

func BuildDepositWalletBatchTypedData added in v1.1.5

func BuildDepositWalletBatchTypedData(
	chainID int64,
	depositWallet string,
	nonce string,
	deadline string,
	calls []relayer.DepositWalletCall,
) (apitypes.TypedData, error)

BuildDepositWalletBatchTypedData returns the EIP-712 typed data used by deposit-wallet WALLET batches.

func BuildDepositWalletOrderTypedData added in v1.1.5

func BuildDepositWalletOrderTypedData(chainID int64, verifyingContract common.Address, order SignedOrder) apitypes.TypedData

BuildDepositWalletOrderTypedData returns the normal CLOB v2 Order typed data.

This is useful for debugging and golden-vector comparison. Deposit wallet orders are not signed directly with this typed data; they are signed through the ERC-7739 wrapper implemented by SignDepositWalletOrder.

func BuildHMACSignature

func BuildHMACSignature(secret string, timestamp int64, method, requestPath string, body []byte) (string, error)

BuildHMACSignature returns the Polymarket L2 HMAC signature for a request.

func CollectionID

func CollectionID(parentCollectionID common.Hash, conditionID common.Hash, indexSet *big.Int) common.Hash

CollectionID computes the CTF collection ID for a condition and index set.

func ConditionID

func ConditionID(oracle common.Address, questionID common.Hash, outcomeSlotCount uint) common.Hash

ConditionID computes the CTF condition ID for oracle, question ID, and slot count.

func GenerateKey

func GenerateKey() (string, error)

GenerateKey creates a new hex-encoded Ethereum private key.

func ParsePrivateKey

func ParsePrivateKey(raw string) (*polyauth.Signer, error)

ParsePrivateKey parses a hex-encoded Ethereum private key into a Polymarket signer.

func PositionID

func PositionID(collateralToken common.Address, collectionID common.Hash) *big.Int

PositionID computes the CTF ERC1155 position ID for a collateral token and collection.

func SignDepositWalletOrder added in v1.1.5

func SignDepositWalletOrder(
	signer *polyauth.Signer,
	chainID int64,
	order *SignedOrder,
	depositWallet common.Address,
	opts ...SignOrderOption,
) error

SignDepositWalletOrder signs a CLOB v2 POLY_1271 order with an owner/session signer.

func SignOrder added in v1.0.2

func SignOrder(signer *polyauth.Signer, chainID int64, order *SignedOrder, opts ...SignOrderOption) error

SignOrder fills missing v2 order defaults and writes the EIP-712 signature into order.

func ValidateBytes32Hex added in v1.0.5

func ValidateBytes32Hex(name, v string) error

ValidateBytes32Hex checks that v is empty or a valid 0x-prefixed bytes32 hex string.

func ValidateHexAddress added in v1.0.7

func ValidateHexAddress(name, value string, allowEmpty bool) error

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Body       []byte
}

func (*APIError) Error

func (e *APIError) Error() string

type AssetType

type AssetType string
const (
	AssetCollateral  AssetType = "COLLATERAL"
	AssetConditional AssetType = "CONDITIONAL"
)

type Auth

type Auth struct {
	Signer        *polyauth.Signer
	ChainID       int64
	Credentials   *Credentials
	UseServerTime bool
}

Auth stores the signer and API credentials used for authenticated CLOB requests.

type BalanceAllowanceParams

type BalanceAllowanceParams struct {
	// AssetType specifies collateral or conditional.
	AssetType AssetType `json:"asset_type" url:"asset_type"`
	// TokenID is the conditional token (required for conditional assets).
	TokenID string `json:"token_id,omitempty" url:"token_id,omitempty"`
	// SignatureType selects the wallet/funder type for balance/allowance lookup/update.
	// For deposit wallet / POLY_1271, set SignatureTypePoly1271.
	SignatureType SignatureType `json:"signature_type,omitempty" url:"signature_type,omitempty"`
}

BalanceAllowanceParams identifies the asset whose balance/allowance cache should be refreshed by CLOB.

For deposit wallet / POLY_1271, set SignatureType to SignatureTypePoly1271. CONDITIONAL assets require TokenID.

type BalanceAllowanceResponse

type BalanceAllowanceResponse struct {
	// Balance is the current token balance.
	Balance Float64 `json:"balance"`
	// Allowance is the approved amount for the exchange contract.
	Allowance Float64 `json:"allowance,omitempty"`
	// Allowances maps spender addresses to approved amounts.
	Allowances map[string]string `json:"allowances,omitempty"`
}

BalanceAllowanceResponse contains user balance and allowance info.

type BanStatus

type BanStatus struct {
	// ClosedOnly is true when the account can only reduce positions.
	ClosedOnly bool `json:"closed_only"`
}

BanStatus reports whether a user is in closed-only mode.

type BatchPriceHistoryParams

type BatchPriceHistoryParams struct {
	// Markets lists the condition IDs to query.
	Markets []string `json:"markets"`
	// StartTS is the start Unix timestamp.
	StartTS int64 `json:"start_ts,omitempty"`
	// EndTS is the end Unix timestamp.
	EndTS int64 `json:"end_ts,omitempty"`
	// Fidelity controls the data point density.
	Fidelity int `json:"fidelity,omitempty"`
	// Interval sets the bucket size (e.g. "5m", "1h").
	Interval string `json:"interval,omitempty"`
}

BatchPriceHistoryParams is the request body for POST /batch-prices-history.

type BatchPriceHistoryResponse

type BatchPriceHistoryResponse struct {
	History map[string][]PricePoint `json:"history"`
}

BatchPriceHistoryResponse contains historical price points keyed by market asset ID.

type BookParams

type BookParams struct {
	// TokenID is the conditional token identifier.
	TokenID string `json:"token_id" url:"token_id"`
	// Side filters by buy or sell, empty means both.
	Side Side `json:"side,omitempty" url:"side,omitempty"`
}

BookParams identifies a token/side combination for bulk price queries.

type BuilderAPIKey

type BuilderAPIKey struct {
	// Key is the API key value.
	Key string `json:"key"`
	// CreatedAt is when the key was created.
	CreatedAt Time `json:"createdAt"`
	// RevokedAt is when the key was revoked, zero if active.
	RevokedAt Time `json:"revokedAt"`
}

BuilderAPIKey describes a builder API key.

type BuilderFeeRate

type BuilderFeeRate struct {
	// BuilderMakerFeeRateBps is the maker fee in basis points.
	BuilderMakerFeeRateBps Int `json:"builderMakerFeeRateBps"`
	// BuilderTakerFeeRateBps is the taker fee in basis points.
	BuilderTakerFeeRateBps Int `json:"builderTakerFeeRateBps"`
}

BuilderFeeRate contains the fee rates for a builder.

type BuilderTrade

type BuilderTrade struct {
	// ID is the trade identifier.
	ID string `json:"id"`
	// TradeType identifies the trade category.
	TradeType string `json:"tradeType"`
	// TakerOrderHash is the taker order hash.
	TakerOrderHash string `json:"takerOrderHash"`
	// Builder is the builder code.
	Builder string `json:"builder"`
	// Market is the condition ID.
	Market string `json:"market"`
	// AssetID is the conditional token identifier.
	AssetID String `json:"assetId"`
	// Side is the trade direction.
	Side Side `json:"side"`
	// Size is the matched quantity.
	Size Float64 `json:"size"`
	// SizeUSDC is the quantity in USDC.
	SizeUSDC Float64 `json:"sizeUsdc"`
	// Price is the execution price.
	Price Float64 `json:"price"`
	// Status is the trade processing status.
	Status string `json:"status"`
	// Outcome is the outcome label.
	Outcome string `json:"outcome"`
	// OutcomeIndex is the 0-based index of the outcome.
	OutcomeIndex Int `json:"outcomeIndex"`
	// Owner is the trade owner address.
	Owner string `json:"owner"`
	// Maker is the maker wallet address.
	Maker string `json:"maker"`
	// TransactionHash is the on-chain transaction hash.
	TransactionHash string `json:"transactionHash"`
	// MatchTime is when the trade was matched.
	MatchTime Time `json:"matchTime"`
	// BucketIndex is the price bucket index.
	BucketIndex Int `json:"bucketIndex"`
	// Fee is the fee amount.
	Fee Float64 `json:"fee"`
	// FeeUSDC is the fee in USDC.
	FeeUSDC Float64 `json:"feeUsdc"`
	// ErrMsg contains error details on failure.
	ErrMsg string `json:"errMsg"`
	// CreatedAt is when the trade record was created.
	CreatedAt Time `json:"createdAt"`
	// UpdatedAt is the last record update.
	UpdatedAt Time `json:"updatedAt"`
}

BuilderTrade represents a trade attributed to a builder.

type BuilderTradeParams

type BuilderTradeParams struct {
	// ID filters by trade identifier.
	ID string `url:"id,omitempty"`
	// MakerAddress filters by maker wallet address.
	MakerAddress string `url:"maker,omitempty"`
	// Market filters by condition ID.
	Market string `url:"market,omitempty"`
	// AssetID filters by conditional token identifier.
	AssetID string `url:"asset_id,omitempty"`
	// Before filters trades before this Unix timestamp.
	Before int64 `url:"before,omitempty"`
	// After filters trades after this Unix timestamp.
	After int64 `url:"after,omitempty"`
	// BuilderCode filters by builder attribution code.
	BuilderCode string `url:"builder_code,omitempty"`
	// NextCursor is the pagination cursor.
	NextCursor string `url:"next_cursor,omitempty"`
}

BuilderTradeParams filters GET /builder/trades requests.

type CTFRelayerArgs added in v1.1.4

type CTFRelayerArgs struct {
	// Type selects SAFE or PROXY relayer signing.
	Type relayer.NonceType
	// From is the EOA signer address. If empty, client signer address is used.
	From string
	// ProxyWallet is the user's Polymarket proxy wallet / funder address.
	ProxyWallet string
	// Metadata is optional relayer metadata.
	Metadata string
	// GasLimit optionally overrides the computed proxy gas limit.
	GasLimit string
}

CTFRelayerArgs contains high-level relayer options for CTF calls.

type CTFTransaction

type CTFTransaction struct {
	// To is the contract address that should receive the transaction.
	To common.Address
	// Data is the ABI-encoded calldata.
	Data []byte
}

CTFTransaction contains the destination contract and calldata for a CTF operation.

type CancelOrdersResponse

type CancelOrdersResponse struct {
	// Canceled lists successfully canceled order IDs.
	Canceled []string `json:"canceled"`
	// NotCanceled maps failed order IDs to error messages.
	NotCanceled map[string]string `json:"not_canceled"`
}

CancelOrdersResponse reports cancellation results.

type CancelRFQQuoteRequest

type CancelRFQQuoteRequest struct {
	// QuoteID identifies the quote to cancel.
	QuoteID string `json:"quoteId"`
}

CancelRFQQuoteRequest is the body for DELETE /rfq/quote.

type CancelRFQRequest

type CancelRFQRequest struct {
	// RequestID identifies the RFQ to cancel.
	RequestID string `json:"requestId"`
}

CancelRFQRequest is the body for DELETE /rfq/request.

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(host string, opts ...Option) *Client

NewClient creates a CLOB client for host.

func (*Client) AcceptRFQRequest

func (c *Client) AcceptRFQRequest(ctx context.Context, requestID string) error

AcceptRFQRequest accepts a pending request-for-quote by its ID. Requires L2 auth.

func (*Client) ApproveRFQQuote

func (c *Client) ApproveRFQQuote(ctx context.Context, quoteID string) (map[string]any, error)

ApproveRFQQuote approves an RFQ quote for execution by its ID. Requires L2 auth.

func (*Client) AreOrdersScoring

func (c *Client) AreOrdersScoring(ctx context.Context, orderIDs []string) (map[string]bool, error)

AreOrdersScoring checks scoring status for multiple orders in a batch. Requires L2 auth.

func (*Client) BuildCTFRelayerRequest added in v1.1.4

func (c *Client) BuildCTFRelayerRequest(
	ctx context.Context,
	tx *CTFTransaction,
	req *CTFRelayerArgs,
	out *RelayerCTFRequest,
) error

BuildCTFRelayerRequest builds and signs a PROXY relayer request for built CTF calldata.

func (*Client) BuildMergePositionsTx

func (c *Client) BuildMergePositionsTx(req *MergePositionsRequest, out *CTFTransaction) error

BuildMergePositionsTx writes the destination and calldata for mergePositions into out.

func (*Client) BuildRedeemNegRiskTx

func (c *Client) BuildRedeemNegRiskTx(req *RedeemNegRiskRequest, out *CTFTransaction) error

BuildRedeemNegRiskTx writes the destination and calldata for V2 neg-risk redemption through the NegRiskCTFCollateralAdapter.

It uses the CTF-compatible redeemPositions(address,bytes32,bytes32,uint256[]) adapter interface. RedeemNegRiskRequest.Amounts is ignored on this V2 path.

func (*Client) BuildRedeemPositionsTx

func (c *Client) BuildRedeemPositionsTx(req *RedeemPositionsRequest, out *CTFTransaction) error

BuildRedeemPositionsTx writes the destination and calldata for redeemPositions into out.

func (*Client) BuildSplitPositionTx

func (c *Client) BuildSplitPositionTx(req *SplitPositionRequest, out *CTFTransaction) error

BuildSplitPositionTx writes the destination and calldata for splitPosition into out.

func (*Client) CTFDepositWalletTransactionRequest added in v1.1.5

func (c *Client) CTFDepositWalletTransactionRequest(
	ctx context.Context,
	tx *CTFTransaction,
	args *DepositWalletCTFArgs,
	out *relayer.SubmitTransactionRequest,
) error

CTFDepositWalletTransactionRequest wraps a CTF transaction into a signed deposit-wallet WALLET batch relayer request.

func (*Client) CancelAll

func (c *Client) CancelAll(ctx context.Context, out *CancelOrdersResponse) error

CancelAll cancels all open orders for the authenticated user. Requires L2 auth.

func (*Client) CancelMarketOrders

func (c *Client) CancelMarketOrders(ctx context.Context, params OrderMarketCancelParams, out *CancelOrdersResponse) error

CancelMarketOrders cancels all open orders for a specific market or side. Requires L2 auth.

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, orderID string, out *CancelOrdersResponse) error

CancelOrder cancels a single order by its ID. Requires L2 auth.

func (*Client) CancelOrders

func (c *Client) CancelOrders(ctx context.Context, orderIDs []string, out *CancelOrdersResponse) error

CancelOrders cancels multiple orders by their IDs. Requires L2 auth.

func (*Client) CancelRFQQuote

func (c *Client) CancelRFQQuote(ctx context.Context, quoteID string) error

CancelRFQQuote cancels a previously created RFQ quote by its ID. Requires L2 auth.

func (*Client) CancelRFQRequest

func (c *Client) CancelRFQRequest(ctx context.Context, requestID string) error

CancelRFQRequest cancels an outstanding request-for-quote by its ID. Requires L2 auth.

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, nonce int64, out *Credentials) error

CreateAPIKey generates a new L2 API key pair for the authenticated user. Requires L1 auth (wallet-signed). The nonce is a unique timestamp-based identifier.

func (*Client) CreateBuilderAPIKey

func (c *Client) CreateBuilderAPIKey(ctx context.Context, out *Credentials) error

CreateBuilderAPIKey generates an API key for builder/developer applications. Requires L2 auth.

func (*Client) CreateRFQQuote

func (c *Client) CreateRFQQuote(ctx context.Context, req CreateRFQQuoteRequest) (map[string]any, error)

CreateRFQQuote creates a quote response to an existing request-for-quote. Requires L2 auth.

func (*Client) CreateRFQRequest

func (c *Client) CreateRFQRequest(ctx context.Context, req CreateRFQRequest) (map[string]any, error)

CreateRFQRequest creates a new request-for-quote to solicit liquidity from market makers. Requires L2 auth.

func (*Client) CreateReadonlyAPIKey

func (c *Client) CreateReadonlyAPIKey(ctx context.Context, out *ReadonlyAPIKey) error

CreateReadonlyAPIKey generates a read-only API key for market data access. Requires L2 auth.

func (*Client) Credentials added in v1.0.7

func (c *Client) Credentials() *Credentials

func (*Client) DeleteAPIKey

func (c *Client) DeleteAPIKey(ctx context.Context) error

DeleteAPIKey revokes the currently active API key. Requires L2 auth.

func (*Client) DeleteReadonlyAPIKey

func (c *Client) DeleteReadonlyAPIKey(ctx context.Context, key string) error

DeleteReadonlyAPIKey revokes a read-only API key by its key string. Requires L2 auth.

func (*Client) DeployDepositWallet added in v1.1.5

func (c *Client) DeployDepositWallet(ctx context.Context, out *relayer.SubmitTransactionResponse) error

DeployDepositWallet submits a WALLET-CREATE request through the configured relayer.

func (*Client) DepositWalletBatch added in v1.1.5

func (c *Client) DepositWalletBatch(
	ctx context.Context,
	args *DepositWalletBatchArgs,
	out *relayer.SubmitTransactionResponse,
) error

DepositWalletBatch builds, signs, and submits a WALLET batch through the configured relayer.

func (*Client) DepositWalletBatchRelayerRequest added in v1.1.5

func (c *Client) DepositWalletBatchRelayerRequest(
	ctx context.Context,
	args *DepositWalletBatchArgs,
	out *relayer.SubmitTransactionRequest,
) error

DepositWalletBatchRelayerRequest builds and signs a WALLET relayer submit request.

This is the deposit-wallet batch path. The signature is a normal 65-byte EIP-712 signature over the DepositWallet Batch typed data. It is not the ERC-7739 wrapped CLOB order signature used by SignatureTypePoly1271 orders.

func (*Client) DepositWalletCreateRelayerRequest added in v1.1.5

func (c *Client) DepositWalletCreateRelayerRequest(out *relayer.SubmitTransactionRequest) error

func (*Client) DeriveAPIKey

func (c *Client) DeriveAPIKey(ctx context.Context, nonce int64, out *Credentials) error

DeriveAPIKey derives an existing API key's credentials from a nonce. Requires L1 auth (wallet-signed).

func (*Client) DropNotifications

func (c *Client) DropNotifications(ctx context.Context, params DropNotificationParams) error

DropNotifications marks notifications as read by their IDs. Requires L2 auth.

func (*Client) GetAPIKeys

func (c *Client) GetAPIKeys(ctx context.Context) ([]Credentials, error)

GetAPIKeys lists all active API keys for the authenticated user. Requires L2 auth.

func (*Client) GetBalanceAllowance

func (c *Client) GetBalanceAllowance(ctx context.Context, params BalanceAllowanceParams, out *BalanceAllowanceResponse) error

GetBalanceAllowance checks the user's token balance and allowance for trading. Requires L2 auth.

func (*Client) GetBatchPricesHistory

func (c *Client) GetBatchPricesHistory(ctx context.Context, params BatchPriceHistoryParams, out *BatchPriceHistoryResponse) error

GetBatchPricesHistory retrieves historical price data for multiple tokens in a batch request.

func (*Client) GetBuilderAPIKeys

func (c *Client) GetBuilderAPIKeys(ctx context.Context) ([]BuilderAPIKey, error)

GetBuilderAPIKeys lists all active builder API keys. Requires L2 auth.

func (*Client) GetBuilderFeeRate

func (c *Client) GetBuilderFeeRate(ctx context.Context, builderCode string, out *BuilderFeeRate) error

GetBuilderFeeRate returns the fee rate configuration for a builder's referral code. No authentication required.

func (*Client) GetBuilderTrades

func (c *Client) GetBuilderTrades(ctx context.Context, params BuilderTradeParams, out *Page[BuilderTrade]) error

GetBuilderTrades retrieves trade history for a builder's referral code, paginated. Requires L2 auth.

func (*Client) GetClobMarketInfo

func (c *Client) GetClobMarketInfo(ctx context.Context, out *ClobMarketInfo) error

GetClobMarketInfo fetches CLOB-specific metadata for a market by condition ID. The out parameter must have ConditionID set.

func (*Client) GetClosedOnlyMode

func (c *Client) GetClosedOnlyMode(ctx context.Context, out *BanStatus) error

GetClosedOnlyMode returns whether the user's account is in closed-only (restricted) mode. Requires L2 auth.

func (*Client) GetCurrentRebates

func (c *Client) GetCurrentRebates(ctx context.Context, params RebateParams) ([]Rebate, error)

GetCurrentRebates returns the current rebate rates for the authenticated user.

func (*Client) GetCurrentRewards

func (c *Client) GetCurrentRewards(ctx context.Context, cursor string, out *Page[CurrentReward]) error

GetCurrentRewards retrieves active reward campaigns for markets, paginated. No authentication required.

func (*Client) GetEarningsForUserForDay

func (c *Client) GetEarningsForUserForDay(ctx context.Context, date string, signatureType SignatureType, cursor string, out *Page[UserEarning]) error

GetEarningsForUserForDay returns the user's reward earnings for a specific date. Requires L2 auth.

func (*Client) GetFeeRate

func (c *Client) GetFeeRate(ctx context.Context, tokenID string, out *FeeRateResponse) error

GetFeeRate returns the trading fee rate for a single token.

func (*Client) GetFeeRateByTokenID

func (c *Client) GetFeeRateByTokenID(ctx context.Context, tokenID string, out *FeeRateResponse) error

GetFeeRateByTokenID returns the trading fee rate for a token by its ID.

func (*Client) GetLastTradePrice

func (c *Client) GetLastTradePrice(ctx context.Context, tokenID string, out *LastTradePriceResponse) error

GetLastTradePrice returns the most recent trade price for a single token.

func (*Client) GetLastTradesPrices

func (c *Client) GetLastTradesPrices(ctx context.Context, books []BookParams) ([]LastTradesPricesResponse, error)

GetLastTradesPrices returns the most recent trade prices for multiple tokens in a batch.

func (*Client) GetMarket

func (c *Client) GetMarket(ctx context.Context, out *Market) error

GetMarket fetches a single market by its condition ID. The out parameter must have ConditionID set.

func (*Client) GetMarketByToken

func (c *Client) GetMarketByToken(ctx context.Context, out *MarketByToken) error

GetMarketByToken fetches market data by token ID instead of condition ID. The out parameter must have either PrimaryTokenID or SecondaryTokenID set.

func (*Client) GetMarketTradesEvents

func (c *Client) GetMarketTradesEvents(ctx context.Context, conditionID string) ([]Trade, error)

GetMarketTradesEvents retrieves live trade activity events for a market by condition ID. No authentication required.

func (*Client) GetMarkets

func (c *Client) GetMarkets(ctx context.Context, cursor string, out *Page[Market]) error

GetMarkets retrieves all markets with full details, paginated.

func (*Client) GetMidpoint

func (c *Client) GetMidpoint(ctx context.Context, tokenID string, out *MidpointResponse) error

GetMidpoint calculates the midpoint price for a single token.

func (*Client) GetMidpoints

func (c *Client) GetMidpoints(ctx context.Context, books []BookParams) (map[string]Float64, error)

GetMidpoints calculates midpoint prices for multiple tokens in a batch.

func (*Client) GetNegRisk

func (c *Client) GetNegRisk(ctx context.Context, tokenID string, out *NegRiskResponse) error

GetNegRisk returns whether a token has negative risk configuration.

func (*Client) GetNotifications

func (c *Client) GetNotifications(ctx context.Context) ([]Notification, error)

GetNotifications fetches pending notifications for the authenticated user. Requires L2 auth.

func (*Client) GetOk

func (c *Client) GetOk(ctx context.Context) (string, error)

GetOk performs a health check against the CLOB API. Returns a simple pong response string.

func (*Client) GetOpenOrders

func (c *Client) GetOpenOrders(ctx context.Context, params OpenOrderParams) ([]OpenOrder, error)

GetOpenOrders returns open orders for the current page only. Use GetOpenOrdersPage when you need next_cursor pagination metadata. Requires L2 auth.

func (*Client) GetOpenOrdersPage added in v1.1.1

func (c *Client) GetOpenOrdersPage(ctx context.Context, params OpenOrderParams) (*Page[OpenOrder], error)

GetOpenOrdersPage returns open orders with next_cursor pagination metadata. Requires L2 auth.

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, out *OpenOrder) error

GetOrder fetches a single order by its ID. The out parameter must have ID set. Requires L2 auth.

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(ctx context.Context, out *OrderBookSummary) error

GetOrderBook fetches the order book for a single token. The out parameter must have AssetID set.

func (*Client) GetOrderBooks

func (c *Client) GetOrderBooks(ctx context.Context, books []BookParams) ([]OrderBookSummary, error)

GetOrderBooks fetches order books for multiple tokens in a single batch request.

func (*Client) GetPreMigrationOrders

func (c *Client) GetPreMigrationOrders(ctx context.Context, params OpenOrderParams) ([]OpenOrder, error)

GetPreMigrationOrders lists open orders from before the CLOB v2 migration. Requires L2 auth.

func (*Client) GetPrice

func (c *Client) GetPrice(ctx context.Context, tokenID string, side Side, out *PriceResponse) error

GetPrice returns the last price for a specific token and side (buy/sell).

func (*Client) GetPrices

func (c *Client) GetPrices(ctx context.Context, books []BookParams) (map[string]map[Side]Float64, error)

GetPrices returns last prices for multiple tokens and both sides in a batch.

func (*Client) GetPricesHistory

func (c *Client) GetPricesHistory(ctx context.Context, params PriceHistoryParams, out *PriceHistoryResponse) error

GetPricesHistory retrieves historical price data for a token from /prices-history.

func (*Client) GetRFQBestQuote

func (c *Client) GetRFQBestQuote(ctx context.Context, params RFQListParams, out *RfqQuote) error

GetRFQBestQuote returns the best available quote matching the given parameters. Requires L2 auth.

func (*Client) GetRFQConfig

func (c *Client) GetRFQConfig(ctx context.Context) (map[string]any, error)

GetRFQConfig returns the current RFQ configuration for the authenticated user. No authentication required.

func (*Client) GetRFQQuoterQuotes

func (c *Client) GetRFQQuoterQuotes(ctx context.Context, params RFQListParams, out *Page[RfqQuote]) error

GetRFQQuoterQuotes lists quotes provided by the user as a quoter, paginated. Requires L2 auth.

func (*Client) GetRFQRequesterQuotes

func (c *Client) GetRFQRequesterQuotes(ctx context.Context, params RFQListParams, out *Page[RfqQuote]) error

GetRFQRequesterQuotes lists quotes received by the user as a requester, paginated. Requires L2 auth.

func (*Client) GetRFQRequests

func (c *Client) GetRFQRequests(ctx context.Context, params RFQListParams, out *Page[RfqRequest]) error

GetRFQRequests lists all request-for-quote entries for the authenticated user. Requires L2 auth.

func (*Client) GetReadonlyAPIKeys

func (c *Client) GetReadonlyAPIKeys(ctx context.Context) ([]ReadonlyAPIKey, error)

GetReadonlyAPIKeys lists all active read-only API keys. Requires L2 auth.

func (*Client) GetRewardPercentages

func (c *Client) GetRewardPercentages(ctx context.Context, signatureType SignatureType) (map[string]Float64, error)

GetRewardPercentages returns the reward percentage multiplier for each market. Requires L2 auth.

func (*Client) GetRewardsForMarket

func (c *Client) GetRewardsForMarket(ctx context.Context, conditionID, cursor string, out *Page[MarketReward]) error

GetRewardsForMarket retrieves reward information for a specific market by condition ID. No authentication required.

func (*Client) GetSamplingMarkets

func (c *Client) GetSamplingMarkets(ctx context.Context, cursor string, out *Page[Market]) error

GetSamplingMarkets retrieves a paginated list of sampled markets with full details.

func (*Client) GetSamplingSimplifiedMarkets

func (c *Client) GetSamplingSimplifiedMarkets(ctx context.Context, cursor string, out *Page[SimplifiedMarket]) error

GetSamplingSimplifiedMarkets retrieves a paginated list of sampled simplified markets.

func (*Client) GetServerTime

func (c *Client) GetServerTime(ctx context.Context) (int64, error)

GetServerTime returns the CLOB server's current Unix timestamp. Useful for clock synchronization when UseServerTime is enabled.

func (*Client) GetSimplifiedMarkets

func (c *Client) GetSimplifiedMarkets(ctx context.Context, cursor string, out *Page[SimplifiedMarket]) error

GetSimplifiedMarkets retrieves all markets in simplified format, paginated.

func (*Client) GetSpread

func (c *Client) GetSpread(ctx context.Context, tokenID string, out *SpreadResponse) error

GetSpread returns the bid-ask spread for a single token.

func (*Client) GetSpreads

func (c *Client) GetSpreads(ctx context.Context, books []BookParams) (map[string]Float64, error)

GetSpreads returns bid-ask spreads for multiple tokens in a batch.

func (*Client) GetTickSize

func (c *Client) GetTickSize(ctx context.Context, tokenID string, out *TickSizeResponse) error

GetTickSize returns the minimum price increment for a single token.

func (*Client) GetTickSizeByTokenID

func (c *Client) GetTickSizeByTokenID(ctx context.Context, tokenID string, out *TickSizeResponse) error

GetTickSizeByTokenID returns the minimum price increment for a token by its ID.

func (*Client) GetTotalEarningsForUserForDay

func (c *Client) GetTotalEarningsForUserForDay(ctx context.Context, date string, signatureType SignatureType, out *UserEarning) error

GetTotalEarningsForUserForDay returns the user's total reward earnings for a specific date. Requires L2 auth.

func (*Client) GetTrades

func (c *Client) GetTrades(ctx context.Context, params TradeParams) ([]Trade, error)

GetTrades lists trade history for the authenticated user. Requires L2 auth.

func (*Client) GetUserEarningsAndMarketsConfig

func (c *Client) GetUserEarningsAndMarketsConfig(ctx context.Context, params EarningsParams, signatureType SignatureType, out *Page[UserRewardsEarning]) error

GetUserEarningsAndMarketsConfig returns the user's earnings combined with market reward configuration. Requires L2 auth.

func (*Client) GetVersion

func (c *Client) GetVersion(ctx context.Context) (int, error)

GetVersion returns the current CLOB API version.

func (*Client) Host

func (c *Client) Host() string

func (*Client) IsOrderScoring

func (c *Client) IsOrderScoring(ctx context.Context, orderID string, out *OrderScoring) error

IsOrderScoring checks whether a specific order is currently being scored by the matching engine. Requires L2 auth.

func (*Client) MergePositions

func (c *Client) MergePositions(ctx context.Context, req *MergePositionsRequest, out *TxReceipt) error

MergePositions submits a mergePositions transaction and writes its receipt into out.

func (*Client) MergePositionsRelayer added in v1.1.4

func (c *Client) MergePositionsRelayer(
	ctx context.Context,
	req *MergePositionsRequest,
	relayerReq *CTFRelayerArgs,
	out *relayer.SubmitTransactionResponse,
) error

MergePositionsRelayer builds a mergePositions transaction, signs a PROXY relayer request, and submits it through the configured relayer.

func (*Client) MergePositionsWithDepositWallet added in v1.1.5

func (c *Client) MergePositionsWithDepositWallet(
	ctx context.Context,
	req *MergePositionsRequest,
	args *DepositWalletCTFArgs,
	out *relayer.SubmitTransactionResponse,
) error

MergePositionsWithDepositWallet builds, signs, and submits a mergePositions call through a deposit-wallet WALLET transaction.

func (*Client) NormalizeCollateralToken added in v1.1.5

func (c *Client) NormalizeCollateralToken(collateral common.Address) (common.Address, error)

func (*Client) PostHeartbeat

func (c *Client) PostHeartbeat(ctx context.Context, heartbeatID string, out *HeartbeatResponse) error

PostHeartbeat sends a heartbeat signal to maintain an active connection state. Requires L2 auth.

func (*Client) PostOrder

func (c *Client) PostOrder(ctx context.Context, req PostOrderRequest, out *PostOrderResponse) error

PostOrder submits a single order to the order book. Requires L2 auth.

func (*Client) PostOrders

func (c *Client) PostOrders(ctx context.Context, reqs []PostOrderRequest, postOnly, deferExec bool) ([]PostOrderResponse, error)

PostOrders submits multiple orders in a single batch request. When postOnly is true, orders that would match against the book are cancelled. When deferExec is true, order execution is deferred for later processing. Requires L2 auth.

func (*Client) RedeemNegRisk

func (c *Client) RedeemNegRisk(ctx context.Context, req *RedeemNegRiskRequest, out *TxReceipt) error

RedeemNegRisk submits a neg-risk adapter redemption transaction and writes its receipt into out.

func (*Client) RedeemNegRiskRelayer added in v1.1.4

func (c *Client) RedeemNegRiskRelayer(
	ctx context.Context,
	req *RedeemNegRiskRequest,
	relayerReq *CTFRelayerArgs,
	out *relayer.SubmitTransactionResponse,
) error

RedeemNegRiskRelayer builds a neg-risk redeemPositions transaction, signs a PROXY relayer request, and submits it through the configured relayer.

func (*Client) RedeemNegRiskWithDepositWallet added in v1.1.5

func (c *Client) RedeemNegRiskWithDepositWallet(
	ctx context.Context,
	req *RedeemNegRiskRequest,
	args *DepositWalletCTFArgs,
	out *relayer.SubmitTransactionResponse,
) error

RedeemNegRiskWithDepositWallet builds, signs, and submits a neg-risk redeemPositions call through a deposit-wallet WALLET transaction.

func (*Client) RedeemPositions

func (c *Client) RedeemPositions(ctx context.Context, req *RedeemPositionsRequest, out *TxReceipt) error

RedeemPositions submits a redeemPositions transaction and writes its receipt into out.

func (*Client) RedeemPositionsRelayer added in v1.1.4

func (c *Client) RedeemPositionsRelayer(
	ctx context.Context,
	req *RedeemPositionsRequest,
	relayerReq *CTFRelayerArgs,
	out *relayer.SubmitTransactionResponse,
) error

RedeemPositionsRelayer builds a redeemPositions transaction, signs a PROXY relayer request, and submits it through the configured relayer.

func (*Client) RedeemPositionsWithDepositWallet added in v1.1.5

func (c *Client) RedeemPositionsWithDepositWallet(
	ctx context.Context,
	req *RedeemPositionsRequest,
	args *DepositWalletCTFArgs,
	out *relayer.SubmitTransactionResponse,
) error

RedeemPositionsWithDepositWallet builds, signs, and submits a redeemPositions call through a deposit-wallet WALLET transaction.

func (*Client) ResolveSignatureType added in v1.1.3

func (c *Client) ResolveSignatureType(signatureType *SignatureType) SignatureType

func (*Client) RevokeBuilderAPIKey

func (c *Client) RevokeBuilderAPIKey(ctx context.Context) error

RevokeBuilderAPIKey revokes the active builder API key. Requires L2 auth.

func (*Client) SignDepositWalletOrder added in v1.1.5

func (c *Client) SignDepositWalletOrder(order *SignedOrder, depositWallet common.Address, opts ...SignOrderOption) error

SignDepositWalletOrder signs a CLOB v2 order for a deposit wallet.

This is the POLY_1271 / signatureType=3 path. The order maker and signer fields must both be the deposit wallet address, while the cryptographic signer is the deposit wallet owner/session signer.

Required output shape:

  • order.SignatureType = SignatureTypePoly1271
  • order.Maker = depositWallet
  • order.Signer = depositWallet
  • order.Signature = ERC-7739 wrapped signature

func (*Client) SignOrder added in v1.0.2

func (c *Client) SignOrder(order *SignedOrder, opts ...SignOrderOption) error

SignOrder fills missing v2 order defaults and signs order with the client's signer.

func (*Client) Signer added in v1.0.7

func (c *Client) Signer() *polyauth.Signer

func (*Client) SplitPosition

func (c *Client) SplitPosition(ctx context.Context, req *SplitPositionRequest, out *TxReceipt) error

SplitPosition submits a splitPosition transaction and writes its receipt into out.

func (*Client) SplitPositionRelayer added in v1.1.4

func (c *Client) SplitPositionRelayer(
	ctx context.Context,
	req *SplitPositionRequest,
	relayerReq *CTFRelayerArgs,
	out *relayer.SubmitTransactionResponse,
) error

SplitPositionRelayer builds a splitPosition transaction, signs a PROXY relayer request, and submits it through the configured relayer.

func (*Client) SplitPositionWithDepositWallet added in v1.1.5

func (c *Client) SplitPositionWithDepositWallet(
	ctx context.Context,
	req *SplitPositionRequest,
	args *DepositWalletCTFArgs,
	out *relayer.SubmitTransactionResponse,
) error

SplitPositionWithDepositWallet builds, signs, and submits a splitPosition call through a deposit-wallet WALLET transaction.

func (*Client) SubmitCTFDepositWalletTransaction added in v1.1.5

func (c *Client) SubmitCTFDepositWalletTransaction(
	ctx context.Context,
	tx *CTFTransaction,
	args *DepositWalletCTFArgs,
	out *relayer.SubmitTransactionResponse,
) error

SubmitCTFDepositWalletTransaction builds, signs, and submits a CTF transaction as a deposit-wallet WALLET batch through the configured relayer.

func (*Client) SubmitCTFRelayerTransaction

func (c *Client) SubmitCTFRelayerTransaction(ctx context.Context, tx *CTFTransaction, req *RelayerCTFRequest, out *relayer.SubmitTransactionResponse) error

SubmitCTFRelayerTransaction submits built CTF calldata through the configured relayer.

func (*Client) SubmitRelayerTransaction

func (c *Client) SubmitRelayerTransaction(ctx context.Context, req *relayer.SubmitTransactionRequest, out *relayer.SubmitTransactionResponse) error

SubmitRelayerTransaction submits a pre-signed transaction through the configured relayer.

func (*Client) UpdateBalanceAllowance

func (c *Client) UpdateBalanceAllowance(ctx context.Context, params BalanceAllowanceParams, out *BalanceAllowanceResponse) error

UpdateBalanceAllowance updates the user's approved token allowance for trading. Requires L2 auth.

type ClobMarketInfo

type ClobMarketInfo struct {
	// ConditionID is the CTF condition identifier.
	ConditionID string `json:"c"`
	// MinimumTickSize is the price increment granularity.
	MinimumTickSize Float64 `json:"mts"`
	// MinimumOrderSize is the smallest allowed order.
	MinimumOrderSize Float64 `json:"mos"`
	// NegRisk indicates a negative-risk market resolution.
	NegRisk bool `json:"nr"`
	// FeeDetails describes the fee structure.
	FeeDetails FeeInfo `json:"fd"`
	// Tokens lists the conditional outcome tokens.
	Tokens []ClobMarketToken `json:"t"`
	// RFQEnabled indicates request-for-quote is active.
	RFQEnabled bool `json:"rfqe"`
	// MakerBaseFee is the maker fee rate.
	MakerBaseFee Float64 `json:"mbf"`
	// TakerBaseFee is the taker fee rate.
	TakerBaseFee Float64 `json:"tbf"`
}

ClobMarketInfo is the compact market info from GET /clob-markets.

type ClobMarketToken

type ClobMarketToken struct {
	// TokenID is the conditional token identifier.
	TokenID String `json:"t"`
	// Outcome is the outcome label.
	Outcome string `json:"o"`
}

ClobMarketToken is a lightweight token in ClobMarketInfo.

type ContractConfig

type ContractConfig struct {
	// Exchange is the CTF Exchange V2 contract used for standard market order
	// signing and settlement.
	Exchange common.Address

	// NegRiskExchange is the CTF Exchange V2 contract used for negative-risk
	// market order signing and settlement.
	NegRiskExchange common.Address

	// NegRiskAdapter is the adapter used for negative-risk conversion and
	// redemption flows.
	NegRiskAdapter common.Address

	// ConditionalTokens is the Gnosis Conditional Tokens Framework contract used
	// by Polymarket outcome tokens.
	ConditionalTokens common.Address

	// Collateral is the pUSD collateral token proxy used by CTF split, merge,
	// redeem, balance, allowance, and approval flows.
	Collateral common.Address

	// CollateralImplementation is the pUSD implementation contract behind the
	// proxy. Most callers should use Collateral instead.
	CollateralImplementation common.Address

	// CollateralOnramp is Polymarket's collateral onramp contract.
	CollateralOnramp common.Address

	// CollateralOfframp is Polymarket's collateral offramp contract.
	CollateralOfframp common.Address

	// PermissionedRamp is Polymarket's permissioned ramp contract.
	PermissionedRamp common.Address

	// CTFCollateralAdapter is the collateral adapter for standard CTF flows.
	CTFCollateralAdapter common.Address

	// NegRiskCTFCollateralAdapter is the collateral adapter for negative-risk CTF
	// flows.
	NegRiskCTFCollateralAdapter common.Address

	// GnosisSafeFactory is the factory used for legacy SAFE wallet deployments.
	GnosisSafeFactory common.Address

	// ProxyFactory is Polymarket's legacy proxy wallet factory.
	ProxyFactory common.Address

	// DepositWalletFactory is the factory used to deploy deterministic deposit
	// wallets through relayer WALLET-CREATE requests.
	DepositWalletFactory common.Address

	// UMAAdapter is the oracle adapter used when deriving condition IDs from
	// question IDs.
	UMAAdapter common.Address

	// UMAOptimisticOracle is the UMA Optimistic Oracle used by resolution
	// infrastructure.
	UMAOptimisticOracle common.Address
}

ContractConfig contains the on-chain contract addresses used by Polymarket on a chain.

func Contracts

func Contracts(chainID int64) (ContractConfig, error)

Contracts returns the known Polymarket contract addresses for chainID.

type CreateOrderOptions added in v1.0.5

type CreateOrderOptions struct {
	// TickSize is the market's minimum price increment (e.g. "0.01").
	// If empty, tick alignment validation is skipped.
	// Use BuildOrderForToken to fetch this automatically from the CLOB API.
	TickSize string
	NegRisk  bool
}

type CreateRFQQuoteRequest

type CreateRFQQuoteRequest struct {
	// RequestID references the original RFQ request.
	RequestID string `json:"requestId"`
	// AssetIn is the ERC-20 address being sent.
	AssetIn string `json:"assetIn"`
	// AssetOut is the ERC-20 address being received.
	AssetOut string `json:"assetOut"`
	// AmountIn is the input quantity.
	AmountIn Float64 `json:"amountIn"`
	// AmountOut is the quoted output quantity.
	AmountOut Float64 `json:"amountOut"`
	// UserType identifies the signature method.
	UserType SignatureType `json:"userType"`
}

CreateRFQQuoteRequest is the body for POST /rfq/quote.

type CreateRFQRequest

type CreateRFQRequest struct {
	// AssetIn is the ERC-20 address of the asset being sent.
	AssetIn string `json:"assetIn"`
	// AssetOut is the ERC-20 address of the asset being received.
	AssetOut string `json:"assetOut"`
	// AmountIn is the input quantity.
	AmountIn Float64 `json:"amountIn"`
	// AmountOut is the desired output quantity.
	AmountOut Float64 `json:"amountOut"`
	// UserType identifies the signature method.
	UserType SignatureType `json:"userType"`
}

CreateRFQRequest is the body for POST /rfq/request.

type Credentials

type Credentials struct {
	// Key is the API key identifier.
	Key string `json:"apiKey"`
	// Secret is the HMAC secret used to sign requests.
	Secret string `json:"secret"`
	// Passphrase protects the API key secret.
	Passphrase string `json:"passphrase"`
}

Credentials holds Polymarket API authentication material returned by CreateAPIKey.

type CurrentReward

type CurrentReward struct {
	// ConditionID is the market condition identifier.
	ConditionID string `json:"condition_id"`
	// RewardsConfig lists the active reward periods.
	RewardsConfig []RewardsConfig `json:"rewards_config"`
	// RewardsMaxSpread is the max spread to qualify for rewards.
	RewardsMaxSpread Float64 `json:"rewards_max_spread"`
	// RewardsMinSize is the minimum order size to qualify.
	RewardsMinSize Float64 `json:"rewards_min_size"`
}

CurrentReward describes active reward configuration for a market.

type Date

type Date = shared.Date

type DepositWalletBatchArgs added in v1.1.5

type DepositWalletBatchArgs struct {
	// From is the owner address. If empty, the client's signer address is used.
	From string
	// Factory optionally overrides Contracts(chainID).DepositWalletFactory.
	// Leave empty for normal chain-aware behavior.
	Factory string
	// DepositWallet is the deterministic deposit wallet address. Required.
	DepositWallet string
	// Nonce is the WALLET nonce. If empty, BuildDepositWalletBatchRelayerRequest
	// fetches it from the configured relayer using type=WALLET.
	Nonce string
	// Deadline is the Unix timestamp after which the batch is invalid. Required.
	Deadline string
	// Calls are the wallet calls executed by the batch.
	Calls []relayer.DepositWalletCall
	// Metadata is optional caller-provided relayer metadata.
	Metadata string
}

DepositWalletBatchArgs contains input for building a signed WALLET batch relayer request.

WALLET batches are used by deposit wallets for approvals, transfers, withdrawals, splits, merges, and other wallet-level calls.

type DepositWalletCTFArgs added in v1.1.5

type DepositWalletCTFArgs struct {
	// From is the owner address. If empty, the client's signer address is used.
	From string
	// Factory optionally overrides Contracts(chainID).DepositWalletFactory.
	Factory string
	// DepositWallet is the deterministic deposit wallet address. Required.
	DepositWallet string
	// Nonce is the WALLET nonce. If empty, the client fetches it from the relayer.
	Nonce string
	// Deadline is the Unix timestamp after which the batch is invalid. Required.
	Deadline string
	// Metadata is optional caller-provided relayer metadata.
	Metadata string
}

DepositWalletCTFArgs contains deposit-wallet WALLET batch options for a CTF transaction.

type DropNotificationParams

type DropNotificationParams struct {
	// IDs is the list of notification identifiers to drop.
	IDs []string `url:"ids,omitempty"`
}

DropNotificationParams identifies notifications to dismiss.

type Earning

type Earning struct {
	// AssetAddress is the reward asset contract address.
	AssetAddress string `json:"asset_address"`
	// Earnings is the total reward amount.
	Earnings Float64 `json:"earnings"`
	// AssetRate is the reward asset exchange rate.
	AssetRate Float64 `json:"asset_rate"`
}

Earning records a single reward earning entry.

type EarningsParams

type EarningsParams struct {
	// Date filters by reward date.
	Date string `url:"date,omitempty"`
	// OrderBy sets the sort field.
	OrderBy string `url:"order_by,omitempty"`
	// Position sets the result offset.
	Position string `url:"position,omitempty"`
	// NoCompetition skips low-competition markets.
	NoCompetition bool `url:"no_competition,omitempty"`
	// NextCursor is the pagination cursor.
	NextCursor string `url:"next_cursor,omitempty"`
}

EarningsParams filters GET /rewards/user/markets requests.

type FeeInfo

type FeeInfo struct {
	// Rate is the fee rate.
	Rate Float64 `json:"r"`
	// Exponent is the fee exponent.
	Exponent Float64 `json:"e"`
	// TakerOnly is true when fees apply only to takers.
	TakerOnly bool `json:"to"`
}

FeeInfo describes the fee structure for a CLOB market.

type FeeRateResponse

type FeeRateResponse struct {
	// BaseFee is the base fee in basis points.
	BaseFee Int `json:"base_fee"`
}

FeeRateResponse contains the base fee rate for a market.

type Float64

type Float64 = shared.Float64

type GeoblockResponse

type GeoblockResponse struct {
	// Blocked is true when the IP is in a restricted jurisdiction.
	Blocked bool `json:"blocked"`
	// IP is the detected client IP.
	IP string `json:"ip"`
	// Country is the ISO country code.
	Country string `json:"country"`
	// Region is the geographic region.
	Region string `json:"region"`
}

GeoblockResponse reports geographic access restrictions.

type GetMarketOptionsResponse added in v1.0.5

type GetMarketOptionsResponse struct {
	TickSize string
	NegRisk  bool
}

type HeartbeatResponse

type HeartbeatResponse struct {
	// HeartbeatID is the unique heartbeat identifier.
	HeartbeatID string `json:"heartbeat_id"`
	// Error contains error details on failure.
	Error string `json:"error"`
}

HeartbeatResponse is returned by the heartbeat endpoint.

type Int

type Int = shared.Int

type Int64

type Int64 = shared.Int64

type LastTradePriceResponse

type LastTradePriceResponse struct {
	// Price is the trade price.
	Price Float64 `json:"price"`
	// Side is the trade direction.
	Side Side `json:"side"`
}

LastTradePriceResponse contains the most recent trade price.

type LastTradesPricesResponse

type LastTradesPricesResponse struct {
	// TokenID is the conditional token identifier.
	TokenID String `json:"token_id"`
	// Price is the last trade price.
	Price Float64 `json:"price"`
	// Side is the trade direction.
	Side Side `json:"side"`
}

LastTradesPricesResponse contains per-token last trade prices.

type MakerOrder

type MakerOrder struct {
	// OrderID is the order that was filled.
	OrderID string `json:"order_id"`
	// Owner is the order owner address.
	Owner string `json:"owner"`
	// MakerAddress is the maker wallet address.
	MakerAddress string `json:"maker_address"`
	// MatchedAmount is the quantity matched.
	MatchedAmount Float64 `json:"matched_amount"`
	// Price is the fill price.
	Price Float64 `json:"price"`
	// FeeRateBps is the fee rate in basis points.
	FeeRateBps Float64 `json:"fee_rate_bps"`
	// AssetID is the conditional token identifier.
	AssetID String `json:"asset_id"`
	// Outcome is the outcome label.
	Outcome string `json:"outcome"`
	// Side is the order direction.
	Side Side `json:"side"`
}

MakerOrder represents a single maker fill in a trade.

type Market

type Market struct {
	// EnableOrderBook indicates order book functionality is available.
	EnableOrderBook bool `json:"enable_order_book"`
	// Active is true when the market is accepting trades.
	Active bool `json:"active"`
	// Closed is true when the market has closed.
	Closed bool `json:"closed"`
	// Archived is true when the market is archived.
	Archived bool `json:"archived"`
	// AcceptingOrders indicates the order book is accepting new orders.
	AcceptingOrders bool `json:"accepting_orders"`
	// AcceptingOrderTimestamp is when the market started accepting orders.
	AcceptingOrderTimestamp Time `json:"accepting_order_timestamp"`
	// MinimumOrderSize is the smallest allowed order.
	MinimumOrderSize Float64 `json:"minimum_order_size"`
	// MinimumTickSize is the price increment granularity.
	MinimumTickSize Float64 `json:"minimum_tick_size"`
	// ConditionID is the CTF condition identifier.
	ConditionID string `json:"condition_id"`
	// QuestionID identifies the underlying Polymarket question.
	QuestionID string `json:"question_id"`
	// Question is the market question text.
	Question string `json:"question"`
	// Description is the market description.
	Description string `json:"description"`
	// MarketSlug is the URL-friendly market slug.
	MarketSlug string `json:"market_slug"`
	// EndDateISO is the market resolution date.
	EndDateISO Time `json:"end_date_iso"`
	// GameStartTime is the event start time.
	GameStartTime Time `json:"game_start_time"`
	// SecondsDelay is the delay period before order book acceptance.
	SecondsDelay Uint64 `json:"seconds_delay"`
	// FPMM is the Fixed Product Market Maker address.
	FPMM string `json:"fpmm"`
	// MakerBaseFee is the maker fee rate.
	MakerBaseFee Float64 `json:"maker_base_fee"`
	// TakerBaseFee is the taker fee rate.
	TakerBaseFee Float64 `json:"taker_base_fee"`
	// NotificationsEnabled indicates push notifications are active.
	NotificationsEnabled bool `json:"notifications_enabled"`
	// NegRisk indicates a negative-risk market resolution.
	NegRisk bool `json:"neg_risk"`
	// NegRiskMarketID identifies the neg-risk grouping.
	NegRiskMarketID string `json:"neg_risk_market_id"`
	// NegRiskRequestID is the original request identifier.
	NegRiskRequestID string `json:"neg_risk_request_id"`
	// Icon is the market icon URL.
	Icon string `json:"icon"`
	// Image is the market banner image URL.
	Image string `json:"image"`
	// Rewards contains reward parameters.
	Rewards Rewards `json:"rewards"`
	// Is5050Outcome is true for binary 50/50 markets.
	Is5050Outcome bool `json:"is_50_50_outcome"`
	// Tokens lists the conditional outcome tokens.
	Tokens []Token `json:"tokens"`
	// Tags categorize the market.
	Tags []string `json:"tags"`
}

Market is the full CLOB market data structure.

type MarketByToken

type MarketByToken struct {
	// ConditionID is the CTF condition identifier.
	ConditionID string `json:"condition_id"`
	// PrimaryTokenID is the winning outcome token ID.
	PrimaryTokenID String `json:"primary_token_id"`
	// SecondaryTokenID is the losing outcome token ID.
	SecondaryTokenID String `json:"secondary_token_id"`
}

MarketByToken maps a primary and secondary token to a condition.

type MarketOrderArgsV2

type MarketOrderArgsV2 struct {
	Price string
	// Price is the worst-price limit (required for amount→shares conversion).
	// BUY: max price you're willing to pay. SELL: min price you'll accept.
	TokenID       string
	Amount        string // BUY: USDC (pUSD) to spend, SELL: shares to sell
	Side          Side
	SignatureType *SignatureType

	// Maker is the wallet address that owns/funds the order.
	//
	// EOA:
	//   Maker may be empty, or equal to signer address.
	//
	// POLY_PROXY / POLY_GNOSIS_SAFE:
	//   Maker should be the funder/proxy/safe address associated with the API key.
	//
	// POLY_1271:
	//   Maker must be the deposit wallet address. BuildMarketOrder sets
	//   order.Signer to the same deposit wallet address before signing.
	Maker string

	BuilderCode string
	Metadata    string
}

type MarketReward

type MarketReward struct {
	// ConditionID is the market condition identifier.
	ConditionID string `json:"condition_id"`
	// Question is the market question text.
	Question string `json:"question"`
	// MarketSlug is the URL-friendly market slug.
	MarketSlug string `json:"market_slug"`
	// EventSlug is the parent event slug.
	EventSlug string `json:"event_slug"`
	// Image is the market banner image URL.
	Image string `json:"image"`
	// RewardsMaxSpread is the max spread to qualify.
	RewardsMaxSpread Float64 `json:"rewards_max_spread"`
	// RewardsMinSize is the minimum order size to qualify.
	RewardsMinSize Float64 `json:"rewards_min_size"`
	// MarketCompetitiveness indicates market saturation.
	MarketCompetitiveness Float64 `json:"market_competitiveness"`
	// Tokens lists the conditional outcome tokens.
	Tokens []Token `json:"tokens"`
	// RewardsConfig lists the active reward periods.
	RewardsConfig []MarketRewardsConfig `json:"rewards_config"`
}

MarketReward describes reward eligibility for a specific market.

type MarketRewardsConfig

type MarketRewardsConfig struct {
	// ID is the config identifier.
	ID String `json:"id"`
	// AssetAddress is the reward asset contract address.
	AssetAddress string `json:"asset_address"`
	// StartDate is the reward start date.
	StartDate Date `json:"start_date"`
	// EndDate is the reward end date.
	EndDate Date `json:"end_date"`
	// RatePerDay is the daily reward rate.
	RatePerDay Float64 `json:"rate_per_day"`
	// TotalRewards is the total reward pool.
	TotalRewards Float64 `json:"total_rewards"`
	// TotalDays is the duration in days.
	TotalDays Float64 `json:"total_days"`
}

MarketRewardsConfig describes the reward period for one market asset.

type MergePositionsRequest

type MergePositionsRequest struct {
	// CollateralToken is the pUSD token address received after merging a full set.
	CollateralToken common.Address
	// ParentCollectionID is zero for top-level Polymarket markets.
	ParentCollectionID common.Hash
	// ConditionID is the market condition ID.
	ConditionID common.Hash
	// Partition is the list of index sets to burn; binary markets use [1, 2].
	Partition []*big.Int
	// Amount is the number of full outcome sets to merge, in base units.
	Amount *big.Int
}

MergePositionsRequest describes a ConditionalTokens mergePositions call.

func MergeBinary

func MergeBinary(collateral common.Address, conditionID common.Hash, amount *big.Int) MergePositionsRequest

MergeBinary returns a mergePositions request for a standard binary Polymarket market.

type MidpointResponse

type MidpointResponse struct {
	// Mid is the midpoint between best bid and best ask.
	Mid Float64 `json:"mid"`
}

MidpointResponse contains the order book midpoint price.

type NegRiskResponse

type NegRiskResponse struct {
	// NegRisk is true for neg-risk markets.
	NegRisk bool `json:"neg_risk"`
}

NegRiskResponse indicates whether a market uses neg-risk resolution.

type Notification

type Notification struct {
	// Type identifies the notification category.
	Type Int `json:"type"`
	// Owner is the recipient address.
	Owner string `json:"owner"`
	// Payload contains the notification data.
	Payload jsonRawObject `json:"payload"`
}

Notification is a user notification from the CLOB.

type OpenOrder

type OpenOrder struct {
	// ID is the order identifier.
	ID string `json:"id"`
	// Status is the current order status.
	Status string `json:"status"`
	// Owner is the order owner address.
	Owner string `json:"owner"`
	// MakerAddress is the maker wallet address.
	MakerAddress string `json:"maker_address"`
	// Market is the condition ID the order belongs to.
	Market string `json:"market"`
	// AssetID is the conditional token identifier.
	AssetID String `json:"asset_id"`
	// Side is the order direction.
	Side Side `json:"side"`
	// OriginalSize is the initial order quantity.
	OriginalSize Float64 `json:"original_size"`
	// SizeMatched is the quantity already filled.
	SizeMatched Float64 `json:"size_matched"`
	// Price is the limit price.
	Price Float64 `json:"price"`
	// AssociateTrades lists the trade IDs from fills.
	AssociateTrades []string `json:"associate_trades"`
	// Outcome is the outcome label.
	Outcome string `json:"outcome"`
	// CreatedAt is when the order was placed.
	CreatedAt Time `json:"created_at"`
	// Expiration is the order expiry time.
	Expiration Time `json:"expiration"`
	// OrderType is the execution type.
	OrderType OrderType `json:"order_type"`
}

OpenOrder represents an active order returned by GET /data/orders.

type OpenOrderParams

type OpenOrderParams struct {
	// ID filters by order identifier.
	ID string `url:"id,omitempty"`
	// Market filters by condition ID.
	Market string `url:"market,omitempty"`
	// AssetID filters by conditional token identifier.
	AssetID string `url:"asset_id,omitempty"`
	// NextCursor Cursor for pagination (base64 encoded offset)
	NextCursor string `url:"next_cursor,omitempty" json:"next_cursor,omitempty"`
}

OpenOrderParams filters GET /data/orders requests.

type Option

type Option func(*Client)

Option customizes a CLOB client created by NewClient.

func WithChainID

func WithChainID(chainID int64) Option

WithChainID sets the EVM chain ID used for auth signatures and CTF transactions.

func WithCredentials

func WithCredentials(creds Credentials) Option

WithCredentials sets Polymarket API credentials for L2-authenticated requests.

func WithDefaultSignatureType added in v1.1.3

func WithDefaultSignatureType(signatureType SignatureType) Option

func WithGeoblockHost

func WithGeoblockHost(host string) Option

WithGeoblockHost sets the host used by geoblock-related requests.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient sets the HTTP client used for REST requests.

func WithRPCURL

func WithRPCURL(rpcURL string) Option

WithRPCURL sets the Polygon JSON-RPC endpoint used by on-chain CTF helpers.

func WithRelayerClient

func WithRelayerClient(client *relayer.Client) Option

WithRelayerClient sets the Polymarket Relayer API client used by CTF helpers.

func WithRelayerSubmitter

func WithRelayerSubmitter(submitter RelayerSubmitter) Option

WithRelayerSubmitter sets the relayer used by SubmitRelayerTransaction helpers.

func WithServerTime

func WithServerTime(enabled bool) Option

WithServerTime makes authenticated requests use the CLOB server timestamp.

func WithSigner

func WithSigner(signer *polyauth.Signer) Option

WithSigner sets the signer used for L1 and L2 authenticated requests.

type OrderArgsV2

type OrderArgsV2 struct {
	TokenID       string
	Price         string
	Size          string
	Side          Side
	Expiration    string
	SignatureType *SignatureType

	// Maker is the wallet address that owns/funds the order.
	//
	// EOA:
	//   Maker may be empty, or equal to signer address.
	//
	// POLY_PROXY / POLY_GNOSIS_SAFE:
	//   Maker should be the funder/proxy/safe address associated with the API key.
	//
	// POLY_1271:
	//   Maker must be the deposit wallet address. BuildOrder sets order.Signer to
	//   the same deposit wallet address before signing.
	Maker string

	BuilderCode string
	Metadata    string
}

type OrderBookSummary

type OrderBookSummary struct {
	// Market is the condition ID.
	Market string `json:"market"`
	// AssetID is the token ID.
	AssetID String `json:"asset_id"`
	// Timestamp is when the snapshot was taken.
	Timestamp Time `json:"timestamp"`
	// Bids are buy orders sorted best-first.
	Bids []OrderSummary `json:"bids"`
	// Asks are sell orders sorted best-first.
	Asks []OrderSummary `json:"asks"`
	// MinOrderSize is the minimum order quantity.
	MinOrderSize Float64 `json:"min_order_size"`
	// NegRisk indicates a negative-risk market.
	NegRisk bool `json:"neg_risk"`
	// TickSize is the minimum price increment.
	TickSize Float64 `json:"tick_size"`
	// LastTradePrice is the price of the most recent trade.
	LastTradePrice Float64 `json:"last_trade_price"`
	// Hash is the order book snapshot hash.
	Hash string `json:"hash"`
}

OrderBookSummary is a snapshot of the order book for a single asset.

type OrderBuilder added in v1.0.5

type OrderBuilder struct {
	// contains filtered or unexported fields
}

func NewOrderBuilder added in v1.0.5

func NewOrderBuilder(client *Client) *OrderBuilder

func (*OrderBuilder) BuildMarketOrder added in v1.0.5

func (b *OrderBuilder) BuildMarketOrder(args MarketOrderArgsV2, opts CreateOrderOptions) (*SignedOrder, error)

func (*OrderBuilder) BuildMarketOrderForToken added in v1.0.5

func (b *OrderBuilder) BuildMarketOrderForToken(ctx context.Context, args MarketOrderArgsV2) (*SignedOrder, error)

BuildMarketOrderForToken fetches tickSize and negRisk for the given TokenID, then builds and signs a market order using args.BuilderCode and args.Metadata.

func (*OrderBuilder) BuildOrder added in v1.0.5

func (b *OrderBuilder) BuildOrder(args OrderArgsV2, opts CreateOrderOptions) (*SignedOrder, error)

BuildOrder constructs and signs a V2 order from human-readable arguments.

Validations performed:

  • price range (0 < price < 1 for limit orders)
  • tickSize alignment (only if opts.TickSize is non-empty)
  • BuilderCode and Metadata format (must be valid bytes32 hex or empty)

BuildOrder only constructs, validates, and signs orders. It does not check balance, allowance, or reserved open order capacity.

func (*OrderBuilder) BuildOrderForToken added in v1.0.5

func (b *OrderBuilder) BuildOrderForToken(ctx context.Context, args OrderArgsV2) (*SignedOrder, error)

func (*OrderBuilder) CreateAndPostMarketOrder added in v1.0.5

func (b *OrderBuilder) CreateAndPostMarketOrder(ctx context.Context, args MarketOrderArgsV2, opts CreateOrderOptions, orderType OrderType, deferExec *bool) (*PostOrderResponse, error)

func (*OrderBuilder) CreateAndPostMarketOrderForToken added in v1.0.5

func (b *OrderBuilder) CreateAndPostMarketOrderForToken(ctx context.Context, args MarketOrderArgsV2, orderType OrderType, deferExec *bool) (*PostOrderResponse, error)

CreateAndPostMarketOrderForToken auto-fetches market options, builds, signs, and posts a market order.

func (*OrderBuilder) CreateAndPostOrder added in v1.0.5

func (b *OrderBuilder) CreateAndPostOrder(ctx context.Context, args OrderArgsV2, opts CreateOrderOptions, orderType OrderType, deferExec *bool) (*PostOrderResponse, error)

func (*OrderBuilder) CreateAndPostOrderForToken added in v1.0.5

func (b *OrderBuilder) CreateAndPostOrderForToken(ctx context.Context, args OrderArgsV2, orderType OrderType, deferExec *bool) (*PostOrderResponse, error)

CreateAndPostOrderForToken auto-fetches market options, builds, signs, and posts.

func (*OrderBuilder) GetMarketOptions added in v1.0.5

func (b *OrderBuilder) GetMarketOptions(ctx context.Context, tokenID string) (*GetMarketOptionsResponse, error)

type OrderMarketCancelParams

type OrderMarketCancelParams struct {
	// Market is the condition ID to cancel orders for.
	Market string `json:"market,omitempty"`
	// AssetID is the conditional token to cancel.
	AssetID string `json:"asset_id,omitempty"`
}

OrderMarketCancelParams targets orders for partial cancellation.

type OrderScoring

type OrderScoring struct {
	// Scoring is true when the order is in the scoring queue.
	Scoring bool `json:"scoring"`
}

OrderScoring reports whether an order is actively scoring.

type OrderSummary

type OrderSummary struct {
	// Price is the limit order price.
	Price Float64 `json:"price"`
	// Size is the available quantity at this price.
	Size Float64 `json:"size"`
}

OrderSummary represents a single price/size level in an order book.

type OrderType

type OrderType string
const (
	GTC OrderType = "GTC"
	FOK OrderType = "FOK"
	GTD OrderType = "GTD"
	FAK OrderType = "FAK"
)

type Page

type Page[T any] = shared.Page[T]

type PostOrderRequest

type PostOrderRequest struct {
	// Order is the signed order payload.
	Order SignedOrder `json:"order"`
	// Owner is the order owner address.
	Owner string `json:"owner"`
	// OrderType is the execution type (GTC, FOK, GTD).
	OrderType OrderType `json:"orderType"`
	// DeferExec defers order execution for later processing.
	DeferExec *bool `json:"deferExec,omitempty"`
}

PostOrderRequest wraps a SignedOrder for POST /order.

type PostOrderResponse

type PostOrderResponse struct {
	// Success is true when the order was accepted.
	Success bool `json:"success"`
	// ErrorMsg contains the error description on failure.
	ErrorMsg string `json:"errorMsg"`
	// OrderID is the assigned order identifier.
	OrderID string `json:"orderID"`
	// TransactionHashes lists on-chain transaction hashes.
	TransactionHashes []string `json:"transactionsHashes"`
	// Status is the order processing status.
	Status string `json:"status"`
	// TakingAmount is the amount filled from the order.
	TakingAmount Float64 `json:"takingAmount"`
	// MakingAmount is the remaining order amount.
	MakingAmount Float64 `json:"makingAmount"`
	// TradeIDs lists the resulting trade identifiers.
	TradeIDs []string `json:"trade_ids"`
}

PostOrderResponse is returned after order submission.

type PriceHistoryParams

type PriceHistoryParams struct {
	// Market is the condition ID.
	Market string `url:"market,omitempty"`
	// StartTS is the start Unix timestamp.
	StartTS int64 `url:"startTs,omitempty"`
	// EndTS is the end Unix timestamp.
	EndTS int64 `url:"endTs,omitempty"`
	// Fidelity controls the data point density.
	Fidelity int `url:"fidelity,omitempty"`
	// Interval sets the bucket size (e.g. "5m", "1h").
	Interval string `url:"interval,omitempty"`
}

PriceHistoryParams filters GET /prices-history requests.

type PriceHistoryResponse

type PriceHistoryResponse struct {
	// History is the ordered list of price points.
	History []PricePoint `json:"history"`
}

PriceHistoryResponse contains a time series of price points.

type PricePoint

type PricePoint struct {
	// T is the Unix timestamp.
	T Int64 `json:"t"`
	// P is the price at time T.
	P Float64 `json:"p"`
}

PricePoint is a single timestamped price record.

type PriceResponse

type PriceResponse struct {
	// Price is the current price.
	Price Float64 `json:"price"`
}

PriceResponse contains the current price for a token/side.

type ProxyRelayerBuilder added in v1.1.4

type ProxyRelayerBuilder interface {
	ProxySubmitTransactionRequest(
		context.Context,
		*polyauth.Signer,
		*relayer.ProxySubmitTransactionArgs,
		*relayer.SubmitTransactionRequest,
	) error
}

type RFQListParams

type RFQListParams struct {
	// Offset is the start index.
	Offset string `url:"offset,omitempty"`
	// Limit sets the maximum returned results.
	Limit int `url:"limit,omitempty"`
	// State filters by quote/request state.
	State string `url:"state,omitempty"`
	// RequestIDs filters by request IDs.
	RequestIDs []string `url:"requestIds,omitempty"`
	// QuoteIDs filters by quote IDs.
	QuoteIDs []string `url:"quoteIds,omitempty"`
	// Markets filters by condition IDs.
	Markets []string `url:"markets,omitempty"`
	// SizeMin filters by minimum trade size.
	SizeMin Float64 `url:"sizeMin,omitempty"`
	// SizeMax filters by maximum trade size.
	SizeMax Float64 `url:"sizeMax,omitempty"`
	// SizeUSDCMin filters by minimum USDC value.
	SizeUSDCMin Float64 `url:"sizeUsdcMin,omitempty"`
	// SizeUSDCMax filters by maximum USDC value.
	SizeUSDCMax Float64 `url:"sizeUsdcMax,omitempty"`
	// PriceMin filters by minimum price.
	PriceMin Float64 `url:"priceMin,omitempty"`
	// PriceMax filters by maximum price.
	PriceMax Float64 `url:"priceMax,omitempty"`
	// SortBy sets the sort field.
	SortBy string `url:"sortBy,omitempty"`
	// SortDir sets the sort direction (asc/desc).
	SortDir string `url:"sortDir,omitempty"`
}

RFQListParams filters GET /rfq/data/* listing endpoints.

type ReadonlyAPIKey

type ReadonlyAPIKey struct {
	// APIKey is the read-only key value.
	APIKey string `json:"apiKey"`
}

ReadonlyAPIKey describes a read-only API key.

type Rebate

type Rebate struct {
	// Date is the rebate date.
	Date Date `json:"date"`
	// ConditionID is the market condition identifier.
	ConditionID string `json:"condition_id"`
	// AssetAddress is the reward asset contract address.
	AssetAddress string `json:"asset_address"`
	// MakerAddress is the maker wallet address.
	MakerAddress string `json:"maker_address"`
	// RebatedFeesUSDC is the total rebated fee in USDC.
	RebatedFeesUSDC Float64 `json:"rebated_fees_usdc"`
}

Rebate documents current rebated fees for a maker on one market asset.

type RebateParams

type RebateParams struct {
	// Date filters by reward date.
	Date string `url:"date,omitempty"`
	// MakerAddress filters by maker wallet address.
	MakerAddress string `url:"maker_address,omitempty"`
}

RebateParams filters current maker rebate requests.

type RedeemNegRiskRequest

type RedeemNegRiskRequest struct {
	// ConditionID is the resolved neg-risk condition ID.
	ConditionID common.Hash
}

RedeemNegRiskRequest describes a neg-risk adapter redemption call.

type RedeemPositionsRequest

type RedeemPositionsRequest struct {
	// CollateralToken is the pUSD token address redeemed after market resolution.
	CollateralToken common.Address
	// ParentCollectionID is zero for top-level Polymarket markets.
	ParentCollectionID common.Hash
	// ConditionID is the resolved market condition ID.
	ConditionID common.Hash
	// IndexSets are the outcome index sets to redeem; binary markets use [1, 2].
	IndexSets []*big.Int
}

RedeemPositionsRequest describes a ConditionalTokens redeemPositions call.

func RedeemBinary

func RedeemBinary(collateral common.Address, conditionID common.Hash) RedeemPositionsRequest

RedeemBinary returns a redeemPositions request for a resolved binary Polymarket market.

type RelayerCTFRequest

type RelayerCTFRequest struct {
	// To is the contract address that should receive the transaction.
	To string
	// From is the signer address.
	From string
	// ProxyWallet is the user's Polymarket proxy wallet.
	ProxyWallet string
	// Data is the ABI-encoded calldata.
	Data string
	// Nonce is the relayer transaction nonce.
	Nonce string
	// Signature is the 0x-prefixed Safe or proxy transaction signature.
	Signature string
	// SignatureParams are Safe transaction parameters.
	SignatureParams *relayer.SignatureParams
	// Type selects SAFE or PROXY relayer signing.
	// Deposit wallet WALLET transactions are intentionally handled by
	// CTFDepositWalletTransactionRequest instead.
	Type relayer.NonceType
	// Metadata is optional caller-provided transaction metadata.
	Metadata string
	// Value is the native token value for the call when required.
	Value string
}

RelayerCTFRequest contains the relayer metadata needed to submit CTF calldata.

type RelayerNonceGetter added in v1.1.5

type RelayerNonceGetter interface {
	GetNonce(context.Context, *relayer.NonceResponse, ...relayer.NonceType) error
}

type RelayerSubmitter

type RelayerSubmitter interface {
	SubmitTransaction(context.Context, *relayer.SubmitTransactionRequest, *relayer.SubmitTransactionResponse) error
}

RelayerSubmitter is the relayer capability used by CLOB CTF helpers.

type RewardRate

type RewardRate struct {
	// AssetAddress is the reward asset contract address.
	AssetAddress string `json:"asset_address"`
	// RewardsDailyRate is the daily reward amount.
	RewardsDailyRate Float64 `json:"rewards_daily_rate"`
}

RewardRate describes daily rewards for a specific asset.

type Rewards

type Rewards struct {
	// Rates is the list of asset-specific reward rates.
	Rates []RewardRate `json:"rates"`
	// MinSize is the minimum order size to qualify for rewards.
	MinSize Float64 `json:"min_size"`
	// MaxSpread is the maximum bid-ask spread to qualify for rewards.
	MaxSpread Float64 `json:"max_spread"`
}

Rewards contains reward parameters for a market.

type RewardsConfig

type RewardsConfig struct {
	AssetAddress string  `json:"asset_address"`
	StartDate    Date    `json:"start_date"`
	EndDate      Date    `json:"end_date"`
	RatePerDay   Float64 `json:"rate_per_day"`
	TotalRewards Float64 `json:"total_rewards"`
}

type RewardsMarketsParams

type RewardsMarketsParams struct {
	// ConditionID filters by market ID.
	ConditionID string `url:"condition_id,omitempty"`
	// Date filters by reward date.
	Date string `url:"date,omitempty"`
	// NextCursor is the pagination cursor.
	NextCursor string `url:"next_cursor,omitempty"`
}

RewardsMarketsParams filters GET /rewards/markets requests.

type RfqQuote

type RfqQuote struct {
	// QuoteID is the unique quote identifier.
	QuoteID string `json:"quoteId"`
	// RequestID references the original RFQ request.
	RequestID string `json:"requestId"`
	// UserAddress is the requester wallet address.
	UserAddress string `json:"userAddress"`
	// ProxyAddress is the proxy wallet address.
	ProxyAddress string `json:"proxyAddress"`
	// Condition is the condition the quote applies to.
	Condition string `json:"condition"`
	// Token is the asset being offered.
	Token String `json:"token"`
	// Complement is the complementary asset.
	Complement String `json:"complement"`
	// Side is the trade direction.
	Side Side `json:"side"`
	// SizeIn is the input quantity.
	SizeIn Float64 `json:"sizeIn"`
	// SizeOut is the output quantity.
	SizeOut Float64 `json:"sizeOut"`
	// Price is the quoted price.
	Price Float64 `json:"price"`
}

RfqQuote represents a quote generated in response to an RFQ.

type RfqRequest

type RfqRequest struct {
	// RequestID is the unique request identifier.
	RequestID string `json:"requestId"`
	// UserAddress is the requester wallet address.
	UserAddress string `json:"userAddress"`
	// ProxyAddress is the proxy wallet address.
	ProxyAddress string `json:"proxyAddress"`
	// Condition is the condition the request applies to.
	Condition string `json:"condition"`
	// Token is the asset being offered.
	Token String `json:"token"`
	// Complement is the complementary asset.
	Complement String `json:"complement"`
	// Side is the requested trade direction.
	Side Side `json:"side"`
	// SizeIn is the input quantity.
	SizeIn Float64 `json:"sizeIn"`
	// SizeOut is the output quantity.
	SizeOut Float64 `json:"sizeOut"`
	// Price is the requested price.
	Price Float64 `json:"price"`
	// Expiry is the request expiry Unix timestamp.
	Expiry Int64 `json:"expiry"`
}

RfqRequest represents an RFQ (request for quote) submission.

type SafeRelayerBuilder added in v1.1.4

type SafeRelayerBuilder interface {
	SafeSubmitTransactionRequest(
		context.Context,
		*polyauth.Signer,
		*relayer.SafeSubmitTransactionArgs,
		*relayer.SubmitTransactionRequest,
	) error
}

type Side

type Side string
const (
	Buy  Side = "BUY"
	Sell Side = "SELL"
)

type SignOrderOption added in v1.0.2

type SignOrderOption func(*signOrderConfig)

SignOrderOption customizes how SignOrder builds the EIP-712 domain and defaults.

func WithSignOrderNegRisk added in v1.0.2

func WithSignOrderNegRisk(enabled bool) SignOrderOption

WithSignOrderNegRisk signs against the neg-risk exchange contract.

func WithSignOrderSalt added in v1.0.2

func WithSignOrderSalt(salt *big.Int) SignOrderOption

WithSignOrderSalt sets the salt used when the order has no salt.

func WithSignOrderTime added in v1.0.2

func WithSignOrderTime(now time.Time) SignOrderOption

WithSignOrderTime sets the timestamp used when the order has no timestamp.

func WithSignOrderVerifyingContract added in v1.0.2

func WithSignOrderVerifyingContract(address common.Address) SignOrderOption

WithSignOrderVerifyingContract signs against a custom exchange contract address.

type SignatureType

type SignatureType int
const (
	SignatureTypeEOA SignatureType = iota
	SignatureTypeProxy
	SignatureTypeGnosisSafe
	// SignatureTypePoly1271 is for EIP-1271 contract wallet validation.
	// Supported by the exchange contract, but not listed on the simplified
	// Create Order documentation page.
	SignatureTypePoly1271
)

type SignedOrder

type SignedOrder struct {
	// Salt is the order uniqueness salt. Marshalled as a JSON number
	// (not string) — Polymarket's CLOB v2 backend rejects salt-as-string
	// with the generic "Invalid order payload" error. Bug discovered
	// 2026-04-28 against production. The salt generator is bounded to
	// the current ms timestamp (≤ ~1.78e12) so int64 safely fits.
	Salt Int64 `json:"salt"`
	// Maker is the order creator address.
	Maker string `json:"maker"`
	// Signer is the signing authority address.
	Signer string `json:"signer"`
	// TokenID is the conditional token identifier.
	TokenID String `json:"tokenId"`
	// MakerAmount is the amount the maker offers.
	MakerAmount String `json:"makerAmount"`
	// TakerAmount is the amount the maker wants.
	TakerAmount String `json:"takerAmount"`
	// Expiration is the order expiry Unix timestamp (GTD orders only).
	// Present in REST wire format but excluded from EIP-712 signing.
	Expiration String `json:"expiration,omitempty"`
	// Side is the order direction.
	Side Side `json:"side"`
	// SignatureType identifies the signature method.
	SignatureType SignatureType `json:"signatureType"`
	// Timestamp is when the order was created.
	Timestamp String `json:"timestamp"`
	// Metadata is optional order metadata.
	Metadata string `json:"metadata"`
	// Builder is the builder code for fee splits.
	Builder string `json:"builder"`
	// Signature is the EIP-712 signature bytes.
	Signature string `json:"signature"`
}

SignedOrder is an EIP-712 signed order ready for submission.

type SimplifiedMarket

type SimplifiedMarket struct {
	// ConditionID is the CTF condition identifier.
	ConditionID string `json:"condition_id"`
	// Tokens lists the conditional outcome tokens.
	Tokens []Token `json:"tokens"`
	// Rewards contains reward parameters.
	Rewards Rewards `json:"rewards"`
	// Active is true when the market is accepting trades.
	Active bool `json:"active"`
	// Closed is true when the market has closed.
	Closed bool `json:"closed"`
	// Archived is true when the market is archived.
	Archived bool `json:"archived"`
	// AcceptingOrders indicates the order book is accepting new orders.
	AcceptingOrders bool `json:"accepting_orders"`
}

SimplifiedMarket is a lightweight market record.

type SplitPositionRequest

type SplitPositionRequest struct {
	// CollateralToken is the pUSD token address supplied as collateral.
	CollateralToken common.Address
	// ParentCollectionID is zero for top-level Polymarket markets.
	ParentCollectionID common.Hash
	// ConditionID is the market condition ID.
	ConditionID common.Hash
	// Partition is the list of index sets to mint; binary markets use [1, 2].
	Partition []*big.Int
	// Amount is the pUSD amount, in base units, to split into a full outcome set.
	Amount *big.Int
}

SplitPositionRequest describes a ConditionalTokens splitPosition call.

func SplitBinary

func SplitBinary(collateral common.Address, conditionID common.Hash, amount *big.Int) SplitPositionRequest

SplitBinary returns a splitPosition request for a standard binary Polymarket market.

type SpreadResponse

type SpreadResponse struct {
	// Spread is the difference between best ask and best bid.
	Spread Float64 `json:"spread"`
}

SpreadResponse contains the current bid-ask spread.

type String

type String = shared.String

type TickSize

type TickSize string
const (
	TickSizeTenth       TickSize = "0.1"
	TickSizeHundredth   TickSize = "0.01"
	TickSizeThousandth  TickSize = "0.001"
	TickSizeTenThousand TickSize = "0.0001"
)

func (*TickSize) UnmarshalJSON added in v1.0.8

func (t *TickSize) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both quoted and numeric tick sizes returned by CLOB.

type TickSizeResponse

type TickSizeResponse struct {
	// MinimumTickSize is the minimum price increment.
	MinimumTickSize TickSize `json:"minimum_tick_size"`
}

TickSizeResponse contains the minimum price increment.

type Time

type Time = shared.Time

type Token

type Token struct {
	// TokenID is the ERC-1155 token identifier.
	TokenID String `json:"token_id"`
	// Outcome is the outcome label (e.g. "Yes", "No").
	Outcome string `json:"outcome"`
	// Price is the current market price.
	Price Float64 `json:"price"`
	// Winner is true when this outcome has been resolved as correct.
	Winner bool `json:"winner,omitempty"`
}

Token represents a conditional outcome token.

type Trade

type Trade struct {
	// ID is the trade identifier.
	ID string `json:"id"`
	// TakerOrderID is the taker's order ID.
	TakerOrderID string `json:"taker_order_id"`
	// Market is the condition ID.
	Market string `json:"market"`
	// AssetID is the conditional token identifier.
	AssetID String `json:"asset_id"`
	// Side is the trade direction.
	Side Side `json:"side"`
	// Size is the matched quantity.
	Size Float64 `json:"size"`
	// FeeRateBps is the fee rate in basis points.
	FeeRateBps Float64 `json:"fee_rate_bps"`
	// Price is the execution price.
	Price Float64 `json:"price"`
	// Status is the trade processing status.
	Status string `json:"status"`
	// MatchTime is when the trade was matched.
	MatchTime Time `json:"match_time"`
	// LastUpdate is the last status change.
	LastUpdate Time `json:"last_update"`
	// Outcome is the outcome label.
	Outcome string `json:"outcome"`
	// BucketIndex is the price bucket index.
	BucketIndex Int `json:"bucket_index"`
	// Owner is the trade owner address.
	Owner string `json:"owner"`
	// MakerAddress is the maker wallet address.
	MakerAddress string `json:"maker_address"`
	// MakerOrders lists the maker orders that were filled.
	MakerOrders []MakerOrder `json:"maker_orders"`
	// TransactionHash is the on-chain transaction hash.
	TransactionHash string `json:"transaction_hash"`
	// TraderSide identifies taker or maker role.
	TraderSide string `json:"trader_side"`
	// ErrorMsg contains error details on failure.
	ErrorMsg string `json:"error_msg"`
}

Trade represents a matched fill between maker and taker.

type TradeParams

type TradeParams struct {
	// ID filters by trade identifier.
	ID string `url:"id,omitempty"`
	// TakerAddress filters by taker wallet address.
	TakerAddress string `url:"taker,omitempty"`
	// MakerAddress filters by maker wallet address.
	MakerAddress string `url:"maker,omitempty"`
	// Market filters by condition ID.
	Market string `url:"market,omitempty"`
	// AssetID filters by conditional token identifier.
	AssetID string `url:"asset_id,omitempty"`
	// Before filters trades before this Unix timestamp.
	Before int64 `url:"before,omitempty"`
	// After filters trades after this Unix timestamp.
	After int64 `url:"after,omitempty"`
}

TradeParams filters GET /data/trades requests.

type TxReceipt

type TxReceipt struct {
	// Hash is the transaction hash.
	Hash common.Hash
	// BlockNumber is the block that included the transaction.
	BlockNumber uint64
}

TxReceipt is the minimal transaction receipt returned by CTF helpers.

type Uint64

type Uint64 = shared.Uint64

type UserEarning

type UserEarning struct {
	// Date is the earning date.
	Date Date `json:"date"`
	// ConditionID is the market condition identifier.
	ConditionID string `json:"condition_id"`
	// AssetAddress is the reward asset contract address.
	AssetAddress string `json:"asset_address"`
	// MakerAddress is the maker wallet address.
	MakerAddress string `json:"maker_address"`
	// Earnings is the total reward earned in USDC.
	Earnings Float64 `json:"earnings"`
	// AssetRate is the reward asset exchange rate.
	AssetRate Float64 `json:"asset_rate"`
}

UserEarning records a maker's reward earning for one market asset.

type UserRewardsEarning

type UserRewardsEarning struct {
	ConditionID           string          `json:"condition_id"`
	Question              string          `json:"question"`
	MarketSlug            string          `json:"market_slug"`
	EventSlug             string          `json:"event_slug"`
	Image                 string          `json:"image"`
	RewardsMaxSpread      Float64         `json:"rewards_max_spread"`
	RewardsMinSize        Float64         `json:"rewards_min_size"`
	MarketCompetitiveness Float64         `json:"market_competitiveness"`
	Tokens                []Token         `json:"tokens"`
	RewardsConfig         []RewardsConfig `json:"rewards_config"`
	MakerAddress          string          `json:"maker_address"`
	EarningPercentage     Float64         `json:"earning_percentage"`
	Earnings              []Earning       `json:"earnings"`
}

type WSAuth

type WSAuth struct {
	// APIKey is the WebSocket API key.
	APIKey string `json:"apiKey"`
	// Secret is the WebSocket HMAC secret.
	Secret string `json:"secret"`
	// Passphrase protects the WebSocket API key.
	Passphrase string `json:"passphrase"`
}

WSAuth holds WebSocket authentication material.

Directories

Path Synopsis
ws
Package ws provides WebSocket clients for live Polymarket CLOB order book and user updates.
Package ws provides WebSocket clients for live Polymarket CLOB order book and user updates.
rtds
Package rtds implements the Polymarket real-time data stream client.
Package rtds implements the Polymarket real-time data stream client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL