polygon

package module
v0.0.0-...-b478a53 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2024 License: MIT Imports: 14 Imported by: 0

README

polygon

Go library for accessing the Polygon.io API

Installation

$ go get github.com/woodstock-tokyo/polygon

Supported APIs

Contact

min@woodstock.club

Documentation

Index

Constants

View Source
const (
	// TextMessage denotes a text data message. The text message payload is
	// interpreted as UTF-8 encoded text data.
	TextMessage = 1

	// BinaryMessage denotes a binary data message.
	BinaryMessage = 2

	// CloseMessage denotes a close control message. The optional message
	// payload contains a numeric code and text. Use the FormatCloseMessage
	// function to format a close message payload.
	CloseMessage = 8

	// PingMessage denotes a ping control message. The optional message payload
	// is UTF-8 encoded text.
	PingMessage = 9

	// PongMessage denotes a pong control message. The optional message payload
	// is UTF-8 encoded text.
	PongMessage = 10
)

The message types are defined in RFC 6455, section 11.8.

Variables

View Source
var (
	ErrRSIStatus    = errors.New("rsi: unexpected status")
	ErrRSINoResults = errors.New("rsi: no results")
)

Functions

func AggregationResultSortFunc

func AggregationResultSortFunc() func(AggregationResult, AggregationResult) int

AggregationResultSortFunc default sort function

Types

type Aggregate

type Aggregate struct {
	Event             EventTypeEnum `json:"ev"`
	Symbol            string        `json:"sym"`
	TickVolume        int64         `json:"v"`
	AccumulatedVolume int64         `json:"av"`
	Open              float64       `json:"op"`
	TickVWAP          float64       `json:"vw"`
	TickOpen          float64       `json:"o"`
	TickClose         float64       `json:"c"`
	TickHigh          float64       `json:"h"`
	TickLow           float64       `json:"l"`
	VWAP              float64       `json:"a"`
	AverageTradeSize  float64       `json:"z"`
	StartTimestamp    int64         `json:"s"`
	EndTimestamp      int64         `json:"e"`
	OTC               *bool         `json:"otc"`
}

type Aggregation

type Aggregation struct {
	Ticker       string              `json:"ticker"`
	QueryCount   int                 `json:"queryCount"`
	ResultsCount int                 `json:"resultsCount"`
	Adjusted     bool                `json:"adjusted"`
	Results      []AggregationResult `json:"results"`
	Status       string              `json:"status"`
	RequestID    string              `json:"request_id"`
	Count        int                 `json:"count"`
}

Aggregation Get aggregate bars for a ticker over a given date range in custom time window sizes

func (Aggregation) Valid

func (a Aggregation) Valid() bool

Valid check whether aggregation is valid or not

type AggregationOption

type AggregationOption struct {
	Adjusted bool  `url:"adjusted,omitempty"`
	Sort     Order `url:"sort,omitempty"`
	Limit    int   `url:"limit,omitempty"`
}

AggregationOption aggregation option

type AggregationResult

type AggregationResult struct {
	Open                   float64 `json:"o"`
	Close                  float64 `json:"c"`
	High                   float64 `json:"h"`
	Low                    float64 `json:"l"`
	TransactionNumber      int     `json:"n"`
	Volume                 float64 `json:"v"`
	VolumeWeightedAvgPrice float64 `json:"vw"`
	Timestamp              int64   `json:"t"`
}

AggregationResult aggregation result item

func (AggregationResult) Time

func (ar AggregationResult) Time() time.Time

Valid check whether aggregation is valid or not

type Client

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

Client models a client to consume the Polygon Cloud API.

func NewClient

func NewClient(token string, options ...ClientOption) *Client

NewClient creates a client with the given authorization token.

func (Client) Aggregation

func (c Client) Aggregation(ctx context.Context, ticker string, multiplier int, timespan Timespan, from, to time.Time, opt *AggregationOption) (Aggregation, error)

Aggregation Get aggregate bars for a ticker over a given date range in custom time window sizes

func (Client) CryptoOpenClose

func (c Client) CryptoOpenClose(ctx context.Context, from, to string, date string, opt *OpenCloseOption) (OpenClose, error)

CryptoOpenClose Get the open, close prices of a crypto pair on a certain date.

func (Client) Dividend

func (c Client) Dividend(ctx context.Context, ticker string, opt *DividendOption) (Dividend, error)

Dividend Get a list of historical cash dividends, including the ticker symbol, declaration date, ex-dividend date, record date, pay date, frequency, and amount.

func (*Client) FetchURLToJSON

func (c *Client) FetchURLToJSON(ctx context.Context, u *url.URL, v any) error

Fetches JSON content from the given URL and unmarshals it into `v`.

func (*Client) GetBytes

func (c *Client) GetBytes(ctx context.Context, endpoint string) ([]byte, error)

GetBytes gets the data from the given endpoint.

func (*Client) GetFloat64

func (c *Client) GetFloat64(ctx context.Context, endpoint string) (float64, error)

GetFloat64 gets the number from the given endpoint.

func (*Client) GetJSON

func (c *Client) GetJSON(ctx context.Context, endpoint string, v any) error

GetJSON gets the JSON data from the given endpoint.

func (*Client) GetJSONWithQueryParams

func (c *Client) GetJSONWithQueryParams(ctx context.Context, endpoint string, queryParams map[string]string, v any) error

GetJSONWithQueryParams gets the JSON data from the given endpoint with the query parameters attached.

func (*Client) GetJSONWithoutToken

func (c *Client) GetJSONWithoutToken(ctx context.Context, endpoint string, v any) error

GetJSONWithoutToken gets the JSON data from the given endpoint without adding a token to the URL.

func (Client) LastestDiviend

func (c Client) LastestDiviend(ctx context.Context, ticker string, opt *DividendOption) (DividendResult, error)

LastestDiviend retrieves the latest dividend for a given ticker

func (Client) LatestRelativeStrengthIndex

func (c Client) LatestRelativeStrengthIndex(ctx context.Context, ticker string) (float64, error)

LatestRelativeStrengthIndex get latest stock RSI by day for a given ticker

func (Client) MarketStatus

func (c Client) MarketStatus(ctx context.Context) (Market, error)

MarketStatus Get the current trading status of the exchanges and overall financial markets.

func (Client) News

func (c Client) News(ctx context.Context, ticker string, opt *NewsOption) (News, error)

News retrieves the given number of news articles for the given stock symbol.

func (Client) PrevClose

func (c Client) PrevClose(ctx context.Context, ticker string, opt *PrevCloseOption) (PrevClose, error)

PrevClose Get the previous day's open, high, low, and close (OHLC) for the specified stock ticker.

func (Client) RelativeStrengthIndex

func (c Client) RelativeStrengthIndex(ctx context.Context, ticker string, opt *RSIOption) (resp RSIResponse, err error)

RelativeStrengthIndex get stock RSI for a given ticker

func (Client) StockOpenClose

func (c Client) StockOpenClose(ctx context.Context, ticker string, date string, opt *OpenCloseOption) (OpenClose, error)

StockOpenClose Get the open, close and afterhours prices of a stock symbol on a certain date.

func (Client) StockSplits

func (c Client) StockSplits(ctx context.Context, opt *StockSplitsOption) (StockSplits, error)

StockSplits Get a list of historical stock splits

func (Client) SubscribeAggregates

func (c Client) SubscribeAggregates(client WebSocketClient, symbols []string, eventType EventTypeEnum) (err error)

func (Client) Summary

func (c Client) Summary(ctx context.Context, assets []SummaryAsset) (Summary, error)

Summary Get everything needed to visualize the tick-by-tick movement of a list of tickers.

func (Client) TickerDetail

func (c Client) TickerDetail(ctx context.Context, ticker string, opt *TickerDetailOption) (TickerDetail, error)

func (Client) TickerEvent

func (c Client) TickerEvent(ctx context.Context, ticker string, opt *TickerEventOption) (TickerEvent, error)

TickerEvent Get a timeline of events for the entity associated with the given ticker, CUSIP, or Composite FIGI.

func (Client) UseV1Endpoints

func (c Client) UseV1Endpoints() Client

polygon api versions are not unified, sometimes we have to switch to v1

func (Client) UseV3Endpoints

func (c Client) UseV3Endpoints() Client

polygon api versions are not unified, sometimes we have to switch to v3

func (Client) UseVXEndpoints

func (c Client) UseVXEndpoints() Client

polygon api versions are not unified, sometimes we have to switch to vX

type ClientOption

type ClientOption func(*Client)

ClientOption applies an option to the client.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets the baseURL for a new Polygon Client

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets the http.Client for a new Polygon Client

func WithSecureHTTPClient

func WithSecureHTTPClient() ClientOption

WithSecureHTTPClient sets a secure http.Client for a new Polygon Client

func WithWebsocketBaseURL

func WithWebsocketBaseURL(baseURL string) ClientOption

WithBaseURL sets the baseURL for a new Polygon Client

type Dividend

type Dividend struct {
	Results   []DividendResult `json:"results"`
	Status    string           `json:"status"`
	RequestID string           `json:"request_id"`
	NextURL   string           `json:"next_url"`
}

Dividend Get a list of historical cash dividends, including the ticker symbol, declaration date, ex-dividend date, record date, pay date, frequency, and amount.

type DividendOption

type DividendOption struct {
	Ticker string `url:"ticker"`
	// Query by the number of times per year the dividend is paid out. Possible values are 0 (one-time), 1 (annually), 2 (bi-annually), 4 (quarterly), and 12 (monthly).
	Frequency int `url:"frequency,omitempty"`
	// Query by the type of dividend. Dividends that have been paid and/or are expected to be paid on consistent schedules are denoted as CD.
	// Special Cash dividends that have been paid that are infrequent or unusual, and/or can not be expected to occur in the future are denoted as SC.
	DividendType      DividendType `url:"dividend_type,omitempty"`
	Order             Order        `url:"order,omitempty"`
	Limit             uint         `url:"limit,omitempty"`
	Sort              string       `url:"sort,omitempty"`
	ExDividendDateGTE string       `url:"ex_dividend_date.gte,omitempty"`
}

type DividendResult

type DividendResult struct {
	CashAmount      float64 `json:"cash_amount"`
	Currency        string  `json:"currency"`
	DeclarationDate string  `json:"declaration_date"`
	DividendType    string  `json:"dividend_type"`
	ExDividendDate  string  `json:"ex_dividend_date"`
	Frequency       int     `json:"frequency"`
	PayDate         string  `json:"pay_date"`
	RecordDate      string  `json:"record_date"`
	Ticker          string  `json:"ticker"`
}

DividendResult dividend result item

type DividendType

type DividendType string
const (
	CD DividendType = "CD"
	SC DividendType = "SC"
	LT DividendType = "LT"
	ST DividendType = "ST"
)

type Error

type Error struct {
	Status       string `json:"status"`
	ErrorMessage string `json:"error"`
	RequestID    string `json:"request_id"`
}

Error represents an Polygon API error

func (Error) Error

func (e Error) Error() string

Error implements the error interface

type EventTypeEnum

type EventTypeEnum string

EventTypeEnum event type enum

const (
	// EventTypeOther others
	EventTypeOther EventTypeEnum = ""
	// EventTypeAM minute aggregates
	EventTypeAM EventTypeEnum = "AM"
	// EventTypeA second aggregates
	EventTypeA EventTypeEnum = "A"
)

type Market

type Market struct {
	Status     MarketStatus `json:"market"`
	EarlyHours bool         `json:"earlyHours"`
	AfterHours bool         `json:"afterHours"`
	ServerTime string       `json:"serverTime"`
	Exchanges  struct {
		NYSE   MarketStatus `json:"nyse"`
		Nasdaq MarketStatus `json:"nasdaq"`
		OTC    MarketStatus `json:"otc"`
	} `json:"exchanges"`
	Currencies struct {
		FX     MarketStatus `json:"fx"`
		Crypto MarketStatus `json:"crypto"`
	} `json:"currencies"`
}

func (Market) String

func (m Market) String(market ...string) string

type MarketOption

type MarketOption struct{}

type MarketStatus

type MarketStatus string
const AfterHours MarketStatus = "after_hours"
const Closed MarketStatus = "closed"
const EarlyHours MarketStatus = "early_hours"
const ExtendedHours MarketStatus = "extended-hours"
const Open MarketStatus = "open"

type MessageType

type MessageType uint

type News

type News struct {
	Results []struct {
		ID        string `json:"id"`
		Publisher struct {
			Name     string `json:"name"`
			Homepage string `json:"homepage_url"`
			Logo     string `json:"logo_url"`
			Favicon  string `json:"favicon_url"`
		} `json:"publisher"`
		Title        string   `json:"title"`
		Author       string   `json:"author"`
		PublishedUTC string   `json:"published_utc"`
		ArticleURL   string   `json:"article_url"`
		AmpURL       string   `json:"amp_url"`
		Tickers      []string `json:"tickers"`
		ImageURL     string   `json:"image_url"`
		Description  string   `json:"description"`
		Keywords     []string `json:"keywords"`
	} `json:"results"`
	Status  string `json:"status"`
	Count   int    `json:"count"`
	NextURL string `json:"next_url"`
}

News models a news item either for the market or for an individual stock.

type NewsOption

type NewsOption struct {
	Ticker                     string `url:"ticker"`
	Published_LessThan         string `url:"published_utc.lt,omitempty"`
	Published_LessThanEqual    string `url:"published_utc.lte,omitempty"`
	Published_GreaterThan      string `url:"published_utc.gt,omitempty"`
	Published_GreaterThanEqual string `url:"published_utc.gte,omitempty"`
	Limit                      uint   `url:"limit,omitempty"`
	Order                      Order  `url:"order,omitempty"`
	Sort                       string `url:"sort,omitempty"`
}

NewsOption option for fetching news

type OpenClose

type OpenClose struct {
	Status     string  `json:"status,omitempty"`
	From       string  `json:"from,omitempty"`
	Symbol     string  `json:"symbol"`
	Open       float64 `json:"open"`
	Close      float64 `json:"close"`
	High       float64 `json:"high,omitempty"`
	Low        float64 `json:"low,omitempty"`
	Volume     float64 `json:"volume,omitempty"`
	AfterHours float64 `json:"afterHours,omitempty"`
	PreMarket  float64 `json:"preMarket,omitempty"`
}

OpenClose Get the open, close and afterhours prices of a stock symbol on a certain date.

type OpenCloseOption

type OpenCloseOption struct {
	Adjusted bool `url:"adjusted,omitempty"`
}

OpenCloseOption prev close option

type Order

type Order string

Order used for sort

const Ascend Order = "asc"
const Descend Order = "desc"

type PrevClose

type PrevClose struct {
	Ticker       string            `json:"ticker"`
	QueryCount   int               `json:"queryCount"`
	ResultsCount int               `json:"resultsCount"`
	Adjusted     bool              `json:"adjusted"`
	Results      []PrevCloseResult `json:"results"`
	Status       string            `json:"status"`
	RequestID    string            `json:"request_id"`
	Count        int               `json:"count"`
}

PrevClose Get the previous day's open, high, low, and close (OHLC) for the specified stock ticker.

func (PrevClose) Valid

func (p PrevClose) Valid() bool

Valid check whether prev close is valid or not

type PrevCloseOption

type PrevCloseOption struct {
	Adjusted bool `url:"adjusted,omitempty"`
}

PrevCloseOption prev close option

type PrevCloseResult

type PrevCloseResult struct {
	Ticker                 string  `json:"T"`
	Open                   float64 `json:"o"`
	Close                  float64 `json:"c"`
	High                   float64 `json:"h"`
	Low                    float64 `json:"l"`
	TransactionNumber      int     `json:"n"`
	Volume                 float64 `json:"v"`
	VolumeWeightedAvgPrice float64 `json:"vw"`
	Timestamp              int64   `json:"t"`
}

PrevCloseResult prev close result item

func (PrevCloseResult) Time

func (pr PrevCloseResult) Time() time.Time

Time check whether prev close is valid or not

type RSIOption

type RSIOption struct {
	Timespan string `url:"timespan"`
	Adjusted bool   `json:"adjusted"`
	Window   uint   `json:"window"`
	Limit    uint   `url:"limit,omitempty"`
	Order    Order  `url:"order,omitempty"`
	Sort     string `url:"sort,omitempty"`
}

RSIOption options for fetching RSI

type RSIResponse

type RSIResponse struct {
	Results struct {
		Underlying struct {
			URL string `json:"url"`
		} `json:"underlying"`
		Values []struct {
			Timestamp int64   `json:"timestamp"`
			Value     float64 `json:"value"`
		} `json:"values"`
	} `json:"results"`
	Status    string `json:"status"`
	RequestID string `json:"request_id"`
	NextURL   string `json:"next_url"`
}

type StockSplits

type StockSplits struct {
	Results []StockSplitsResult `json:"results"`
	Status  string              `json:"status"`
	NextURL string              `json:"next_url"`
}

StockSplits Get a list of historical stock splits

type StockSplitsOption

type StockSplitsOption struct {
	Ticker           string `url:"ticker,omitempty"`
	ExecutionDate    string `url:"execution_date,omitempty"`
	ExecutionDateGTE string `url:"execution_date.gte,omitempty"`
	Order            Order  `url:"order,omitempty"`
	Limit            uint   `url:"limit,omitempty"`
	Sort             string `url:"sort,omitempty"`
}

type StockSplitsResult

type StockSplitsResult struct {
	ExecutionDate string  `json:"execution_date"`
	SplitFrom     float64 `json:"split_from"`
	SplitTo       float64 `json:"split_to"`
	Ticker        string  `json:"ticker"`
}

StockSplitsResult stock splits result item

type Summary

type Summary struct {
	RequestID string          `json:"request_id"`
	Results   []SummaryResult `json:"results"`
	Status    string          `json:"status"`
}

Summary Get everything needed to visualize the tick-by-tick movement of a list of tickers.

type SummaryAsset

type SummaryAsset struct {
	Ticker    string
	AssetType string
}

Asset

type SummaryOption

type SummaryOption struct {
	TickerAnyOf string `url:"ticker.any_of,omitempty"`
}

SummaryOption summary option

type SummaryOptions

type SummaryOptions struct {
	ContractType      string `json:"contract_type"`
	ExerciseStyle     string `json:"exercise_style"`
	ExpirationDate    string `json:"expiration_date"`
	SharesPerContract uint   `json:"shares_per_contract"`
	StrikePrice       uint   `json:"strike_price"`
	UnderlyingTicker  string `json:"underlying_ticker"`
}

SummaryOptions summary options item

type SummaryResult

type SummaryResult struct {
	Branding struct {
		IconURL string `json:"icon_url"`
		LogoURL string `json:"logo_url"`
	} `json:"branding"`
	MarketStatus MarketStatus   `json:"market_status"`
	Name         string         `json:"name"`
	Price        float64        `json:"price"`
	Session      SummarySession `json:"session"`
	Options      SummaryOptions `json:"options"`
	Ticker       string         `json:"ticker"`
	Type         string         `json:"type"`
}

SummaryResult summary result item

type SummarySession

type SummarySession struct {
	Change                    float64 `json:"change"`
	ChangePercent             float64 `json:"change_percent"`
	Close                     float64 `json:"close"`
	EarlyTradingChange        float64 `json:"early_trading_change"`
	EarlyTradingChangePercent float64 `json:"early_trading_change_percent"`
	High                      float64 `json:"high"`
	LateTradingChange         float64 `json:"late_trading_change"`
	LateTradingChangePercent  float64 `json:"late_trading_change_percent"`
	Low                       float64 `json:"low"`
	Open                      float64 `json:"open"`
	PreviousClose             float64 `json:"previous_close"`
	Volume                    float64 `json:"volume"`
}

SummarySession summary session item

type TickerChangeEventItem

type TickerChangeEventItem struct {
	Ticker string `json:"ticker"`
}

type TickerDetail

type TickerDetail struct {
	Results   TickerDetailResult `json:"results"`
	Status    string             `json:"status"`
	RequestID string             `json:"request_id"`
}

TickerDetail Get a single ticker supported by Polygon.io. This response will have detailed information about the ticker and the company behind it

type TickerDetailOption

type TickerDetailOption struct {
	Date string `url:"date,omitempty"`
}

type TickerDetailResult

type TickerDetailResult struct {
	Ticker          string  `json:"ticker"`
	Name            string  `json:"name"`
	Market          string  `json:"market"`
	Locale          string  `json:"locale"`
	PrimaryExchange string  `json:"primary_exchange"`
	Type            string  `json:"type"`
	Active          bool    `json:"active"`
	CurrencyName    string  `json:"currency_name"`
	MarketCap       float64 `json:"market_cap"`
	PhoneNumber     string  `json:"phone_number"`
	Address         struct {
		Address1   string `json:"address1"`
		City       string `json:"city"`
		State      string `json:"state"`
		PostalCode string `json:"postal_code"`
	} `json:"address"`
	Description    string `json:"description"`
	Sector         string `json:"sic_description"`
	HomePageURL    string `json:"homepage_url"`
	TotalEmployees int    `json:"total_employees"`
	ListDate       string `json:"list_date"`
	Branding       struct {
		LogoURL string `json:"logo_url"`
		IconURL string `json:"icon_url"`
	} `json:"branding"`
	SIC string `json:"sic_code"`
}

TickerDetailResult ticker detail result item

type TickerEvent

type TickerEvent struct {
	Results   TickerEventResult `json:"results"`
	Status    string            `json:"status"`
	RequestID string            `json:"request_id"`
}

TickerEvent Get a timeline of events for the entity associated with the given ticker, CUSIP, or Composite FIGI.

type TickerEventItem

type TickerEventItem struct {
	Type         string                `json:"type"`
	Date         string                `json:"date"`
	TickerChange TickerChangeEventItem `json:"ticker_change"`
}

type TickerEventOption

type TickerEventOption struct {
	// A comma-separated list of the types of event to include. Currently ticker_change is the only supported event_type. Leave blank to return all supported event_types.
	Types string `url:"types,omitempty"`
}

type TickerEventResult

type TickerEventResult struct {
	Name   string            `json:"name"`
	FIGI   string            `json:"figi"`
	CIK    string            `json:"cik"`
	Events []TickerEventItem `json:"events"`
}

TickerEventResult ticker event result item

type Timespan

type Timespan string

Timespan used for aggregation

const Day Timespan = "day"
const Hour Timespan = "hour"
const Minute Timespan = "minute"
const Month Timespan = "month"
const Quarter Timespan = "quarter"
const Week Timespan = "week"
const Year Timespan = "year"

type WebSocketClient

type WebSocketClient interface {
	Dial(urlStr string, reqHeader http.Header)
	WriteMessage(messageType int, data []byte) error
}

Jump to

Keyboard shortcuts

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