polygon

package
v1.2.1-alpha Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2022 License: MIT Imports: 7 Imported by: 0

README

docs

Polygon API Wrapper

This package wraps the references defined by the Polygon API, and can be installed using

go get github.com/alpine-hodler/web

Creating a Client

The polygon.Client type is a wrapper for the Go net/http standard library package. An http.RoundTripper is required to authenticate for Polygon requests. Currently the only method supported for Polygon authentication is via OAuth 2.0 bearer token. See documentation examples for more information on best practices.

Rate Limits

Per the Polygon Knowledge Base:

Our free tier subscriptions come with a limit of 5 API requests per minute. Paying customers are allowed unlimited API requests. While we do not have a concrete rate limit, we do monitor usage to ensure that no single user is affecting others’ quality of service. We recommend staying under 100 requests per second to avoid any throttling issues.

The HTTP package uses "golang.org/x/time/rate" to ensure that rate limits are honored. This data is lazy loaded to cut down on memory consumption.

Development

Notes on developing in this package.

Testing

You will need to create an account with Polygon. Then populate the following data in pkg/polygon/.test.env:

POLYGON_API_KEY=

Note that pkg/coinbase/.test.env is an ignored file and should not be commitable to the repository.

Documentation

Index

Examples

Constants

View Source
const (
	AggregateBarPath rawPath
	UpcomingPath
)
View Source
const (
	AggregateBarRatelimiter ratelimiter
	UpcomingRatelimiter
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AssetClass

type AssetClass string

AssetClass is an identifier for a group of similar financial instruments.

const (
	AssetClassStocks  AssetClass = "stocks"
	AssetClassOptions AssetClass = "options"
	AssetClassCrypto  AssetClass = "crypto"
	AssetClassFx      AssetClass = "fx"
)

func (*AssetClass) String

func (AssetClass *AssetClass) String() string

String will convert a AssetClass into a string.

type Bar

type Bar struct {
	// A request id assigned by the server.
	RequestID string `bson:"request_id" json:"request_id" sql:"request_id"`

	// An array of conditions that match your query.
	Results []*BarResult `bson:"results" json:"results" sql:"results"`

	// Status is the status of the market on the holiday.
	Status Status `bson:"status" json:"status" sql:"status"`

	// The exchange symbol that this item is traded under.
	Ticker string `bson:"ticker" json:"ticker" sql:"ticker"`

	// The number of aggregates (minute or day) used to generate the response.
	QueryCount int `bson:"query_count" json:"queryCount" sql:"query_count"`

	// The total number of results for this request.
	ResultsCount int `bson:"results_count" json:"resultsCount" sql:"results_count"`

	// Whether or not this response was adjusted for splits.
	Adjusted bool `bson:"adjusted" json:"adjusted" sql:"adjusted"`
}

Bar represents an aggregate bar for a stock over a given date range in custom time window sizes.

type BarResult

type BarResult struct {
	// C is the close price for the symbol in the given time period.
	C float64 `bson:"c" json:"c" sql:"c"`

	// H is the highest price for the symbol in the given time period.
	H float64 `bson:"h" json:"h" sql:"h"`

	// L is the lowest price for the symbol in the given time period.
	L float64 `bson:"l" json:"l" sql:"l"`

	// N is the number of transactions in the aggregate window.
	N float64 `bson:"n" json:"n" sql:"n"`

	// O is the open price for the symbol in the given time period.
	O float64 `bson:"o" json:"o" sql:"o"`

	// T is the Unix Msec timestamp for the start of the aggregate window.
	T float64 `bson:"t" json:"t" sql:"t"`

	// V is the trading volume of the symbol in the given time period.
	V float64 `bson:"v" json:"v" sql:"v"`

	// VW is the volume weighted average price.
	Vw float64 `bson:"vw" json:"vw" sql:"vw"`
}

BarResult are conditions that match a bar query.

type Client

type Client struct{ http.Client }

Client is a wrapper for http.Client.

func NewClient

func NewClient(_ context.Context, roundtripper transport.T) (*Client, error)

NewClient will return a new HTTP client to interface with the polygon.io web API.

func (*Client) AggregateBar

func (c *Client) AggregateBar(stocksTicker string, multiplier string, timespan Timespan, from string, to string) (m *Bar, _ error)

Get aggregate bars for a stock over a given date range in custom time window sizes.

source: https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksticker__range__multiplier___timespan___from___to

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/alpine-hodler/web/pkg/polygon"
	"github.com/alpine-hodler/web/pkg/transport"
)

func main() {
	url := "https://api.polygon.io"
	apikey := os.Getenv("POLYGON_API_KEY")

	client, err := polygon.NewClient(context.TODO(), transport.NewAuth2().SetBearer(apikey).SetURL(url))
	if err != nil {
		log.Fatalf("error fetching client: %v", err)
	}

	bar, err := client.AggregateBar("AAPL", "1", polygon.TimespanDay, "2021-07-22", "2021-07-22")
	if err != nil {
		log.Fatalf("error fetching aggregate bar: %v", err)
	}

	fmt.Printf("an aggregate bar: %+v\n", bar.Results[0])
}
Output:

func (*Client) Upcoming

func (c *Client) Upcoming() (m []*Upcoming, _ error)

Upcoming gets market holidays and their open/close times.

source: https://polygon.io/docs/crypto/get_v1_marketstatus_upcoming

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/alpine-hodler/web/pkg/polygon"
	"github.com/alpine-hodler/web/pkg/transport"
)

func main() {
	url := "https://api.polygon.io"
	apikey := os.Getenv("POLYGON_API_KEY")

	client, err := polygon.NewClient(context.TODO(), transport.NewAuth2().SetBearer(apikey).SetURL(url))
	if err != nil {
		log.Fatalf("error fetching client: %v", err)
	}

	upcoming, err := client.Upcoming()
	if err != nil {
		log.Fatalf("error fetching upcoming holidays: %v", err)
	}

	fmt.Printf("the next holiday is %q\n", upcoming[0].Name)
}
Output:

type ConditionType

type ConditionType string

ConditionType is an identifier for a collection of related conditions.

const (
	ConditionTypeSaleCondition                 ConditionType = "sale_condition"
	ConditionTypeQuoteCondition                ConditionType = "quote_condition"
	ConditionTypeSipGeneratedFlag              ConditionType = "sip_generated_flag"
	ConditionTypeFinancialStatusIndicator      ConditionType = "financial_status_indicator"
	ConditionTypeShortSaleRestrictionIndicator ConditionType = "short_sale_restriction_indicator"
	ConditionTypeSettlementCondition           ConditionType = "settlement_condition"
	ConditionTypeMarketCondition               ConditionType = "market_condition"
	ConditionTypeTradeThruExempt               ConditionType = "trade_thru_exempt"
)

func (*ConditionType) String

func (ConditionType *ConditionType) String() string

String will convert a ConditionType into a string.

type Consolidated

type Consolidated struct {
	// Whether or not trades with this condition update the high/low.
	UpdatesHighLow bool `bson:"updates_high_low" json:"updates_high_low" sql:"updates_high_low"`

	// Whether or not trades with this condition update the open/close.
	UpdatesOpenClose bool `bson:"updates_open_close" json:"updates_open_close" sql:"updates_open_close"`

	// Whether or not trades with this condition update the volume.
	UpdatesVolume bool `bson:"updates_volume" json:"updates_volume" sql:"updates_volume"`
}

Consolidated describes the aggregation rules on a consolidated (all exchanges) basis.

type MarketCenter

type MarketCenter struct {
	// Whether or not trades with this condition update the high/low.
	UpdatesHighLow bool `bson:"updates_high_low" json:"updates_high_low" sql:"updates_high_low"`

	// Whether or not trades with this condition update the open/close.
	UpdatesOpenClose bool `bson:"updates_open_close" json:"updates_open_close" sql:"updates_open_close"`

	// Whether or not trades with this condition update the volume.
	UpdatesVolume bool `bson:"updates_volume" json:"updates_volume" sql:"updates_volume"`
}

MarketCenter describes aggregation rules on a per-market-center basis.

type SkipMapping

type SkipMapping struct {
	CTA  string `bson:"cta" json:"CTA" sql:"cta"`
	OPRA string `bson:"opra" json:"OPRA" sql:"opra"`
	UTP  string `bson:"utp" json:"UTP" sql:"utp"`
}

SkipMapping is a mapping to a symbol for each SIP that has this condition.

type Status

type Status string
const (
	StatusOk         Status = "ok"
	StatusEarlyClose Status = "early-close"
	StatusClosed     Status = "closed"
)

func (*Status) String

func (Status *Status) String() string

String will convert a Status into a string.

type StockTicker

type StockTicker struct {
	// Abbreviation is a commonly-used abbreviation for this condition.
	Abbreviation string `bson:"abbreviation" json:"abbreviation" sql:"abbreviation"`

	// AssetClass is an identifier for a group of similar financial instruments.
	AssetClass AssetClass `bson:"asset_class" json:"asset_class" sql:"asset_class"`

	// DataTypes are data types that this condition applies to.
	DataTypes []string `bson:"data_types" json:"data_types" sql:"data_types"`

	// Description is a short description of the semantics of this condition.
	Description string `bson:"description" json:"description" sql:"description"`

	// Exchange, if present, is a mapping this condition from a Polygon.io code to a SIP symbol depends on this attribute.
	// In other words, data with this condition attached comes exclusively from the given exchange.
	Exchange int `bson:"exchange" json:"exchange" sql:"exchange"`

	// ID is an identifier used by Polygon.io for this condition. Unique per data type.
	ID int `bson:"id" json:"id" sql:"id"`

	// Legacy, if true, is this condition is from an old version of the SIPs' specs and no longer is used. Other conditions
	// may or may not reuse the same symbol as this one.
	Legacy bool `bson:"legacy" json:"legacy" sql:"legacy"`

	// MarketCenter describes aggregation rules on a per-market-center basis.
	MarketCenter MarketCenter `bson:"market_center" json:"market_center" sql:"market_center"`

	// Name is the name of this condition.
	Name string `bson:"name" json:"name" sql:"name"`

	// SipMapping is a mapping to a symbol for each SIP that has this condition.
	SipMapping SkipMapping `bson:"sip_mapping" json:"sip_mapping" sql:"sip_mapping"`

	// Type is an identifier for a collection of related conditions.
	Type ConditionType `bson:"type" json:"type" sql:"type"`

	// UpdateRules are a list of aggregation rules.
	UpdateRules UpdateRules `bson:"update_rules" json:"update_rules" sql:"update_rules"`
}

StockTicker are conditions that match a stock ticker query.

type Timespan

type Timespan string

Timespan is the size of the time window.

const (
	TimespanMinute  Timespan = "minute"
	TimespanHour    Timespan = "hour"
	TimespanDay     Timespan = "day"
	TimespanWeek    Timespan = "week"
	TimespanMonth   Timespan = "month"
	TimespanQuarter Timespan = "quarter"
	TimespanYear    Timespan = "year"
)

func (*Timespan) String

func (Timespan *Timespan) String() string

String will convert a Timespan into a string.

type Upcoming

type Upcoming struct {
	// Close is the market close time on the holiday (if it's not closed).
	Close string `bson:"close" json:"close" sql:"close"`

	// Date is the date of the holiday.
	Date string `bson:"date" json:"date" sql:"date"`

	// Exchange is market the record is for.
	Exchange string `bson:"exchange" json:"exchange" sql:"exchange"`

	// Name is the name of the holiday.
	Name string `bson:"name" json:"name" sql:"name"`

	// Open is the market open time on the holiday (if it's not closed).
	Open string `bson:"open" json:"open" sql:"open"`

	// Status is the status of the market on the holiday.
	Status string `bson:"status" json:"status" sql:"status"`
}

Upcoming returns information concerning market holidays and their open/close times.

type UpdateRules

type UpdateRules struct {
	// Describes aggregation rules on a consolidated (all exchanges) basis.
	Consolidated Consolidated `bson:"consolidated" json:"consolidated" sql:"consolidated"`
}

UpdateRules are a list of aggregation rules.

Jump to

Keyboard shortcuts

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