api

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckResponse

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

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

DecodeJSON decodes a JSON response body into the given target.

func GetAuthToken

func GetAuthToken(store keyring.Store, baseURL string, forceRefresh bool) (string, error)

GetAuthToken retrieves a valid auth token using the keyring store. It handles secret retrieval, token exchange, and caching. If forceRefresh is true, it ignores any cached token.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       string
	Message    string
}

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

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) IsForbidden

func (e *APIError) IsForbidden() bool

IsForbidden returns true if the error is a 403 Forbidden.

func (*APIError) IsNotFound

func (e *APIError) IsNotFound() bool

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

func (*APIError) IsUnauthorized

func (e *APIError) IsUnauthorized() bool

IsUnauthorized returns true if the error is a 401 Unauthorized.

type Account

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

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

AccountsResponse represents the API response for listing accounts.

type BuyingPower

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

BuyingPower represents buying power information.

type Client

type Client struct {
	BaseURL        string
	AuthToken      string
	HTTPClient     *http.Client
	TokenRefresher TokenRefresher // Optional: called on 401 to get fresh token
}

Client handles HTTP requests to the Public.com API.

func NewClient

func NewClient(baseURL, authToken string) *Client

NewClient creates a new API client with the given base URL and auth token.

func NewClientWithAuth

func NewClientWithAuth(store keyring.Store, baseURL string) (*Client, error)

NewClientWithAuth creates a new API client with automatic token retrieval. It fetches the auth token using the provided keyring store and base URL.

func (*Client) Delete

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

Delete performs a DELETE request to the specified path.

func (*Client) Get

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

Get performs a GET request to the specified path.

func (*Client) GetInstrument

func (c *Client) GetInstrument(ctx context.Context, symbol, instType string) (*InstrumentResponse, error)

GetInstrument retrieves trading details for a single instrument.

func (*Client) GetOptionChain

func (c *Client) GetOptionChain(ctx context.Context, accountID, symbol, expiration string) (*OptionChainResponse, error)

GetOptionChain retrieves the option chain for a symbol and expiration date.

func (*Client) GetOptionExpirations

func (c *Client) GetOptionExpirations(ctx context.Context, accountID, symbol string) (*OptionExpirationsResponse, error)

GetOptionExpirations retrieves available option expiration dates for a symbol.

func (*Client) GetOptionGreeks

func (c *Client) GetOptionGreeks(ctx context.Context, accountID string, osiSymbols []string) (*GreeksResponse, error)

GetOptionGreeks retrieves greeks for the given OSI option symbols.

func (*Client) GetPortfolio

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

GetPortfolio retrieves the portfolio for the given account ID.

func (*Client) GetQuotes

func (c *Client) GetQuotes(ctx context.Context, accountID string, instruments []QuoteInstrument) ([]Quote, error)

GetQuotes retrieves quotes for the given instruments.

func (*Client) GetWithParams

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

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.

func (*Client) WithTokenRefresher

func (c *Client) WithTokenRefresher(refresher TokenRefresher) *Client

WithTokenRefresher sets a token refresher function that will be called on 401.

type CostBasis

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

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

Equity represents an equity breakdown item.

type Gain

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

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

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

GreeksResponse represents the API response for option greeks.

type HistoryResponse

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

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

Instrument represents a trading instrument.

type InstrumentIdentifier

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

InstrumentIdentifier represents an instrument identifier in API responses.

type InstrumentResponse

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 OptionChainRequest

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

OptionChainRequest represents a request for an option chain.

type OptionChainResponse

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

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

OptionExpirationsRequest represents a request for option expirations.

type OptionExpirationsResponse

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

OptionExpirationsResponse represents the API response for option expirations.

type OptionGreeks

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

OptionGreeks represents greeks for a single option.

type OptionInstrument

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

OptionInstrument represents an instrument for options requests.

type OptionQuote

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 Order

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

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

OrderExpiration represents order time-in-force.

type OrderInstrument

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

OrderInstrument represents the instrument being traded in an order.

type OrderListResponse

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

OrderListResponse represents the portfolio API response containing orders.

type OrderRequest

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

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

OrderResponse represents the API response for order placement.

type OrderStatusResponse

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

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

OrdersResponse represents the portfolio API response containing orders.

type Portfolio

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

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

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

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

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

Price represents a price with timestamp.

type Quote

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

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

QuoteInstrument represents an instrument to quote.

type QuoteRequest

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

QuoteRequest represents a request for quotes.

type QuotesResponse

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

QuotesResponse represents the API response for quotes.

type RegulatoryFees

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

RegulatoryFees represents the breakdown of regulatory fees.

type TokenRefresher

type TokenRefresher func() (string, error)

TokenRefresher is a function that returns a fresh auth token. It's called when the API returns 401 Unauthorized.

type Transaction

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