publicapi

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package publicapi provides a Go client for the Public.com API.

This package can be imported by external projects to interact with Public.com's trading API programmatically.

Package publicapi provides shared utilities for the Public.com API client.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckResponse added in v0.5.0

func CheckResponse(resp *http.Response) error

CheckResponse checks the API response for errors. If the response status code indicates an error (>= 400), it parses the error body and returns an APIError. Otherwise, returns nil.

func DecodeJSON added in v0.5.0

func DecodeJSON(resp *http.Response, target interface{}) error

DecodeJSON decodes a JSON response body into the given target.

func FormatGainLoss

func FormatGainLoss(value string) string

FormatGainLoss formats a gain/loss value with +/- prefix. Returns "$0.00" for empty, zero, or invalid values.

func FormatVolume

func FormatVolume(vol int64) string

FormatVolume formats a volume number with thousand separators. Returns "-" for zero values.

Types

type APIError added in v0.5.0

type APIError struct {
	StatusCode int
	Code       string
	Message    string
}

APIError represents an error response from the Public.com API.

func (*APIError) Error added in v0.5.0

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) IsForbidden added in v0.5.0

func (e *APIError) IsForbidden() bool

IsForbidden returns true if the error is a 403 Forbidden.

func (*APIError) IsNotFound added in v0.5.0

func (e *APIError) IsNotFound() bool

IsNotFound returns true if the error is a 404 Not Found.

func (*APIError) IsUnauthorized added in v0.5.0

func (e *APIError) IsUnauthorized() bool

IsUnauthorized returns true if the error is a 401 Unauthorized.

type Account added in v0.5.0

type Account struct {
	AccountID            string `json:"accountId"`
	AccountType          string `json:"accountType"`
	OptionsLevel         string `json:"optionsLevel"`
	BrokerageAccountType string `json:"brokerageAccountType"`
	TradePermissions     string `json:"tradePermissions"`
}

Account represents a Public.com account.

type AccountsResponse added in v0.5.0

type AccountsResponse struct {
	Accounts []Account `json:"accounts"`
}

AccountsResponse represents the API response for listing accounts.

type BuyingPower added in v0.5.0

type BuyingPower struct {
	CashOnlyBuyingPower string `json:"cashOnlyBuyingPower"`
	BuyingPower         string `json:"buyingPower"`
	OptionsBuyingPower  string `json:"optionsBuyingPower"`
}

BuyingPower represents buying power information.

type Client added in v0.5.0

type Client struct {
	BaseURL       string
	TokenProvider TokenProvider
	HTTPClient    *http.Client
	// contains filtered or unexported fields
}

Client handles HTTP requests to the Public.com API.

func NewClient added in v0.5.0

func NewClient(baseURL string, tokenProvider TokenProvider) *Client

NewClient creates a new API client with the given base URL and token provider. The token provider will be called to obtain tokens, allowing for automatic token refresh when needed.

func NewClientWithToken added in v0.5.0

func NewClientWithToken(baseURL, token string) *Client

NewClientWithToken creates a new API client with a static token. This is useful for short-lived operations where token refresh is not needed. The client will not attempt to refresh the token on 401 responses.

func (*Client) Delete added in v0.5.0

func (c *Client) Delete(ctx context.Context, path string) (*http.Response, error)

Delete performs a DELETE request to the specified path.

func (*Client) Get added in v0.5.0

func (c *Client) Get(ctx context.Context, path string) (*http.Response, error)

Get performs a GET request to the specified path.

func (*Client) GetAccounts added in v0.5.0

func (c *Client) GetAccounts(ctx context.Context) ([]Account, error)

GetAccounts retrieves all accounts for the authenticated user.

func (*Client) GetPortfolio added in v0.5.0

func (c *Client) GetPortfolio(ctx context.Context, accountID string) (*Portfolio, error)

GetPortfolio retrieves the portfolio for a specific account.

func (*Client) GetWithParams added in v0.5.0

func (c *Client) GetWithParams(ctx context.Context, path string, params map[string]string) (*http.Response, error)

GetWithParams performs a GET request to the specified path with query parameters.

func (*Client) Post added in v0.5.0

func (c *Client) Post(ctx context.Context, path string, body io.Reader) (*http.Response, error)

Post performs a POST request to the specified path with the given body.

type CostBasis added in v0.5.0

type CostBasis struct {
	TotalCost      string `json:"totalCost"`
	UnitCost       string `json:"unitCost"`
	GainValue      string `json:"gainValue"`
	GainPercentage string `json:"gainPercentage"`
	LastUpdate     string `json:"lastUpdate"`
}

CostBasis represents cost basis information.

type Equity added in v0.5.0

type Equity struct {
	Type                  string `json:"type"`
	Value                 string `json:"value"`
	PercentageOfPortfolio string `json:"percentageOfPortfolio"`
}

Equity represents an equity breakdown item.

type Gain added in v0.5.0

type Gain struct {
	GainValue      string `json:"gainValue"`
	GainPercentage string `json:"gainPercentage"`
	Timestamp      string `json:"timestamp"`
}

Gain represents a gain/loss value with percentage.

type GreeksData added in v0.5.0

type GreeksData struct {
	Delta             string `json:"delta"`
	Gamma             string `json:"gamma"`
	Theta             string `json:"theta"`
	Vega              string `json:"vega"`
	Rho               string `json:"rho"`
	ImpliedVolatility string `json:"impliedVolatility"`
}

GreeksData contains the actual greek values.

type GreeksResponse added in v0.5.0

type GreeksResponse struct {
	Greeks []OptionGreeks `json:"greeks"`
}

GreeksResponse represents the API response for option greeks.

type HistoryResponse added in v0.5.0

type HistoryResponse struct {
	Transactions []Transaction `json:"transactions"`
	NextToken    string        `json:"nextToken"`
	Start        string        `json:"start"`
	End          string        `json:"end"`
	PageSize     int           `json:"pageSize"`
}

HistoryResponse represents the API response for account history.

type Instrument added in v0.5.0

type Instrument struct {
	Symbol string `json:"symbol"`
	Name   string `json:"name"`
	Type   string `json:"type"`
}

Instrument represents a trading instrument.

type InstrumentIdentifier added in v0.5.0

type InstrumentIdentifier struct {
	Symbol string `json:"symbol"`
	Type   string `json:"type"`
}

InstrumentIdentifier represents an instrument identifier in API responses.

type InstrumentResponse added in v0.5.0

type InstrumentResponse struct {
	Instrument          InstrumentIdentifier `json:"instrument"`
	Trading             string               `json:"trading"`
	FractionalTrading   string               `json:"fractionalTrading"`
	OptionTrading       string               `json:"optionTrading"`
	OptionSpreadTrading string               `json:"optionSpreadTrading"`
	InstrumentDetails   any                  `json:"instrumentDetails,omitempty"`
}

InstrumentResponse represents the API response for instrument details.

type InstrumentsResponse added in v0.5.0

type InstrumentsResponse struct {
	Instruments []InstrumentResponse `json:"instruments"`
}

InstrumentsResponse represents the API response for listing instruments.

type MultilegExpiration added in v0.5.0

type MultilegExpiration struct {
	TimeInForce string `json:"timeInForce"`
}

MultilegExpiration represents time-in-force for multi-leg orders.

type MultilegInstrument added in v0.5.0

type MultilegInstrument struct {
	Symbol string `json:"symbol"`
	Type   string `json:"type"`
}

MultilegInstrument represents an instrument in a multi-leg order.

type MultilegLeg added in v0.5.0

type MultilegLeg struct {
	Instrument         MultilegInstrument `json:"instrument"`
	Side               string             `json:"side"`
	OpenCloseIndicator string             `json:"openCloseIndicator"`
	RatioQuantity      int                `json:"ratioQuantity"`
}

MultilegLeg represents a single leg in a multi-leg order.

type MultilegOrderRequest added in v0.5.0

type MultilegOrderRequest struct {
	OrderID    string             `json:"orderId"`
	OrderType  string             `json:"orderType"`
	Expiration MultilegExpiration `json:"expiration"`
	Quantity   string             `json:"quantity"`
	LimitPrice string             `json:"limitPrice"`
	Legs       []MultilegLeg      `json:"legs"`
}

MultilegOrderRequest represents a multi-leg order request.

type MultilegOrderResponse added in v0.5.0

type MultilegOrderResponse struct {
	OrderID string `json:"orderId"`
}

MultilegOrderResponse represents the API response for a multi-leg order.

type MultilegPreflightLeg added in v0.5.0

type MultilegPreflightLeg struct {
	Instrument         MultilegInstrument `json:"instrument"`
	Side               string             `json:"side"`
	OpenCloseIndicator string             `json:"openCloseIndicator"`
	RatioQuantity      int                `json:"ratioQuantity"`
}

MultilegPreflightLeg represents a leg in the preflight response.

type MultilegPreflightRequest added in v0.5.0

type MultilegPreflightRequest struct {
	OrderType  string             `json:"orderType"`
	Expiration MultilegExpiration `json:"expiration"`
	Quantity   string             `json:"quantity"`
	LimitPrice string             `json:"limitPrice"`
	Legs       []MultilegLeg      `json:"legs"`
}

MultilegPreflightRequest represents a multi-leg preflight request.

type MultilegPreflightResponse added in v0.5.0

type MultilegPreflightResponse struct {
	BaseSymbol              string                 `json:"baseSymbol"`
	StrategyName            string                 `json:"strategyName"`
	Legs                    []MultilegPreflightLeg `json:"legs"`
	EstimatedCommission     string                 `json:"estimatedCommission"`
	RegulatoryFees          MultilegRegulatoryFees `json:"regulatoryFees"`
	EstimatedIndexOptionFee string                 `json:"estimatedIndexOptionFee"`
	OrderValue              string                 `json:"orderValue"`
	EstimatedQuantity       string                 `json:"estimatedQuantity"`
	EstimatedCost           string                 `json:"estimatedCost"`
	BuyingPowerRequirement  string                 `json:"buyingPowerRequirement"`
	EstimatedProceeds       string                 `json:"estimatedProceeds"`
	PriceIncrement          MultilegPriceIncrement `json:"priceIncrement"`
}

MultilegPreflightResponse represents the API response for multi-leg preflight.

type MultilegPriceIncrement added in v0.5.0

type MultilegPriceIncrement struct {
	IncrementBelow3  string `json:"incrementBelow3"`
	IncrementAbove3  string `json:"incrementAbove3"`
	CurrentIncrement string `json:"currentIncrement"`
}

MultilegPriceIncrement represents price increment information.

type MultilegRegulatoryFees added in v0.5.0

type MultilegRegulatoryFees struct {
	SECFee      string `json:"secFee"`
	TAFFee      string `json:"tafFee"`
	ORFFee      string `json:"orfFee"`
	ExchangeFee string `json:"exchangeFee"`
	OCCFee      string `json:"occFee"`
	CATFee      string `json:"catFee"`
}

MultilegRegulatoryFees represents regulatory fees for multi-leg orders.

type OptionChainRequest added in v0.5.0

type OptionChainRequest struct {
	Instrument     OptionInstrument `json:"instrument"`
	ExpirationDate string           `json:"expirationDate"`
}

OptionChainRequest represents a request for an option chain.

type OptionChainResponse added in v0.5.0

type OptionChainResponse struct {
	BaseSymbol string        `json:"baseSymbol"`
	Calls      []OptionQuote `json:"calls"`
	Puts       []OptionQuote `json:"puts"`
}

OptionChainResponse represents the API response for an option chain.

type OptionExpirationsRequest added in v0.5.0

type OptionExpirationsRequest struct {
	Instrument OptionInstrument `json:"instrument"`
}

OptionExpirationsRequest represents a request for option expirations.

type OptionExpirationsResponse added in v0.5.0

type OptionExpirationsResponse struct {
	BaseSymbol  string   `json:"baseSymbol"`
	Expirations []string `json:"expirations"`
}

OptionExpirationsResponse represents the API response for option expirations.

type OptionGreeks added in v0.5.0

type OptionGreeks struct {
	Symbol string     `json:"symbol"`
	Greeks GreeksData `json:"greeks"`
}

OptionGreeks represents greeks for a single option.

type OptionInstrument added in v0.5.0

type OptionInstrument struct {
	Symbol string `json:"symbol"`
	Type   string `json:"type"`
}

OptionInstrument represents an instrument for options requests.

type OptionQuote added in v0.5.0

type OptionQuote struct {
	Instrument   OptionInstrument `json:"instrument"`
	Outcome      string           `json:"outcome"`
	Last         string           `json:"last"`
	Bid          string           `json:"bid"`
	BidSize      int              `json:"bidSize"`
	Ask          string           `json:"ask"`
	AskSize      int              `json:"askSize"`
	Volume       int              `json:"volume"`
	OpenInterest int              `json:"openInterest"`
}

OptionQuote represents a single option quote in the chain.

type OptionsOrderRequest added in v0.5.0

type OptionsOrderRequest struct {
	OrderID            string          `json:"orderId"`
	Instrument         OrderInstrument `json:"instrument"`
	OrderSide          string          `json:"orderSide"`
	OrderType          string          `json:"orderType"`
	Expiration         OrderExpiration `json:"expiration"`
	Quantity           string          `json:"quantity"`
	LimitPrice         string          `json:"limitPrice,omitempty"`
	OpenCloseIndicator string          `json:"openCloseIndicator"`
}

OptionsOrderRequest represents a single-leg options order request.

type OptionsPreflightRequest added in v0.5.0

type OptionsPreflightRequest struct {
	Instrument         OrderInstrument `json:"instrument"`
	OrderSide          string          `json:"orderSide"`
	OrderType          string          `json:"orderType"`
	Expiration         OrderExpiration `json:"expiration"`
	Quantity           string          `json:"quantity"`
	LimitPrice         string          `json:"limitPrice,omitempty"`
	OpenCloseIndicator string          `json:"openCloseIndicator"`
}

OptionsPreflightRequest represents a single-leg options preflight request.

type OptionsPreflightResponse added in v0.5.0

type OptionsPreflightResponse struct {
	Instrument             OrderInstrument       `json:"instrument"`
	EstimatedCommission    string                `json:"estimatedCommission"`
	RegulatoryFees         OptionsRegulatoryFees `json:"regulatoryFees"`
	EstimatedCost          string                `json:"estimatedCost"`
	BuyingPowerRequirement string                `json:"buyingPowerRequirement"`
	OrderValue             string                `json:"orderValue"`
	EstimatedQuantity      string                `json:"estimatedQuantity"`
	EstimatedProceeds      string                `json:"estimatedProceeds,omitempty"`
}

OptionsPreflightResponse represents the API response for single-leg options preflight.

type OptionsRegulatoryFees added in v0.5.0

type OptionsRegulatoryFees struct {
	SECFee      string `json:"secFee"`
	TAFFee      string `json:"tafFee"`
	ORFFee      string `json:"orfFee"`
	ExchangeFee string `json:"exchangeFee"`
	OCCFee      string `json:"occFee"`
	CATFee      string `json:"catFee"`
}

OptionsRegulatoryFees represents the breakdown of regulatory fees for options.

type Order added in v0.5.0

type Order struct {
	OrderID        string     `json:"orderId"`
	Instrument     Instrument `json:"instrument"`
	Side           string     `json:"side"`
	Type           string     `json:"type"`
	Status         string     `json:"status"`
	Quantity       string     `json:"quantity"`
	FilledQuantity string     `json:"filledQuantity"`
	LimitPrice     string     `json:"limitPrice,omitempty"`
	StopPrice      string     `json:"stopPrice,omitempty"`
	CreatedAt      string     `json:"createdAt"`
}

Order represents an open order from the API.

type OrderExpiration added in v0.5.0

type OrderExpiration struct {
	TimeInForce string `json:"timeInForce"`
}

OrderExpiration represents order time-in-force.

type OrderInstrument added in v0.5.0

type OrderInstrument struct {
	Symbol string `json:"symbol"`
	Type   string `json:"type"`
}

OrderInstrument represents the instrument being traded in an order.

type OrderListResponse added in v0.5.0

type OrderListResponse struct {
	AccountID string  `json:"accountId"`
	Orders    []Order `json:"orders"`
}

OrderListResponse represents the portfolio API response containing orders.

type OrderRequest added in v0.5.0

type OrderRequest struct {
	OrderID    string          `json:"orderId"`
	Instrument OrderInstrument `json:"instrument"`
	OrderSide  string          `json:"orderSide"`
	OrderType  string          `json:"orderType"`
	Expiration OrderExpiration `json:"expiration"`
	Quantity   string          `json:"quantity,omitempty"`
	Amount     string          `json:"amount,omitempty"`
	LimitPrice string          `json:"limitPrice,omitempty"`
	StopPrice  string          `json:"stopPrice,omitempty"`
}

OrderRequest represents an order placement request.

type OrderResponse added in v0.5.0

type OrderResponse struct {
	OrderID string `json:"orderId"`
}

OrderResponse represents the API response for order placement.

type OrderStatusResponse added in v0.5.0

type OrderStatusResponse struct {
	OrderID        string          `json:"orderId"`
	Instrument     OrderInstrument `json:"instrument"`
	CreatedAt      string          `json:"createdAt"`
	Type           string          `json:"type"`
	Side           string          `json:"side"`
	Status         string          `json:"status"`
	Quantity       string          `json:"quantity"`
	LimitPrice     string          `json:"limitPrice,omitempty"`
	StopPrice      string          `json:"stopPrice,omitempty"`
	FilledQuantity string          `json:"filledQuantity"`
	AveragePrice   string          `json:"averagePrice,omitempty"`
	ClosedAt       string          `json:"closedAt,omitempty"`
}

OrderStatusResponse represents the API response for order status.

type OrdersResponse added in v0.5.0

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

OrdersResponse represents the portfolio API response containing orders.

type Portfolio added in v0.5.0

type Portfolio struct {
	AccountID   string      `json:"accountId"`
	AccountType string      `json:"accountType"`
	BuyingPower BuyingPower `json:"buyingPower"`
	Equity      []Equity    `json:"equity"`
	Positions   []Position  `json:"positions"`
}

Portfolio represents a portfolio response from the API.

type Position added in v0.5.0

type Position struct {
	Instrument         Instrument `json:"instrument"`
	Quantity           string     `json:"quantity"`
	CurrentValue       string     `json:"currentValue"`
	PercentOfPortfolio string     `json:"percentOfPortfolio"`
	LastPrice          Price      `json:"lastPrice"`
	InstrumentGain     Gain       `json:"instrumentGain"`
	PositionDailyGain  Gain       `json:"positionDailyGain"`
	CostBasis          CostBasis  `json:"costBasis"`
}

Position represents a portfolio position.

type PreflightRequest added in v0.5.0

type PreflightRequest struct {
	Instrument OrderInstrument `json:"instrument"`
	OrderSide  string          `json:"orderSide"`
	OrderType  string          `json:"orderType"`
	Expiration OrderExpiration `json:"expiration"`
	Quantity   string          `json:"quantity,omitempty"`
	LimitPrice string          `json:"limitPrice,omitempty"`
	StopPrice  string          `json:"stopPrice,omitempty"`
}

PreflightRequest represents a preflight request to estimate order costs.

type PreflightResponse added in v0.5.0

type PreflightResponse struct {
	Instrument             OrderInstrument `json:"instrument"`
	EstimatedCommission    string          `json:"estimatedCommission"`
	RegulatoryFees         RegulatoryFees  `json:"regulatoryFees"`
	EstimatedCost          string          `json:"estimatedCost"`
	BuyingPowerRequirement string          `json:"buyingPowerRequirement"`
	OrderValue             string          `json:"orderValue"`
	EstimatedQuantity      string          `json:"estimatedQuantity"`
}

PreflightResponse represents the API response for preflight estimation.

type Price added in v0.5.0

type Price struct {
	LastPrice string `json:"lastPrice"`
	Timestamp string `json:"timestamp"`
}

Price represents a price with timestamp.

type Quote added in v0.5.0

type Quote struct {
	Instrument    QuoteInstrument `json:"instrument"`
	Outcome       string          `json:"outcome"`
	Last          string          `json:"last"`
	LastTimestamp string          `json:"lastTimestamp"`
	Bid           string          `json:"bid"`
	BidSize       int             `json:"bidSize"`
	BidTimestamp  string          `json:"bidTimestamp"`
	Ask           string          `json:"ask"`
	AskSize       int             `json:"askSize"`
	AskTimestamp  string          `json:"askTimestamp"`
	Volume        int64           `json:"volume"`
	OpenInterest  *int64          `json:"openInterest"`
}

Quote represents a single quote.

type QuoteInstrument added in v0.5.0

type QuoteInstrument struct {
	Symbol string `json:"symbol"`
	Type   string `json:"type"`
}

QuoteInstrument represents an instrument to quote.

type QuoteRequest added in v0.5.0

type QuoteRequest struct {
	Instruments []QuoteInstrument `json:"instruments"`
}

QuoteRequest represents a request for quotes.

type QuotesResponse added in v0.5.0

type QuotesResponse struct {
	Quotes []Quote `json:"quotes"`
}

QuotesResponse represents the API response for quotes.

type RegulatoryFees added in v0.5.0

type RegulatoryFees struct {
	SECFee string `json:"secFee"`
	TAFFee string `json:"tafFee"`
	ORFFee string `json:"orfFee"`
}

RegulatoryFees represents the breakdown of regulatory fees.

type TokenProvider added in v0.5.0

type TokenProvider interface {
	// Token returns a valid authentication token.
	// It may return a cached token or fetch a new one.
	Token() (string, error)
}

TokenProvider is an interface for obtaining authentication tokens. Implementations should handle token caching and refresh logic internally.

type Transaction added in v0.5.0

type Transaction struct {
	ID              string `json:"id"`
	Timestamp       string `json:"timestamp"`
	Type            string `json:"type"`
	SubType         string `json:"subType"`
	AccountNumber   string `json:"accountNumber"`
	Symbol          string `json:"symbol"`
	SecurityType    string `json:"securityType"`
	Side            string `json:"side"`
	Description     string `json:"description"`
	NetAmount       string `json:"netAmount"`
	PrincipalAmount string `json:"principalAmount"`
	Quantity        string `json:"quantity"`
	Direction       string `json:"direction"`
	Fees            string `json:"fees"`
}

Transaction represents a single transaction in account history.

Jump to

Keyboard shortcuts

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