flux

package module
v0.0.0-...-319c6cf Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2022 License: MIT Imports: 15 Imported by: 0

README

flux

Flux Logo

Flux is a highly performant wrapper for the TDAmeritrade Provisioner

go.dev reference Go Version Code Size Go Report Card FOSSA Status Build Status

Usage

Flux works in unison with my TDAmeritrade API Wrapper tda-go for the authentication and access token functions. This is why this is also required to be imported (and potentially added to your go.mod file).

import "github.com/adityaxdiwakar/flux"

This program is intended to act as a non-blocking interface to TDAmeritrade data provisioner, it is required to be instantiated and opened, but operaes within a goroutine to prevent blocking the main process.

A simple example:

package main

import (
  "fmt"
  "os"
  "syscall"
   
  "github.com/adityaxdiwakar/flux"
  "github.com/adityaxdiwakar/tda-go"
)

func main() {
  tdaSession := tda.Session{
     Refresh: "<YOUR_REFRESH_TOKEN>,
     ConsumerKey: "<YOUR_CONSUMER_KEY>",
     RootUrl: "https://api.tdameritrade.com/v1",
     
  }
  
  s, err := flux.New(tdaSession)
  if err != nil {
     panic(err) // panic if an error is present
  }
  s.Open()
  
  payload, err := s.RequestChart(flux.ChartRequestSignature{
    Ticker: "AAPL", Width: "HOUR1", Range: "DAY1",
  })
  fmt.Println(payload.Instrument.Description) // prints `APPLE INC COM`
  
  // make a channel that is notified of any system interrupts 
  // this is a blocking set of lines, if the `sc` channel is notified
  // the function will continue and move to s.Close()
  sc := make(chan os.signal, 1)
  signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
  <-sc
  
  s.Close()
}




There are more examples in the examples folder.

License

FOSSA Status

Documentation

Index

Constants

View Source
const (
	// ProbabilityITM field
	ProbabilityITM = QuoteField("PROBABILITY_ITM")
	// OpenInterest field
	OpenInterest = QuoteField("OPEN_INT")
)
View Source
const (
	// Mark field
	Mark = QuoteField("MARK")
	// MarkChange field
	MarkChange = QuoteField("MARK_CHANGE")
	// MarkPercentChange field
	MarkPercentChange = QuoteField("MARK_PERCENT_CHANGE")
	// NetChange field
	NetChange = QuoteField("NET_CHANGE")
	// NetPercentChange field
	NetPercentChange = QuoteField("NET_CHANGE_PERCENT")
	// Bid field
	Bid = QuoteField("BID")
	// BidExchange field
	BidExchange = QuoteField("BID_EXCHANGE")
	// Ask field
	Ask = QuoteField("ASK")
	// AskExchange field
	AskExchange = QuoteField("ASK_EXCHANGE")
	// BidSize field
	BidSize = QuoteField("BID_SIZE")
	// AskSize field
	AskSize = QuoteField("ASK_SIZE")
	// Volume field
	Volume = QuoteField("VOLUME")
	// Open field
	Open = QuoteField("OPEN")
	// High52 field
	High52 = QuoteField("HIGH52")
	// Low52 field
	Low52 = QuoteField("LOW52")
	// High field
	High = QuoteField("HIGH")
	// Low field
	Low = QuoteField("LOW")
	// VWAP field
	VWAP = QuoteField("VWAP")
	// VolIdx field
	VolIdx = QuoteField("VOLATILITY_INDEX")
	// ImplVol field
	ImplVol = QuoteField("IMPLIED_VOLATILITY")
	// MMMove field
	MMMove = QuoteField("MARKET_MAKER_MOVE")
	// PercentIV field
	PercentIV = QuoteField("PERCENT_IV")
	// HistoricalVol30 field
	HistoricalVol30 = QuoteField("HISTORICAL_VOLATILITY_30_DAYS")
	// MktCap field
	MktCap = QuoteField("MARKET_CAP")
	// Beta field
	Beta = QuoteField("BETA")
	// PE field
	PE = QuoteField("PE")
	// InitMargin field
	InitMargin = QuoteField("INITIAL_MARGIN")
	// Last field
	Last = QuoteField("LAST")
	// LastSize field
	LastSize = QuoteField("LAST_SIZE")
	// LastExchange field
	LastExchange = QuoteField("LAST_EXCHANGE")
	// Rho field
	Rho = QuoteField("RHO")
	// BorrowStatus field
	BorrowStatus = QuoteField("BORROW_STATUS")
	// Delta field
	Delta = QuoteField("DELTA")
	// Gamma field
	Gamma = QuoteField("GAMMA")
	// Theta field
	Theta = QuoteField("THETA")
	// Vega field
	Vega = QuoteField("VEGA")
	// DivAmount field
	DivAmount = QuoteField("DIV_AMOUNT")
	// EPS field
	EPS = QuoteField("EPS")
	// ExdDivDate field
	ExdDivDate = QuoteField("EXD_DIV_DATE")
	// Yield field
	Yield = QuoteField("YIELD")
	// FrontVol field
	FrontVol = QuoteField("FRONT_VOLATILITY")
	// BackVol field
	BackVol = QuoteField("BACK_VOLATILITY")
	// VolDiff field
	VolDiff = QuoteField("VOLATILITY_DIFFERENCE")
	// Close field
	Close = QuoteField("CLOSE")
)

Variables

View Source
var (
	// ErrWsAlreadyOpen is returned if the connection being opened is already opened
	ErrWsAlreadyOpen = errors.New("error: connection already open")

	// ErrGatewayUnsuccessful is returned if the gateway helper could not retrieve the gateway URL
	ErrGatewayUnsuccessful = errors.New("error: gateway could not be requested")

	// ErrProtocolUnestablished is an error for the initial socket handshake
	// based on whether or not the proper session is returned
	ErrProtocolUnestablished = errors.New("error: could not establish protocol")

	// ErrAuthenticationUnsuccessful is returned if there is an authentication
	// error in the socket handshake and login command
	ErrAuthenticationUnsuccessful = errors.New("error: authentication unsuccessful")

	// ErrNotReceivedInTime is returned if the data being loaded could not be
	// found in the time enforcement
	ErrNotReceivedInTime = errors.New("error: took too long to respond, try again")
)

Functions

This section is empty.

Types

type ChartRequestSignature

type ChartRequestSignature struct {
	// ticker for the content of a chart request
	Ticker string

	// range is the timeframe for chart data to be received, see specs.txt
	Range string

	// width is the width of the candles to be received, see specs.txt
	Width string

	// internal use only
	UniqueID string
}

ChartRequestSignature is the parameter for a chart request

type ChartStoredCache

type ChartStoredCache struct {
	Symbol  string `json:"symbol"`
	Candles struct {
		Timestamps []int64   `json:"timestamps"`
		Opens      []float64 `json:"opens"`
		Highs      []float64 `json:"highs"`
		Lows       []float64 `json:"lows"`
		Closes     []float64 `json:"closes"`
		Volumes    []float64 `json:"volumes"`
	} `json:"candles"`
	RequestID  string `json:"requestId"`
	RequestVer int    `json:"requestVer"`
}

ChartStoredCache is an object containing what is returned from a chart request

type OptionChainGetFilter

type OptionChainGetFilter struct {
	StrikeQuantity int64    `json:"strikeQuantity,omitempty"`
	SeriesNames    []string `json:"seriesNames,omitempty"`
}

OptionChainGetFilter is the sub-parameter for filtering an option chain

type OptionChainGetRequestSignature

type OptionChainGetRequestSignature struct {
	// ticker for option chain get request
	Underlying string

	// filter for specific option chain to get
	Filter OptionChainGetFilter

	// internal use only
	UniqueID string
}

OptionChainGetRequestSignature is the parameter for an option chain request

type OptionChainGetStoredCache

type OptionChainGetStoredCache struct {
	OptionSeries []OptionChainSeries `json:"optionSeries"`
	Service      string              `json:"service"`
	RequestID    string              `json:"requestId"`
	RequestVer   int                 `json:"requestVer"`
}

OptionChainGetStoredCache is an object containing what is returned from an option chain request

type OptionChainSeries

type OptionChainSeries struct {
	Expiration       string             `json:"expiration"`
	ExpirationString string             `json:"expirationString"`
	FractionalType   string             `json:"fractionalType"`
	OptionPairs      []optionChainPairs `json:"optionPairs"`
	Spc              float64            `json:"spc"`
	Name             string             `json:"name"`
	Contract         string             `json:"contract"`
	ContractDisplay  string             `json:"contractDisplay"`
	DaysToExpiration int                `json:"daysToExpiration"`
	SettlementType   string             `json:"settlementType"`
}

OptionChainSeries are individual series from the option chain get response

type OptionQuoteCache

type OptionQuoteCache struct {
	Items      []OptionQuoteItem `json:"items"`
	Exchanges  []string          `json:"exchanges"`
	Service    string            `json:"service"`
	RequestID  string            `json:"requestId"`
	RequestVer int               `json:"requestVer"`
}

OptionQuoteCache is an object containing what is returned from an option quote request

type OptionQuoteFilter

type OptionQuoteFilter struct {
	SeriesNames []string `json:"seriesNames"`
	MaxStrike   float64  `json:"maxStrike"`
	MinStrike   float64  `json:"minStrike"`
}

OptionQuoteFilter is the sub-parameter for filtering an option quote

type OptionQuoteItem

type OptionQuoteItem struct {
	Symbol string `json:"symbol"`
	Values struct {
		ASK            float64 `json:"ASK"`
		BID            float64 `json:"BID"`
		DELTA          float64 `json:"DELTA"`
		OPENINT        float64 `json:"OPEN_INT"`
		PROBABILITYITM float64 `json:"PROBABILITY_ITM"`
		VOLUME         int     `json:"VOLUME"`
	} `json:"values"`
}

OptionQuoteItem is a single option quote

type OptionQuoteRequestSignature

type OptionQuoteRequestSignature struct {
	// ticker for option chain get request
	Underlying string

	Exchange string

	Fields []QuoteField

	// filter for specific option chain to get
	Filter OptionQuoteFilter

	// internal use only
	UniqueID string
}

OptionQuoteRequestSignature is the parameter for an option quote request

type OptionSeries

type OptionSeries struct {
	Underlying      string    `json:"underlying"`
	Name            string    `json:"name"`
	Spc             float64   `json:"spc"`
	Multiplier      float64   `json:"multiplier"`
	ExpirationStyle string    `json:"expirationStyle"`
	IsEuropean      bool      `json:"isEuropean"`
	Expiration      time.Time `json:"expiration"`
	LastTradeDate   time.Time `json:"lastTradeDate"`
	SettlementType  string    `json:"settlementType"`
}

OptionSeries is an object containing the data for an option series

type OptionSeriesCache

type OptionSeriesCache struct {
	Series     []OptionSeries `json:"series"`
	Service    string         `json:"service"`
	RequestID  string         `json:"requestId"`
	RequestVer int            `json:"requestVer"`
}

OptionSeriesCache is an object containing what is returned from an option series request

type OptionSeriesRequestSignature

type OptionSeriesRequestSignature struct {
	// ticker for option series request
	Ticker string

	// internal use only
	UniqueID string
}

OptionSeriesRequestSignature is the parameter for a chart request

type QuoteField

type QuoteField string

QuoteField is a custom type for quote fields (backed by string)

type QuoteItem

type QuoteItem struct {
	Symbol string      `json:"symbol"`
	Values quoteValues `json:"values"`
}

QuoteItem is a single item in a QuoteResponse

type QuoteRequestSignature

type QuoteRequestSignature struct {
	// ticker for the content of a quote request
	Ticker string

	// how frequently to get a quote (TODO: useless for flux)
	RefreshRate int

	Fields []QuoteField
}

QuoteRequestSignature is the parameter for a quote request

type QuoteStoredCache

type QuoteStoredCache struct {
	Items     []QuoteItem `json:"items"`
	Service   string      `json:"service"`
	RequestID string      `json:"requestId"`
	Ver       int         `json:"ver"`
}

QuoteStoredCache is the response from a quote request

type SearchRequestSignature

type SearchRequestSignature struct {
	// pattern is the search query for the request
	Pattern string

	// limit is the number of results to pull up, typically 3-5 is normal
	Limit int

	// internal use only
	UniqueID string
}

SearchRequestSignature is the parameter for a search request

type SearchStoredCache

type SearchStoredCache struct {
	Instruments []struct {
		Composite              bool   `json:"composite"`
		Cusip                  string `json:"cusip,omitempty"`
		DaysToExpiration       int    `json:"daysToExpiration"`
		Description            string `json:"description"`
		DisplaySymbol          string `json:"displaySymbol"`
		ExtoEnabled            bool   `json:"extoEnabled"`
		Flags                  int    `json:"flags"`
		FractionalType         string `json:"fractionalType"`
		FutureOption           bool   `json:"futureOption"`
		HasOptions             bool   `json:"hasOptions"`
		ID                     int    `json:"id"`
		Industry               int    `json:"industry"`
		InstrumentType         string `json:"instrumentType"`
		IsFutureProduct        bool   `json:"isFutureProduct"`
		Multiplier             int    `json:"multiplier"`
		RootDisplaySymbol      string `json:"rootDisplaySymbol"`
		RootSymbol             string `json:"rootSymbol"`
		SourceType             string `json:"sourceType"`
		Spc                    int    `json:"spc"`
		SpreadDaysToExpiration string `json:"spreadDaysToExpiration"`
		SpreadsSupported       bool   `json:"spreadsSupported"`
		Symbol                 string `json:"symbol"`
		Tradeable              bool   `json:"tradeable"`
	} `json:"instruments"`
	RequestID  string `json:"requestId"`
	RequestVer int    `json:"requestVer"`
	Service    string `json:"service"`
}

SearchStoredCache is the response for search request

type Session

type Session struct {
	TdaSession tda.Session

	ConfigURL                 string
	CurrentState              storedCache
	TransactionChannel        chan storedCache
	NotificationChannel       chan bool
	ChartRequestVers          map[string]int
	QuoteRequestVers          map[string]int
	SearchRequestVers         map[string]int
	OptionSeriesRequestVers   map[string]int
	OptionChainGetRequestVers map[string]int
	OptionQuoteRequestVers    map[string]int
	Mu                        sync.Mutex
	QuoteMu                   sync.Mutex
	MutexLock                 bool
	HandlerWorking            bool
	DebugFlag                 bool
	Established               bool
	// contains filtered or unexported fields
}

Session is the session object for the flux driver and can be created and returned using flux.New()

func New

func New(creds tda.Session, debug bool) (*Session, error)

New takes the input of a tda.Session (see github.com/adityaxdiwakar/tda-go) and returns a flux Session which is used for all essentially library uses

func (*Session) Close

func (s *Session) Close() error

Close sends a websocket.CloseMessage to the server and waits for closure

func (*Session) Gateway

func (s *Session) Gateway() (string, error)

Gateway returns the gateway URL as a string for the live trading connection to be made

func (*Session) Open

func (s *Session) Open() error

Open is a method that opens the websocket connection with the TDAmeritrade server and returns an error if it is present

func (*Session) RequestChart

func (s *Session) RequestChart(specs ChartRequestSignature) (*ChartStoredCache, error)

RequestChart takes a ChartRequestSignature as an input and responds with a ChartStoredCache object, it utilizes the cached if it can (with updated diffs), or else it makes a new request and waits for it - if a ticker does not load in time, ErrNotReceviedInTime is sent as an error

func (*Session) RequestMultipleCharts

func (s *Session) RequestMultipleCharts(specsSlice []ChartRequestSignature) ([]*ChartStoredCache, []ChartRequestSignature)

RequestMultipleCharts takes a slice of ChartRequestSignature as an input and responds with a a slice of chart objects, it utilizes the cached if it can (with updated diffs), or else it makes a new request and waits for it - if a ticker does not load in time, ErrNotReceviedInTime is sent as an error

func (*Session) RequestOptionChainGet

func (s *Session) RequestOptionChainGet(spec OptionChainGetRequestSignature) (*[]OptionChainSeries, error)

RequestOptionChainGet requests to get an option chain with the input being the OptionChainGetRequestSignature

func (*Session) RequestOptionQuote

func (s *Session) RequestOptionQuote(spec OptionQuoteRequestSignature) (*OptionQuoteCache, error)

RequestOptionQuote requests to get an option quote with the spec OptionQuoteRequestSignature

func (*Session) RequestOptionSeries

func (s *Session) RequestOptionSeries(spec OptionSeriesRequestSignature) (*[]OptionSeries, error)

RequestOptionSeries returns options series data for a specific series based on the spec provided

func (*Session) RequestQuote

func (s *Session) RequestQuote(specs QuoteRequestSignature) (*QuoteStoredCache, error)

RequestQuote returns the quote for the relevant spec with the fields requested

func (*Session) RequestSearch

func (s *Session) RequestSearch(spec SearchRequestSignature) (*SearchStoredCache, error)

RequestSearch takes a SearchRequestSignature as an input and responds with a search query, it does not utilize a cache (although it maintains one) so the query made will be up to date with the servers. If the query is not loaded within a certain time, ErrNotReceivedInTime is sent as an error

func (*Session) Reset

func (s *Session) Reset() error

Reset resets the state; it does not reset the connection

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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