kalshi

package module
v0.0.0-...-312d185 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: CC0-1.0 Imports: 28 Imported by: 0

README

kalshi

Go Reference Go workflow status codecov

Package kalshi provides a Go implementation of the Kalshi API.

go get github.com/ammario/kalshi

Supports:

  • Streaming market data feed
  • All core API endpoints
  • Rate-limits
  • Cursor-based pagination

Basic Usage

See the _test.go files for more examples.

func main() {
  client := New(kalshi.APIProdURL)
  ctx := context.Background()
  err := client.Login(
    ctx,
    "jill@live.com", "hunter12",
  )
  if err != nil {
    panic(err)
  }
  defer client.Logout(ctx)

  // Get all S&P 500 markets.
  markets, err := client.Markets(ctx, kalshi.MarketsRequest{
    SeriesTicker: "INX"
  })
  if err != nil {
    panic(err)
  }

  for _, market := range markets {
    fmt.Println("found market", market)
  }
}

Endpoint Support

Markets

kalshi supports all Market endpoints.

Endpoint Support Status
GetSeries
GetEvent
GetMarkets
GetTrades
GetMarket
GetMarketHistory
GetMarketOrderbook
GetSeries
Exchange

kalshi supports all Exchange endpoints.

Endpoint Support Status
GetExchangeSchedule
GetExchangeStatus
Auth

kalshi supports all Auth endpoints.

Endpoint Support Status
Login
Logout
Portfolio

kalshi has mixed support for Portfolio endpoints.

Endpoint Support Status
GetBalance
GetFills
GetOrders
CreateOrder
GetOrder
CancelOrder
BatchCreateOrders
BatchCancelOrders
DecreaseOrder
GetPositions
GetPortolioSettlements
Market Data Feed

Market Data Feed is supported, although it hasn't been thoroughly tested. You may open a feed through (*Client).OpenFeed().

Documentation

Overview

Package kalshi implements a Go client for the Kalshi API.

Index

Constants

View Source
const (
	APIDemoURL = "https://demo-api.kalshi.co/trade-api/v2/"
	APIProdURL = "https://demo-api.kalshi.co/trade-api/v2/"
)

Variables

View Source
var (
	ErrInvalidPEMBlock = errors.New("failed to parse PEM block")
	ErrEncryptedKey    = errors.New("private key is encrypted but no password provided")
	ErrKeyDecryption   = errors.New("failed to decrypt private key")
)

Functions

func LoadPrivateKeyFromPEM

func LoadPrivateKeyFromPEM(pemData []byte, password string) (*rsa.PrivateKey, error)

LoadPrivateKeyFromPEM loads an RSA private key from PEM-encoded data. If the key is encrypted, a password must be provided.

Types

type Candlestick

type Candlestick struct {
	EndPeriodTs    int64        `json:"end_period_ts"`
	YesBid         Ohlc         `json:"yes_bid"`
	YesAsk         Ohlc         `json:"yes_ask"`
	Price          OhlcExtended `json:"price"`
	Volume         int64        `json:"volume"`
	VolumeFp       string       `json:"volume_fp"`
	OpenInterest   int64        `json:"open_interest"`
	OpenInterestFp string       `json:"open_interest_fp"`
}

Candlestick represents a single candlestick data point.

type Cents

type Cents int

func (Cents) String

func (c Cents) String() string

type Client

type Client struct {
	// BaseURL is one of APIDemoURL or APIProdURL.
	BaseURL string

	// See https://trading-api.readme.io/reference/tiers-and-rate-limits.
	WriteRatelimit *rate.Limiter
	ReadRateLimit  *rate.Limiter
	// contains filtered or unexported fields
}

Client must be instantiated via NewClient.

func New deprecated

func New(baseURL string) *Client

Deprecated: New creates a client without authentication. Use NewClient instead. This function is kept for backward compatibility but will not work with the API.

func NewClient

func NewClient(keyID string, privateKey *rsa.PrivateKey, baseURL string) *Client

NewClient creates a new Kalshi client with RSA key-based authentication. The client is ready to use immediately without needing to call Login.

func (*Client) Balance

func (c *Client) Balance(ctx context.Context) (Cents, error)

Balance is described here: https://trading-api.readme.io/reference/getbalance.

func (*Client) CancelOrder

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

CancelOrder is described here: https://trading-api.readme.io/reference/cancelorder.

func (*Client) CreateOrder

func (c *Client) CreateOrder(ctx context.Context, req CreateOrderRequest) (*Order, error)

CreateOrder is described here: https://trading-api.readme.io/reference/createorder.

func (*Client) DecreaseOrder

func (c *Client) DecreaseOrder(ctx context.Context, orderID string, req DecreaseOrderRequest) (*Order, error)

DecreaseOrder is described here: https://trading-api.readme.io/reference/decreaseorder.

func (*Client) Event

func (c *Client) Event(ctx context.Context, event string) (*EventResponse, error)

Event is described here: https://trading-api.readme.io/reference/getevent.

func (*Client) Events

func (c *Client) Events(ctx context.Context, req EventsRequest) (*EventsResponse, error)

Events is described here: https://trading-api.readme.io/reference/getevents.

func (*Client) ExchangeSchedule

func (c *Client) ExchangeSchedule(ctx context.Context) (*ExchangeScheduleResponse, error)

ExchangeSchedule is described here: https://trading-api.readme.io/reference/getexchangeschedule.

func (*Client) ExchangeStatus

func (c *Client) ExchangeStatus(ctx context.Context) (*ExchangeStatusResponse, error)

ExchangeStatus is described here: https://trading-api.readme.io/reference/getexchangestatus.

func (*Client) Fills

func (c *Client) Fills(ctx context.Context, req FillsRequest) (*FillsResponse, error)

Fills is described here: https://trading-api.readme.io/reference/getfills.

func (*Client) GetMarketCandlesticks

func (c *Client) GetMarketCandlesticks(
	ctx context.Context,
	req GetMarketCandlesticksRequest,
) (*GetMarketCandlesticksResponse, error)

GetMarketCandlesticks is described here: https://docs.kalshi.com/api-reference/market/get-market-candlesticks.

func (*Client) ListSeries

func (c *Client) ListSeries(ctx context.Context, req ListSeriesRequest) (*ListSeriesResponse, error)

ListSeries is described here: https://trading-api.readme.io/reference/listseries.

func (*Client) Market

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

Market is described here: https://trading-api.readme.io/reference/getmarket.

func (*Client) MarketHistory

func (c *Client) MarketHistory(
	ctx context.Context,
	ticker string,
	req MarketHistoryRequest,
) (*MarketHistoryResponse, error)

func (*Client) MarketOrderBook

func (c *Client) MarketOrderBook(ctx context.Context, ticker string) (*MarketOrderBookResponse, error)

MarketOrderBook is described here: https://trading-api.readme.io/reference/getmarketorderbook.

func (*Client) Markets

func (c *Client) Markets(
	ctx context.Context,
	req MarketsRequest,
) (*MarketsResponse, error)

Markets is described here: https://trading-api.readme.io/reference/getmarkets.

func (*Client) OpenFeed

func (c *Client) OpenFeed(ctx context.Context) (*Feed, error)

OpenFeed creates a new market data streaming connection. OpenFeed is described in more detail here: https://trading-api.readme.io/reference/introduction. WARNING: OpenFeed has not been thoroughly tested.

func (*Client) Order

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

Order is described here: https://trading-api.readme.io/reference/getorder.

func (*Client) Orders

func (c *Client) Orders(ctx context.Context, req OrdersRequest) (*OrdersResponse, error)

Orders is described here: https://trading-api.readme.io/reference/getorders

func (*Client) Positions

func (c *Client) Positions(ctx context.Context, req PositionsRequest) (*PositionsResponse, error)

Positions is described here: https://trading-api.readme.io/reference/getpositions.

func (*Client) Series

func (c *Client) Series(ctx context.Context, seriesTicker string, req GetSeriesRequest) (*Series, error)

Series is described here: https://trading-api.readme.io/reference/getseries.

func (*Client) Settlements

func (c *Client) Settlements(ctx context.Context, req SettlementsRequest) (*SettlementsResponse, error)

Settlements is described here: https://trading-api.readme.io/reference/getportfoliosettlements.

func (*Client) Trades

func (c *Client) Trades(
	ctx context.Context,
	req TradesRequest,
) (*TradesResponse, error)

Trades is described here: https://trading-api.readme.io/reference/gettrades.

type CreateOrderRequest

type CreateOrderRequest struct {
	Action        OrderAction `json:"action,omitempty"`
	BuyMaxCost    Cents       `json:"buy_max_cost,omitempty"`
	Count         int         `json:"count,omitempty"`
	Expiration    *Timestamp  `json:"expiration_ts,omitempty"`
	NoPrice       Cents       `json:"no_price,omitempty"`
	YesPrice      Cents       `json:"yes_price,omitempty"`
	Ticker        string      `json:"ticker,omitempty"`
	ClientOrderID string      `json:"client_order_id,omitempty"`
	Type          OrderType   `json:"type"`
	Side          Side        `json:"side"`
}

CreateOrderRequest is described here: https://trading-api.readme.io/reference/createorder.

func (*CreateOrderRequest) Price

func (o *CreateOrderRequest) Price() Cents

func (*CreateOrderRequest) SetPrice

func (c *CreateOrderRequest) SetPrice(p Cents)

SetPrice sets the price of the order based on its side.

func (*CreateOrderRequest) String

func (c *CreateOrderRequest) String() string

String returns a human-readable representation of the order.

type CursorRequest

type CursorRequest struct {
	Limit  int    `url:"limit,omitempty"`
	Cursor string `url:"cursor,omitempty"`
}

type CursorResponse

type CursorResponse struct {
	Cursor string `json:"cursor"`
}

type DecreaseOrderRequest

type DecreaseOrderRequest struct {
	ReduceBy int `json:"reduce_by,omitempty"`
	ReduceTo int `json:"reduce_to,omitempty"`
}

DecreaseOrder is described here: https://trading-api.readme.io/reference/decreaseorder.

type Event

type Event struct {
	Category          string    `json:"category"`
	EventTicker       string    `json:"event_ticker"`
	MutuallyExclusive bool      `json:"mutually_exclusive"`
	SeriesTicker      string    `json:"series_ticker"`
	StrikeDate        time.Time `json:"strike_date"`
	StrikePeriod      string    `json:"strike_period"`
	SubTitle          string    `json:"sub_title"`
	Title             string    `json:"title"`
}

Event is described here: https://trading-api.readme.io/reference/getevents.

type EventPosition

type EventPosition struct {
	EventExposure     Cents  `json:"event_exposure"`
	EventTicker       string `json:"event_ticker"`
	FeesPaid          Cents  `json:"fees_paid"`
	RealizedPnl       Cents  `json:"realized_pnl"`
	RestingOrderCount int    `json:"resting_order_count"`
	TotalCost         Cents  `json:"total_cost"`
}

EventPosition is described here: https://trading-api.readme.io/reference/getpositions.

type EventResponse

type EventResponse struct {
	Event   Event    `json:"event"`
	Markets []Market `json:"markets"`
}

EventResponse is described here: https://trading-api.readme.io/reference/getevent.

type EventsRequest

type EventsRequest struct {
	CursorRequest
	// Status is one of "open", "closed", or "settled".
	Status       string `url:"status,omitempty"`
	SeriesTicker string `url:"series_ticker,omitempty"`
}

EventsRequest is described here: https://trading-api.readme.io/reference/getevents.

type EventsResponse

type EventsResponse struct {
	CursorResponse
	Events []Event `json:"events"`
}

EventsResponse is described here: https://trading-api.readme.io/reference/getevents.

type ExchangeScheduleResponse

type ExchangeScheduleResponse struct {
	Schedule struct {
		StandardHours struct {
			Monday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"monday"`
			Tuesday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"tuesday"`
			Wednesday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"wednesday"`
			Thursday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"thursday"`
			Friday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"friday"`
			Saturday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"saturday"`
			Sunday struct {
				OpenTime  string `json:"open_time"`
				CloseTime string `json:"close_time"`
			} `json:"sunday"`
		} `json:"standard_hours"`
		MaintenanceWindows []struct {
			EndDatetime   string `json:"end_datetime"`
			StartDatetime string `json:"start_datetime"`
		} `json:"maintenance_windows,omitempty"`
	} `json:"schedule"`
}

ExchangeScheduleResponse is described here: https://trading-api.readme.io/reference/getexchangeschedule.

type ExchangeStatusResponse

type ExchangeStatusResponse struct {
	ExchangeActive bool `json:"exchange_active,omitempty"`
	TradingActive  bool `json:"trading_active,omitempty"`
}

ExchangeStatusResponse is described here: https://trading-api.readme.io/reference/getexchangestatus.

type Feed

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

Feed is a websocket connection to the Kalshi streaming API. Feed is described in more detail here: https://trading-api.readme.io/reference/introduction. WARNING: Feed has not been thoroughly tested.

func (*Feed) Book

func (s *Feed) Book(ctx context.Context, marketTicker string, feed chan<- *StreamOrderBook) error

Book instantiates a streaming order book feed for market.

func (*Feed) Close

func (f *Feed) Close() error

type Fill

type Fill struct {
	Action      OrderAction `json:"action"`
	Count       int         `json:"count"`
	CreatedTime time.Time   `json:"created_time"`
	IsTaker     bool        `json:"is_taker"`
	NoPrice     Cents       `json:"no_price"`
	OrderID     string      `json:"order_id"`
	Side        Side        `json:"side"`
	Ticker      string      `json:"ticker"`
	TradeID     string      `json:"trade_id"`
	YesPrice    Cents       `json:"yes_price"`
}

Fill is described here: https://trading-api.readme.io/reference/getfills.

type FillsRequest

type FillsRequest struct {
	CursorRequest
	Ticker  string    `url:"ticker,omitempty"`
	OrderID string    `url:"order_id,omitempty"`
	MinTS   Timestamp `url:"min_ts,omitempty"`
	MaxTS   Timestamp `url:"max_ts,omitempty"`
}

FillsRequest is described here: https://trading-api.readme.io/reference/getfills.

type FillsResponse

type FillsResponse struct {
	CursorResponse
	Fills []Fill `json:"fills"`
}

FillsResponse is described here: https://trading-api.readme.io/reference/getfills.

type GetMarketCandlesticksRequest

type GetMarketCandlesticksRequest struct {
	SeriesTicker             string `url:"-"`
	Ticker                   string `url:"-"`
	StartTs                  int64  `url:"start_ts,omitempty"`
	EndTs                    int64  `url:"end_ts,omitempty"`
	PeriodInterval           int    `url:"period_interval,omitempty"`
	IncludeLatestBeforeStart bool   `url:"include_latest_before_start,omitempty"`
}

GetMarketCandlesticksRequest is described here: https://docs.kalshi.com/api-reference/market/get-market-candlesticks.

type GetMarketCandlesticksResponse

type GetMarketCandlesticksResponse struct {
	Ticker       string        `json:"ticker"`
	Candlesticks []Candlestick `json:"candlesticks"`
}

GetMarketCandlesticksResponse is described here: https://docs.kalshi.com/api-reference/market/get-market-candlesticks.

type GetSeriesRequest

type GetSeriesRequest struct {
	IncludeVolume bool `url:"include_volume,omitempty"`
}

GetSeriesRequest is described here: https://trading-api.readme.io/reference/getseries.

type ListSeriesRequest

type ListSeriesRequest struct {
	Category               string `url:"category,omitempty"`
	Tags                   string `url:"tags,omitempty"`
	IncludeProductMetadata bool   `url:"include_product_metadata,omitempty"`
	IncludeVolume          bool   `url:"include_volume,omitempty"`
}

ListSeriesRequest is described here: https://trading-api.readme.io/reference/listseries.

type ListSeriesResponse

type ListSeriesResponse struct {
	Series []Series `json:"series"`
}

ListSeriesResponse is described here: https://trading-api.readme.io/reference/listseries.

type Market

type Market struct {
	Ticker                   string    `json:"ticker"`
	EventTicker              string    `json:"event_ticker"`
	MarketType               string    `json:"market_type"`
	Title                    string    `json:"title"`
	Subtitle                 string    `json:"subtitle"`
	YesSubTitle              string    `json:"yes_sub_title"`
	NoSubTitle               string    `json:"no_sub_title"`
	CreatedTime              time.Time `json:"created_time"`
	UpdatedTime              time.Time `json:"updated_time"`
	OpenTime                 time.Time `json:"open_time"`
	CloseTime                time.Time `json:"close_time"`
	ExpirationTime           time.Time `json:"expiration_time"`
	LatestExpirationTime     time.Time `json:"latest_expiration_time"`
	ExpectedExpirationTime   time.Time `json:"expected_expiration_time"`
	SettlementTimerSeconds   int       `json:"settlement_timer_seconds"`
	Status                   string    `json:"status"`
	ResponsePriceUnits       string    `json:"response_price_units"`
	YesBid                   Cents     `json:"yes_bid"`
	YesBidDollars            string    `json:"yes_bid_dollars"`
	YesAsk                   Cents     `json:"yes_ask"`
	YesAskDollars            string    `json:"yes_ask_dollars"`
	NoBid                    Cents     `json:"no_bid"`
	NoBidDollars             string    `json:"no_bid_dollars"`
	NoAsk                    Cents     `json:"no_ask"`
	NoAskDollars             string    `json:"no_ask_dollars"`
	LastPrice                Cents     `json:"last_price"`
	LastPriceDollars         string    `json:"last_price_dollars"`
	PreviousYesBid           Cents     `json:"previous_yes_bid"`
	PreviousYesBidDollars    string    `json:"previous_yes_bid_dollars"`
	PreviousYesAsk           Cents     `json:"previous_yes_ask"`
	PreviousYesAskDollars    string    `json:"previous_yes_ask_dollars"`
	PreviousPrice            Cents     `json:"previous_price"`
	PreviousPriceDollars     string    `json:"previous_price_dollars"`
	Volume                   int       `json:"volume"`
	VolumeFp                 string    `json:"volume_fp"`
	Volume24H                int       `json:"volume_24h"`
	Volume24HFp              string    `json:"volume_24h_fp"`
	Liquidity                Cents     `json:"liquidity"`
	LiquidityDollars         string    `json:"liquidity_dollars"`
	OpenInterest             int       `json:"open_interest"`
	OpenInterestFp           string    `json:"open_interest_fp"`
	NotionalValue            Cents     `json:"notional_value"`
	NotionalValueDollars     string    `json:"notional_value_dollars"`
	Result                   string    `json:"result"`
	CanCloseEarly            bool      `json:"can_close_early"`
	FractionalTradingEnabled bool      `json:"fractional_trading_enabled"`
	ExpirationValue          string    `json:"expiration_value"`
	SettlementValue          Cents     `json:"settlement_value"`
	SettlementValueDollars   string    `json:"settlement_value_dollars"`
	SettlementTs             time.Time `json:"settlement_ts"`
	FeeWaiverExpirationTime  time.Time `json:"fee_waiver_expiration_time"`
	EarlyCloseCondition      string    `json:"early_close_condition"`
	TickSize                 Cents     `json:"tick_size"`
	RulesPrimary             string    `json:"rules_primary"`
	RulesSecondary           string    `json:"rules_secondary"`
	PriceLevelStructure      string    `json:"price_level_structure"`
	PriceRanges              []struct {
		Start string `json:"start"`
		End   string `json:"end"`
		Step  string `json:"step"`
	} `json:"price_ranges"`
	StrikeType          string         `json:"strike_type"`
	FloorStrike         float64        `json:"floor_strike,omitempty"`
	CapStrike           float64        `json:"cap_strike,omitempty"`
	FunctionalStrike    string         `json:"functional_strike"`
	CustomStrike        map[string]any `json:"custom_strike"`
	MveCollectionTicker string         `json:"mve_collection_ticker"`
	MveSelectedLegs     []struct {
		EventTicker               string `json:"event_ticker"`
		MarketTicker              string `json:"market_ticker"`
		Side                      string `json:"side"`
		YesSettlementValueDollars string `json:"yes_settlement_value_dollars"`
	} `json:"mve_selected_legs"`
	PrimaryParticipantKey string `json:"primary_participant_key"`
	IsProvisional         bool   `json:"is_provisional"`
	Category              string `json:"category"`
	RiskLimit             Cents  `json:"risk_limit_cents"`
}

Market is described here: https://trading-api.readme.io/reference/getmarkets.

func (*Market) EstimateReturn

func (m *Market) EstimateReturn(p *MarketPosition) Cents

EstimateReturn shows the estimated return for an open position.

func (*Market) MarketValue

func (m *Market) MarketValue(p *MarketPosition) Cents

func (*Market) NoMidPrice

func (m *Market) NoMidPrice() Cents

func (*Market) YesMidPrice

func (m *Market) YesMidPrice() Cents

type MarketHistory

type MarketHistory struct {
	NoAsk        Cents     `json:"no_ask"`
	NoBid        Cents     `json:"no_bid"`
	OpenInterest int       `json:"open_interest"`
	Ts           Timestamp `json:"ts"`
	Volume       int       `json:"volume"`
	YesAsk       Cents     `json:"yes_ask"`
	YesBid       Cents     `json:"yes_bid"`
	YesPrice     Cents     `json:"yes_price"`
}

MarketHistory is described here: https://trading-api.readme.io/reference/getmarkethistory.

type MarketHistoryRequest

type MarketHistoryRequest struct {
	CursorRequest
	MinTS Timestamp `json:"min_ts,omitempty"`
	MaxTS Timestamp `json:"max_ts,omitempty"`
}

MarketHistoryRequest is described here: https://trading-api.readme.io/reference/getmarkethistory.

type MarketHistoryResponse

type MarketHistoryResponse struct {
	CursorResponse
	History []MarketHistory `json:"history"`
	Ticker  string          `json:"ticker"`
}

MarketHistoryResponse is described here: https://trading-api.readme.io/reference/getmarkethistory.

type MarketOrderBookResponse

type MarketOrderBookResponse struct {
	OrderBook   OrderBook `json:"orderbook"`
	OrderBookFp struct {
		YesBidsDollars []OrderBookBidFp `json:"yes_dollars"`
		NoBidsDollars  []OrderBookBidFp `json:"no_dollars"`
	} `json:"orderbook_fp"`
}

MarketOrderBookResponse is described here: https://trading-api.readme.io/reference/getmarketorderbook.

type MarketPosition

type MarketPosition struct {
	// Fees paid on fill orders, in cents.
	FeesPaid Cents `json:"fees_paid"`
	// Number of contracts bought in this market. Negative means NO contracts and positive means YES contracts.
	Position int `json:"position"`
	// Locked in profit and loss, in cents.
	RealizedPnl Cents `json:"realized_pnl"`
	// Aggregate size of resting orders in contract units.
	RestingOrdersCount int `json:"resting_orders_count"`
	// Unique identifier for the market.
	Ticker string `json:"ticker"`
	// Total spent on this market in cents.
	TotalTraded Cents `json:"total_traded"`
	// Cost of the aggregate market position in cents.
	MarketExposure Cents `json:"market_exposure"`
}

MarketPosition is described here: https://trading-api.readme.io/reference/getpositions.

func (*MarketPosition) AbsPosition

func (p *MarketPosition) AbsPosition() int

func (*MarketPosition) AvgPrice

func (p *MarketPosition) AvgPrice() Cents

func (*MarketPosition) String

func (p *MarketPosition) String() string

type MarketsRequest

type MarketsRequest struct {
	CursorRequest
	EventTicker  string `url:"event_ticker,omitempty"`
	SeriesTicker string `url:"series_ticker,omitempty"`
	MaxCloseTs   int    `url:"max_close_ts,omitempty"`
	MinCloseTs   int    `url:"min_close_ts,omitempty"`
	// Status is one of "open", "closed", and "settled"
	Status  string   `url:"status,omitempty"`
	Tickers []string `url:"status,omitempty"`
}

MarketsRequest is described here: https://trading-api.readme.io/reference/getmarkets.

type MarketsResponse

type MarketsResponse struct {
	Markets []Market `json:"markets,omitempty"`
	CursorResponse
}

MarketsResponse is described here: https://trading-api.readme.io/reference/getmarkets.

type Ohlc

type Ohlc struct {
	Open         int64  `json:"open"`
	OpenDollars  string `json:"open_dollars"`
	Low          int64  `json:"low"`
	LowDollars   string `json:"low_dollars"`
	High         int64  `json:"high"`
	HighDollars  string `json:"high_dollars"`
	Close        int64  `json:"close"`
	CloseDollars string `json:"close_dollars"`
}

Ohlc represents Open, High, Low, Close values.

type OhlcExtended

type OhlcExtended struct {
	Ohlc
	Mean            int64  `json:"mean"`
	MeanDollars     string `json:"mean_dollars"`
	Previous        int64  `json:"previous"`
	PreviousDollars string `json:"previous_dollars"`
	Min             int64  `json:"min"`
	MinDollars      string `json:"min_dollars"`
	Max             int64  `json:"max"`
	MaxDollars      string `json:"max_dollars"`
}

OhlcExtended represents extended OHLC values including Mean, Previous, Min, Max.

type Order

type Order struct {
	Action           OrderAction `json:"action"`
	ClientOrderID    string      `json:"client_order_id"`
	CloseCancelCount int         `json:"close_cancel_count"`
	CreatedTime      *Time       `json:"created_time"`
	DecreaseCount    int         `json:"decrease_count"`
	ExpirationTime   *Time       `json:"expiration_time"`
	FccCancelCount   int         `json:"fcc_cancel_count"`
	LastUpdateTime   *Time       `json:"last_update_time"`
	MakerFillCost    int         `json:"maker_fill_cost"`
	MakerFillCount   int         `json:"maker_fill_count"`
	MakerFees        Cents       `json:"maker_fees"`
	NoPrice          Cents       `json:"no_price"`
	OrderID          string      `json:"order_id"`
	PlaceCount       int         `json:"place_count"`
	QueuePosition    int         `json:"queue_position"`
	RemainingCount   int         `json:"remaining_count"`
	Side             Side        `json:"side"`
	Status           OrderStatus `json:"status"`
	TakerFees        Cents       `json:"taker_fees"`
	TakerFillCost    Cents       `json:"taker_fill_cost"`
	TakerFillCount   int         `json:"taker_fill_count"`
	Ticker           string      `json:"ticker"`
	Type             OrderType   `json:"type"`
	UserID           string      `json:"user_id"`
	YesPrice         Cents       `json:"yes_price"`
}

Order is described here: https://trading-api.readme.io/reference/getorders.

func (*Order) Price

func (o *Order) Price() Cents

type OrderAction

type OrderAction string
const (
	Buy  OrderAction = "buy"
	Sell OrderAction = "sell"
)

type OrderBook

type OrderBook struct {
	YesBids        OrderBookBids        `json:"yes"`
	NoBids         OrderBookBids        `json:"no"`
	YesBidsDollars []OrderBookBidDollar `json:"yes_dollars"`
	NoBidsDollars  []OrderBookBidDollar `json:"no_dollars"`
}

OrderBook is a snapshot of the order book.

Make sure you understand the market structure before using this struct. A central feature of the Kalshi contract model is that a No bid corresponds to a Yes ask of the complementary price and vice versa. That is, a No bid at 40 cents is equivalent to a Yes ask at 60 cents. This OrderBook type is a a list of bids on either side.

Detailed documentation can be found here: https://trading-api.readme.io/reference/getmarketorderbook.

func (OrderBook) BestNoOffer

func (b OrderBook) BestNoOffer(quantity int) (Cents, bool)

BestNoOffer returns the best average asking price for No contracts given a desired quantity.

func (OrderBook) BestYesOffer

func (b OrderBook) BestYesOffer(quantity int) (Cents, bool)

BestYesOffer returns the best average asking price for Yes contracts given a desired quantity.

func (OrderBook) NoLiquidity

func (b OrderBook) NoLiquidity() Cents

NoLiquidity returns the total sum required to buy all available No contracts on the market.

func (OrderBook) NoOffersUnderLimit

func (b OrderBook) NoOffersUnderLimit(limit Cents) int

NoOffersUnderLimit is the quantity of No contracts available to be taken at a price less than or equal to the given limit.

func (OrderBook) NoTotalOffers

func (b OrderBook) NoTotalOffers() int

NoTotalOffers is the quantity of total No contracts available to be taken.

func (OrderBook) YesLiquidity

func (b OrderBook) YesLiquidity() Cents

YesLiquidity returns the total sum required to buy all available Yes contracts on the market.

func (OrderBook) YesOffersUnderLimit

func (b OrderBook) YesOffersUnderLimit(limit Cents) int

YesOffersUnderLimit is the quantity of Yes contracts available to be taken at a price less than or equal to the given limit.

func (OrderBook) YesTotalOffers

func (b OrderBook) YesTotalOffers() int

YesTotalOffers is the quantity of total Yes contracts available to be taken.

type OrderBookBid

type OrderBookBid struct {
	Price    Cents
	Quantity int
}

OrderBookBid represents the aggregate quantity of all resting Bids at a given price.

func (OrderBookBid) MarshalJSON

func (o OrderBookBid) MarshalJSON() ([]byte, error)

func (*OrderBookBid) UnmarshalJSON

func (o *OrderBookBid) UnmarshalJSON(b []byte) error

type OrderBookBidDollar

type OrderBookBidDollar struct {
	Price    string
	Quantity int
}

OrderBookBidDollar represents a bid level with a dollar price string and integer quantity, serialized as ["0.1500", 100].

func (*OrderBookBidDollar) UnmarshalJSON

func (o *OrderBookBidDollar) UnmarshalJSON(b []byte) error

type OrderBookBidFp

type OrderBookBidFp struct {
	Price    string
	Quantity string
}

OrderBookBidFp represents a fractional bid level with dollar price and quantity both as strings, serialized as ["0.1500", "100.00"].

func (*OrderBookBidFp) UnmarshalJSON

func (o *OrderBookBidFp) UnmarshalJSON(b []byte) error

type OrderBookBids

type OrderBookBids []OrderBookBid

type OrderStatus

type OrderStatus string
const (
	Resting  OrderStatus = "resting"
	Canceled OrderStatus = "canceled"
	Executed OrderStatus = "executed"
	Pending  OrderStatus = "pending"
)

type OrderType

type OrderType string
const (
	MarketOrder OrderType = "market"
	LimitOrder  OrderType = "limit"
)

type OrdersRequest

type OrdersRequest struct {
	Ticker string      `url:"ticker,omitempty"`
	Status OrderStatus `url:"status,omitempty"`
}

OrdersRequest is described here: https://trading-api.readme.io/reference/getorders

type OrdersResponse

type OrdersResponse struct {
	CursorResponse
	Orders []Order `json:"orders"`
}

Orders is described here: https://trading-api.readme.io/reference/getorders.

type PositionsRequest

type PositionsRequest struct {
	CursorRequest
	Limit            int              `url:"limit,omitempty"`
	SettlementStatus SettlementStatus `url:"settlement_status,omitempty"`
	Ticker           string           `url:"ticker,omitempty"`
	EventTicker      string           `url:"event_ticker,omitempty"`
}

Position is described here: https://trading-api.readme.io/reference/getpositions.

type PositionsResponse

type PositionsResponse struct {
	CursorResponse
	EventPositions  []EventPosition  `json:"event_positions"`
	MarketPositions []MarketPosition `json:"market_positions"`
}

PositionsResponse is described here: https://trading-api.readme.io/reference/getpositions.

type Series

type Series struct {
	Ticker                 string             `json:"ticker"`
	Frequency              string             `json:"frequency"`
	Title                  string             `json:"title"`
	Category               string             `json:"category"`
	Tags                   []string           `json:"tags"`
	SettlementSources      []SettlementSource `json:"settlement_sources"`
	ContractURL            string             `json:"contract_url"`
	ContractTermsURL       string             `json:"contract_terms_url"`
	FeeType                string             `json:"fee_type"`
	FeeMultiplier          float64            `json:"fee_multiplier"`
	AdditionalProhibitions []string           `json:"additional_prohibitions"`
	ProductMetadata        map[string]any     `json:"product_metadata"`
	Volume                 int                `json:"volume"`
	VolumeFp               string             `json:"volume_fp"`
}

Series is described here: https://trading-api.readme.io/reference/getseries.

type Settlement

type Settlement struct {
	MarketResult string    `json:"market_result"`
	NoCount      int       `json:"no_count"`
	NoTotalCost  int       `json:"no_total_cost"`
	Revenue      int       `json:"revenue"`
	SettledTime  time.Time `json:"settled_time"`
	Ticker       string    `json:"ticker"`
	YesCount     int       `json:"yes_count"`
	YesTotalCost int       `json:"yes_total_cost"`
}

Settlement is described here: https://trading-api.readme.io/reference/getportfoliosettlements.

type SettlementSource

type SettlementSource struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

SettlementSource represents a settlement source for a series.

type SettlementStatus

type SettlementStatus string
const (
	StatusAll       SettlementStatus = "all"
	StatusSettled   SettlementStatus = "settled"
	StatusUnsettled SettlementStatus = "unsettled"
)

type SettlementsRequest

type SettlementsRequest struct {
	CursorRequest
}

PortfolioSettlements is described here: https://trading-api.readme.io/reference/getportfoliosettlements.

type SettlementsResponse

type SettlementsResponse struct {
	CursorResponse
	Settlements []Settlement `json:"settlements"`
}

SettlementsResponse is described here: https://trading-api.readme.io/reference/getportfoliosettlements.

type Side

type Side string

Side is either Yes or No.

const (
	Yes Side = "yes"
	No  Side = "no"
)

func SideBool

func SideBool(yes bool) Side

SideBool turns a Yes bool into a Side.

type StreamOrderBook

type StreamOrderBook struct {
	OrderBook
	LoadedAt time.Time
	// MarketID is included so multiple streaming order books can be multiplexed
	// onto one channel.
	MarketID string
}

StreamOrderBook is sent by the streaming connection.

type Time

type Time struct {
	time.Time
}

Time is a time.Time that tolerates additional '"' characters. Kalshi API endpoints use both RFC3339 and POSIX timestamps.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

type Timestamp

type Timestamp time.Time

Timestamp represents a POSIX Timestamp in seconds.

func ExpireAfter

func ExpireAfter(duration time.Duration) *Timestamp

ExpireAfter is a helper function for creating an expiration timestamp some duration after the current time.

func OrderExecuteImmediateOrCancel

func OrderExecuteImmediateOrCancel() *Timestamp

When passed to `CreateOrder`, the order will attempt to partially or completely fill and the remaining unfilled quantity will be cancelled. This is also known as Immediate-or-Cancel (IOC).

func OrderGoodTillCanceled

func OrderGoodTillCanceled() *Timestamp

When passed to `CreateOrder`, the order won't expire until explicitly cancelled. This is also known as Good 'Till Cancelled (GTC). This function just returns `nil`.

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

func (Timestamp) Time

func (t Timestamp) Time() time.Time

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(b []byte) error

type Trade

type Trade struct {
	TradeID         string    `json:"trade_id"`
	Ticker          string    `json:"ticker"`
	Price           float64   `json:"price"`
	Count           int       `json:"count"`
	CountFp         string    `json:"count_fp"`
	YesPrice        Cents     `json:"yes_price"`
	NoPrice         Cents     `json:"no_price"`
	YesPriceDollars string    `json:"yes_price_dollars"`
	NoPriceDollars  string    `json:"no_price_dollars"`
	TakerSide       Side      `json:"taker_side"`
	CreatedTime     time.Time `json:"created_time"`
}

Trade is described here: https://trading-api.readme.io/reference/gettrades.

type TradesRequest

type TradesRequest struct {
	CursorRequest
	Ticker string `url:"ticker,omitempty"`
	MinTS  int    `url:"min_ts,omitempty"`
	MaxTS  int    `url:"max_ts,omitempty"`
}

TradesRequest is described here: https://trading-api.readme.io/reference/gettrades.

type TradesResponse

type TradesResponse struct {
	CursorResponse
	Trades []Trade `json:"trades,omitempty"`
}

TradesResponse is described here: https://trading-api.readme.io/reference/gettrades.

Jump to

Keyboard shortcuts

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