tdameritrade

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2020 License: MIT Imports: 15 Imported by: 0

README

go-tdameritrade

go client for the tdameritrade api

Documentation

import "github.com/jay-fyi/go-tdameritrade"

go-tdameritrade handles all interaction with the TD Ameritrade REST API. See the TD Ameritrade developer site to learn how their APIs work. This is a very thin wrapper and does not perform any validation. go-tdameritrade doesn't support streaming yet.

Authentication with TD Ameritrade

There is an example of using OAuth2 to authenticate a user and use the services on the TD Ameritrade API in examples/webauth/webauth.go. Authentication is handled by the Authenticator struct and its methods StartOAuth2Flow and FinishOAuth2Flow. You can get an authenticated tdameritrade.Client from an authenticated request with the AuthenticatedClient method, and use that to interact with the TD API. See auth.go.

// Authenticator is a helper for TD Ameritrade's authentication.
// It authenticates users and validates the state returned from TD Ameritrade to protect users from CSRF attacks.
// It's recommended to use NewAuthenticator instead of creating this struct directly because TD Ameritrade requires Client IDs to be in the form clientid@AMER.OAUTHAP.
// This is not immediately obvious from the documentation.
// See https://developer.tdameritrade.com/content/authentication-faq
type Authenticator struct {
	Store  PersistentStore
	OAuth2 oauth2.Config
}

The library handles state generation and the OAuth2 flow. Users simply implement the PersistentStore interface (see auth.go) and tell it how to store and retrieve OAuth2 state and an oauth2.Token with the logged in user's credentials.

// PersistentStore is meant to persist data from TD Ameritrade that is needed between requests.
// Implementations must return the same value they set for a user in StoreState in GetState, or the login process will fail.
// It is meant to allow credentials to be stored in cookies, JWTs and anything else you can think of.
type PersistentStore interface {
	StoreToken(token *oauth2.Token, w http.ResponseWriter, req *http.Request) error
	GetToken(req *http.Request) (*oauth2.Token, error)
	StoreState(state string, w http.ResponseWriter, req *http.Request) error
	GetState(*http.Request) (string, error)
}

Interacting with the TD Ameritrade API

The library is centered around the tdameritrade.Client. It allows access to all services exposed by the TD Ameritrade REST API. More information about each service can be found on TD Ameritrade's developer website.

// A Client manages communication with the TD-Ameritrade API.
type Client struct {
	client *http.Client // HTTP client used to communicate with the API.

	// Base URL for API requests. Defaults to the public TD-Ameritrade API, but can be
	// set to any endpoint. This allows for more manageable testing.
	BaseURL *url.URL

	// services used for talking to different parts of the tdameritrade api
	PriceHistory       *PriceHistoryService
	Account            *AccountsService
	MarketHours        *MarketHoursService
	Quotes             *QuotesService
	Instrument         *InstrumentService
	Chains             *ChainsService
	Mover              *MoverService
	TransactionHistory *TransactionHistoryService
	User               *UserService
	Watchlist          *WatchlistService
}

You get a tdameritrade.Client from the FinishOAuth2 or AuthenticatedClient method on the tdameritrade.Authenticator struct.

Examples

More examples are in the examples directory.

Configuring the Authenticator from an environment variable
clientID := os.Getenv("TDAMERITRADE_CLIENT_ID")
if clientID == "" {
	log.Fatal("Unauthorized: No client ID present")
}

authenticator := tdameritrade.NewAuthenticator(
	&HTTPHeaderStore{},
	oauth2.Config{
		ClientID: clientID,
		Endpoint: oauth2.Endpoint{
			TokenURL: "https://api.tdameritrade.com/v1/oauth2/token",
			AuthURL:  "https://auth.tdameritrade.com/auth",
		},
		RedirectURL: "https://localhost:8080/callback",
	},
)
Authenticating a user with OAuth2
type TDHandlers struct {
	authenticator *tdameritrade.Authenticator
}

func (h *TDHandlers) Authenticate(w http.ResponseWriter, req *http.Request) {
	redirectURL, err := h.authenticator.StartOAuth2Flow(w, req)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	http.Redirect(w, req, redirectURL, http.StatusTemporaryRedirect)
}

func (h *TDHandlers) Callback(w http.ResponseWriter, req *http.Request) {
	ctx := context.Background()
	_, err := h.authenticator.FinishOAuth2Flow(ctx, w, req)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	http.Redirect(w, req, "/quote?ticker=SPY", http.StatusTemporaryRedirect)
}
Looking up a stock quote using the API.
type TDHandlers struct {
	authenticator *tdameritrade.Authenticator
}

func (h *TDHandlers) Quote(w http.ResponseWriter, req *http.Request) {
	ctx := context.Background()
	client, err := h.authenticator.AuthenticatedClient(ctx, req)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	ticker, ok := req.URL.Query()["ticker"]
	if !ok || len(ticker) == 0 {
		w.Write([]byte("ticker is required"))
		return
	}

	quote, _, err := client.Quotes.GetQuotes(ctx, ticker[0])
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	body, err := json.Marshal(quote)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	w.Write(body)

}

Use at your own risk.

Documentation

Overview

Package tdameritrade is a wrapper around the TD Ameritrade REST API. It contains helpers for building apps that interact with TD Ameritrade's API on behalf of traders.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoCode is returned when the TD Ameritrade request is missing a code.
	ErrNoCode = fmt.Errorf("missing code in request from TD Ameritrade")

	// ErrNoState is returned when TD Ameritrade request is missing state, indicating a CSRF attempt.
	ErrNoState = fmt.Errorf("missing state in request from TD Ameritrade")
)
View Source
var (
	ChangeTypes    = []string{"value", "percent"}
	DirectionTypes = []string{"up", "down"}
)

Functions

This section is empty.

Types

type Account

type Account struct {
	SecuritiesAccount `json:"securitiesAccount"`
}

type AccountOptions

type AccountOptions struct {
	Position bool
	Orders   bool
}

type Accounts

type Accounts []*Account

type AccountsService

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

AccountsService handles communication with the account related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/account-access/apis

func (*AccountsService) CancelOrder

func (s *AccountsService) CancelOrder(ctx context.Context, accountID, orderID string) (*Response, error)

func (*AccountsService) CreateSavedOrder

func (s *AccountsService) CreateSavedOrder(ctx context.Context, accountID string, order *Order) (*Response, error)

func (*AccountsService) DeleteSavedOrder

func (s *AccountsService) DeleteSavedOrder(ctx context.Context, accountID, savedOrderID string) (*Response, error)

func (*AccountsService) GetAccount

func (s *AccountsService) GetAccount(ctx context.Context, accountID string, opts *AccountOptions) (*Account, *Response, error)

func (*AccountsService) GetAccounts

func (s *AccountsService) GetAccounts(ctx context.Context, opts *AccountOptions) (*Accounts, *Response, error)

func (*AccountsService) GetOrder

func (s *AccountsService) GetOrder(ctx context.Context, accountID, orderID string) (*Response, error)

func (*AccountsService) GetOrderByPath

func (s *AccountsService) GetOrderByPath(ctx context.Context, accountID string, orderParams *OrderParams) (*Response, error)

func (*AccountsService) GetOrderByQuery

func (s *AccountsService) GetOrderByQuery(ctx context.Context, accountID string, orderParams *OrderParams) (*Response, error)

func (*AccountsService) GetSavedOrder

func (s *AccountsService) GetSavedOrder(ctx context.Context, accountID, savedOrderID string, orderParams *OrderParams) (*Response, error)

func (*AccountsService) PlaceOrder

func (s *AccountsService) PlaceOrder(ctx context.Context, accountID string, order *Order) (*Response, error)

func (*AccountsService) ReplaceOrder

func (s *AccountsService) ReplaceOrder(ctx context.Context, accountID string, orderID string, order *Order) (*Response, error)

func (*AccountsService) ReplaceSavedOrder

func (s *AccountsService) ReplaceSavedOrder(ctx context.Context, accountID, savedOrderID string, order *Order) (*Response, error)

type Authenticator

type Authenticator struct {
	Store  PersistentStore
	OAuth2 oauth2.Config
}

Authenticator is a helper for TD Ameritrade's authentication. It authenticates users and validates the state returned from TD Ameritrade to protect users from CSRF attacks. It's recommended to use NewAuthenticator instead of creating this struct directly because TD Ameritrade requires Client IDs to be in the form clientid@AMER.OAUTHAP. This is not immediately obvious from the documentation. See https://developer.tdameritrade.com/content/authentication-faq

func NewAuthenticator

func NewAuthenticator(store PersistentStore, oauth2 oauth2.Config) *Authenticator

NewAuthenticator will automatically append @AMER.OAUTHAP to the client ID to save callers hours of frustration.

func (*Authenticator) AuthenticatedClient

func (a *Authenticator) AuthenticatedClient(ctx context.Context, req *http.Request) (*Client, error)

AuthenticatedClient tries to create an authenticated `Client` from a user's request

func (*Authenticator) FinishOAuth2Flow

func (a *Authenticator) FinishOAuth2Flow(ctx context.Context, w http.ResponseWriter, req *http.Request) (*Client, error)

FinishOAuth2Flow finishes authenticating a user returning from TD Ameritrade. It verifies that TD Ameritrade has returned the expected state to prevent CSRF attacks and returns an authenticated `Client` on success.

func (*Authenticator) StartOAuth2Flow

func (a *Authenticator) StartOAuth2Flow(w http.ResponseWriter, req *http.Request) (string, error)

StartOAuth2Flow returns TD Ameritrade's Auth URL and stores a random state value. Redirect users to the returned URL to begin authentication.

type Authorizations

type Authorizations struct {
	Apex               bool   `json:"apex"`
	LevelTwoQuotes     bool   `json:"levelTwoQuotes"`
	StockTrading       bool   `json:"stockTrading"`
	MarginTrading      bool   `json:"marginTrading"`
	StreamingNews      bool   `json:"streamingNews"`
	OptionTradingLevel string `json:"optionTradingLevel"`
	StreamerAccess     bool   `json:"streamerAccess"`
	AdvancedMargin     bool   `json:"advancedMargin"`
	ScottradeAccount   bool   `json:"scottradeAccount"`
}

type Balance

type Balance struct {
	AccruedInterest              float64 `json:"accruedInterest"`
	CashBalance                  float64 `json:"cashBalance"`
	CashReceipts                 float64 `json:"cashReceipts"`
	LongOptionMarketValue        float64 `json:"longOptionMarketValue"`
	LiquidationValue             float64 `json:"liquidationValue"`
	LongMarketValue              float64 `json:"longMarketValue"`
	MoneyMarketFund              float64 `json:"moneyMarketFund"`
	Savings                      float64 `json:"savings"`
	ShortMarketValue             float64 `json:"shortMarketValue"`
	PendingDeposits              float64 `json:"pendingDeposits"`
	CashAvailableForTrading      float64 `json:"cashAvailableForTrading"`
	CashAvailableForWithdrawal   float64 `json:"cashAvailableForWithdrawal"`
	CashCall                     float64 `json:"cashCall"`
	LongNonMarginableMarketValue float64 `json:"longNonMarginableMarketValue"`
	TotalCash                    float64 `json:"totalCash"`
	ShortOptionMarketValue       float64 `json:"shortOptionMarketValue"`
	MutualFundValue              float64 `json:"mutualFundValue"`
	BondValue                    float64 `json:"bondValue"`
	CashDebitCallValue           float64 `json:"cashDebitCallValue"`
	UnsettledCash                float64 `json:"unsettledCash"`
}

type CancelTime

type CancelTime struct {
	Date        string `json:"date,omitempty"`
	ShortFormat bool   `json:"shortFormat,omitempty"`
}

type CashEquivalent

type CashEquivalent struct {
	Cusip       string `json:"cusip,omitempty"`
	Symbol      string `json:"symbol"`
	Description string `json:"description,omitempty"`
	Type        string `json:"type"` //"'SAVINGS' or 'MONEY_MARKET_FUND'"
}

type Chains

type Chains struct {
	Symbol            string     `json:"symbol"`
	Status            string     `json:"status"`
	Underlying        Underlying `json:"underlying"`
	Strategy          string     `json:"strategy"`
	Interval          float64    `json:"interval"`
	IsDelayed         bool       `json:"isDelayed"`
	IsIndex           bool       `json:"isIndex"`
	InterestRate      float64    `json:"interestRate"`
	UnderlyingPrice   float64    `json:"underlyingPrice"`
	Volatility        float64    `json:"volatility"`
	DaysToExpiration  float64    `json:"daysToExpiration"`
	NumberOfContracts int        `json:"numberOfContracts"`
	CallExpDateMap    ExpDateMap `json:"callExpDateMap"`
	PutExpDateMap     ExpDateMap `json:"putExpDateMap"`
}

type ChainsService

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

ChainsService handles communication with the chains related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/option-chains/apis

func (*ChainsService) GetChains

func (s *ChainsService) GetChains(ctx context.Context, queryValues url.Values) (*Chains, *Response, error)

Users must provide the required URL queryValues for this function to work. TD Ameritrade url values: https://developer.tdameritrade.com/option-chains/apis/get/marketdata/chains Instructions for using url.Values: https://golang.org/pkg/net/url/#Values

type Client

type Client struct {

	// Base URL for API requests. Defaults to the public TD-Ameritrade API, but can be
	// set to any endpoint. This allows for more manageable testing.
	BaseURL *url.URL

	// services used for talking to different parts of the tdameritrade api
	PriceHistory       *PriceHistoryService
	Account            *AccountsService
	MarketHours        *MarketHoursService
	Quotes             *QuotesService
	Instrument         *InstrumentService
	Chains             *ChainsService
	Mover              *MoverService
	TransactionHistory *TransactionHistoryService
	User               *UserService
	Watchlist          *WatchlistService
	// contains filtered or unexported fields
}

A Client manages communication with the TD-Ameritrade API.

func NewClient

func NewClient(httpClient *http.Client) (*Client, error)

NewClient returns a new TD-Ameritrade API client. If a nil httpClient is provided, a new http.Client will be used. To use API methods which require authentication, provide an http.Client that will perform the authentication for you (such as that provided by the golang.org/x/oauth2 library).

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error)

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body.

func (*Client) UpdateBaseURL

func (c *Client) UpdateBaseURL(baseURL string) error

type Equity

type Equity struct {
	Cusip       string `json:"cusip,omitempty"`
	Symbol      string `json:"symbol"`
	Description string `json:"description,omitempty"`
}

type Execution

type Execution struct {
	ActivityType           string          `json:"activityType"`  //"'EXECUTION' or 'ORDER_ACTION'",
	ExecutionType          string          `json:"executionType"` //"'FILL'",
	Quantity               float64         `json:"quantity"`
	OrderRemainingQuantity float64         `json:"orderRemainingQuantity"`
	ExecutionLegs          []*ExecutionLeg `json:"executionLegs"`
}

type ExecutionLeg

type ExecutionLeg struct {
	LegID             int64   `json:"legId"`
	Quantity          float64 `json:"quantity"`
	MismarkedQuantity float64 `json:"mismarkedQuantity"`
	Price             float64 `json:"price"`
	Time              string  `json:"time"`
}

type ExpDateMap

type ExpDateMap map[string]map[string][]ExpDateOption

the first string is the exp date. the second string is the strike price.

type ExpDateOption

type ExpDateOption struct {
	PutCall                string  `json:"putCall"`
	Symbol                 string  `json:"symbol"`
	Description            string  `json:"description"`
	ExchangeName           string  `json:"exchangeName"`
	Bid                    float64 `json:"bid"`
	Ask                    float64 `json:"ask"`
	Last                   float64 `json:"last"`
	Mark                   float64 `json:"mark"`
	BidSize                int     `json:"bidSize"`
	AskSize                int     `json:"askSize"`
	BidAskSize             string  `json:"bidAskSize"`
	LastSize               float64 `json:"lastSize"`
	HighPrice              float64 `json:"highPrice"`
	LowPrice               float64 `json:"lowPrice"`
	OpenPrice              float64 `json:"openPrice"`
	ClosePrice             float64 `json:"closePrice"`
	TotalVolume            int     `json:"totalVolume"`
	TradeDate              string  `json:"tradeDate"`
	TradeTimeInLong        int     `json:"tradeTimeInLong"`
	QuoteTimeInLong        int     `json:"quoteTimeInLong"`
	NetChange              float64 `json:"netChange"`
	Volatility             float64 `json:"volatility"`
	Delta                  float64 `json:"delta"`
	Gamma                  float64 `json:"gamma"`
	Theta                  float64 `json:"theta"`
	Vega                   float64 `json:"vega"`
	Rho                    float64 `json:"rho"`
	OpenInterest           int     `json:"openInterest"`
	TimeValue              float64 `json:"timeValue"`
	TheoreticalOptionValue float64 `json:"theoreticalOptionValue"`
	TheoreticalVolatility  float64 `json:"theoreticalVolatility"`
	OptionDeliverablesList string  `json:"optionDeliverablesList"`
	StrikePrice            float64 `json:"strikePrice"`
	ExpirationDate         int     `json:"expirationDate"`
	DaysToExpiration       int     `json:"daysToExpiration"`
	ExpirationType         string  `json:"expirationType"`
	LastTradingDate        int     `json:"lastTradingDay"`
	Multiplier             float64 `json:"multiplier"`
	SettlementType         string  `json:"settlementType"`
	DeliverableNote        string  `json:"deliverableNote"`
	IsIndexOption          bool    `json:"isIndexOption"`
	PercentChange          float64 `json:"percentChange"`
	MarkChange             float64 `json:"markChange"`
	MarkPercentChange      float64 `json:"markPercentChange"`
	InTheMoney             bool    `json:"inTheMoney"`
	Mini                   bool    `json:"mini"`
	NonStandard            bool    `json:"nonStandard"`
}

type FixedIncome

type FixedIncome struct {
	Cusip        string  `json:"cusip"`
	Symbol       string  `json:"symbol"`
	Description  string  `json:"description"`
	MaturityDate string  `json:"maturityDate"`
	VariableRate float64 `json:"variableRate"`
	Factor       float64 `json:"factor"`
}

type Hours

type Hours struct {
	Category     string       `json:"category"`
	Date         string       `json:"date"`
	Exchange     string       `json:"exchange"`
	IsOpen       bool         `json:"isOpen"`
	MarketType   string       `json:"marketType"`
	Product      string       `json:"product"`
	ProductName  string       `json:"productName"`
	SessionHours SessionHours `json:"sessionHours"`
}

type Instrument

type Instrument struct {
	AssetType string `json:"assetType"`
	Data      interface{}
}

func (*Instrument) MarshalJSON

func (i *Instrument) MarshalJSON() ([]byte, error)

func (*Instrument) UnmarshalJSON

func (i *Instrument) UnmarshalJSON(bs []byte) (err error)

type InstrumentInfo

type InstrumentInfo struct {
	Cusip       string `json:"cusip,omitempty"`
	Symbol      string `json:"symbol"`
	Description string `json:"description,omitempty"`
	Type        string `json:"assetType"` //"'NOT_APPLICABLE' or 'OPEN_END_NON_TAXABLE' or 'OPEN_END_TAXABLE' or 'NO_LOAD_NON_TAXABLE' or 'NO_LOAD_TAXABLE'"
	Exchange    string `json:"exchange"`
}

type InstrumentService

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

InstrumentService handles communication with the marketdata related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/instruments/apis

func (*InstrumentService) GetInstrument

func (s *InstrumentService) GetInstrument(ctx context.Context, cusip string) (*Instruments, *Response, error)

func (*InstrumentService) SearchInstruments

func (s *InstrumentService) SearchInstruments(ctx context.Context, symbol, projection string) (*Instruments, *Response, error)

type Instruments

type Instruments map[string]*InstrumentInfo

type KeyEntry

type KeyEntry struct {
	Key string `json:"key"`
}

type MarketHours

type MarketHours map[string]map[string]*Hours

type MarketHoursService

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

MarketHoursService handles communication with the marketdata related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/market-hours/apis

func (*MarketHoursService) GetMarketHours

func (s *MarketHoursService) GetMarketHours(ctx context.Context, market string, date time.Time) (*MarketHours, *Response, error)

func (*MarketHoursService) GetMarketHoursMulti

func (s *MarketHoursService) GetMarketHoursMulti(ctx context.Context, markets string, date time.Time) (*MarketHours, *Response, error)

type Mover

type Mover struct {
	Change      float64 `json:"change"`
	Description string  `json:"description"`
	Direction   string  `json:"direction"`
	Last        float64 `json:"last"`
	TotalVolume float64 `json:"totalVolume"`
	Symbol      string  `json:"symbol"`
}

type MoverOptions

type MoverOptions struct {
	Direction  string `url:"direction"`
	ChangeType string `url:"change"`
}

type MoverService

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

func (*MoverService) Mover

func (s *MoverService) Mover(ctx context.Context, symbol string, opts *MoverOptions) (*[]Mover, *Response, error)

type MutualFund

type MutualFund struct {
	Cusip       string `json:"cusip,omitempty"`
	Symbol      string `json:"symbol"`
	Description string `json:"description,omitempty"`
	Type        string `json:"type"` //"'NOT_APPLICABLE' or 'OPEN_END_NON_TAXABLE' or 'OPEN_END_TAXABLE' or 'NO_LOAD_NON_TAXABLE' or 'NO_LOAD_TAXABLE'"
}

type NewWatchlist

type NewWatchlist struct {
	Name           string          `json:"name"`
	WatchlistItems []WatchlistItem `json:"watchlistItems"`
}

NewWatchlist is a watchlist to be created by a user.

type OptionA

type OptionA struct {
	Cusip              string               `json:"cusip,omitempty"`
	Symbol             string               `json:"symbol"`
	Description        string               `json:"description,omitempty"`
	Type               string               `json:"type"`
	PutCall            string               `json:"putCall"`
	UnderlyingSymbol   string               `json:"underlyingSymbol"`
	OptionMultiplier   float64              `json:"optionMultiplier"`
	OptionDeliverables []*OptionDeliverable `json:"optionDeliverables"`
}

type OptionDeliverable

type OptionDeliverable struct {
	Symbol           string  `json:"symbol"`
	DeliverableUnits float64 `json:"deliverableUnits"`
	CurrencyType     string  `json:"currencyType"`
	AssetType        string  `json:"assetType"`
}

type Order

type Order struct {
	Session                  string                `json:"session"`
	Duration                 string                `json:"duration"`
	OrderType                string                `json:"orderType"`
	CancelTime               *CancelTime           `json:"cancelTime,omitempty"`
	ComplexOrderStrategyType string                `json:"complexOrderStrategyType,omitempty"`
	Quantity                 float64               `json:"quantity,omitempty"`
	FilledQuantity           float64               `json:"filledQuantity,omitempty"`
	RemainingQuantity        float64               `json:"remainingQuantity,omitempty"`
	RequestedDestination     string                `json:"requestedDestination,omitempty"`
	DestinationLinkName      string                `json:"destinationLinkName,omitempty"`
	ReleaseTime              string                `json:"releaseTime,omitempty"`
	StopPrice                float64               `json:"stopPrice,omitempty"`
	StopPriceLinkBasis       string                `json:"stopPriceLinkBasis,omitempty"`
	StopPriceLinkType        string                `json:"stopPriceLinkType,omitempty"`
	StopPriceOffset          float64               `json:"stopPriceOffset,omitempty"`
	StopType                 string                `json:"stopType,omitempty"`
	PriceLinkBasis           string                `json:"priceLinkBasis,omitempty"`
	PriceLinkType            string                `json:"priceLinkType,omitempty"`
	Price                    float64               `json:"price,omitempty"`
	TaxLotMethod             string                `json:"taxLotMethod,omitempty"`
	OrderLegCollection       []*OrderLegCollection `json:"orderLegCollection"`
	ActivationPrice          float64               `json:"activationPrice,omitempty"`
	SpecialInstruction       string                `json:"specialInstruction,omitempty"`
	OrderStrategyType        string                `json:"orderStrategyType"`
	OrderID                  int64                 `json:"orderId,omitempty"`
	Cancelable               bool                  `json:"cancelable,omitempty"`
	Editable                 bool                  `json:"editable,omitempty"`
	Status                   string                `json:"status,omitempty"`
	EnteredTime              string                `json:"enteredTime,omitempty"`
	CloseTime                string                `json:"closeTime,omitempty"`
	Tag                      string                `json:"tag,omitempty"`
	AccountID                float64               `json:"accountId,omitempty"`
	OrderActivityCollection  []*Execution          `json:"orderActivityCollection,omitempty"`
	ReplacingOrderCollection []*Order              `json:"replacingOrderCollection,omitempty"`
	ChildOrderStrategies     []*Order              `json:"childOrderStrategies,omitempty"`
	StatusDescription        string                `json:"statusDescription,omitempty"`
}

type OrderLegCollection

type OrderLegCollection struct {
	OrderLegType   string     `json:"orderLegType,omitempty"`
	LegID          int        `json:"legId,omitempty"`
	Instrument     Instrument `json:"instrument"`
	Instruction    string     `json:"instruction"`
	PositionEffect string     `json:"positionEffect,omitempty"`
	Quantity       int        `json:"quantity"`
	QuantityType   string     `json:"quantityType,omitempty"`
}

type OrderParams

type OrderParams struct {
	MaxResults int
	From       time.Time
	To         time.Time
	Status     string
}

type Period

type Period struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

type PersistentStore

type PersistentStore interface {
	StoreToken(token *oauth2.Token, w http.ResponseWriter, req *http.Request) error
	GetToken(req *http.Request) (*oauth2.Token, error)
	StoreState(state string, w http.ResponseWriter, req *http.Request) error
	GetState(*http.Request) (string, error)
}

PersistentStore is meant to persist data from TD Ameritrade that is needed between requests. Implementations must return the same value they set for a user in StoreState in GetState, or the login process will fail. It is meant to allow credentials to be stored in cookies, JWTs and anything else you can think of.

type Preferences

type Preferences struct {
	ExpressTrading                   bool   `json:"expressTrading"`
	DirectOptionsRouting             bool   `json:"directOptionsRouting"`
	DirectEquityRouting              bool   `json:"directEquityRouting"`
	DefaultEquityOrderLegInstruction string `json:"defaultEquityOrderLegInstruction"`
	DefaultEquityOrderType           string `json:"defaultEquityOrderType"`
	DefaultEquityOrderPriceLinkType  string `json:"defaultEquityOrderPriceLinkType"`
	DefaultEquityOrderDuration       string `json:"defaultEquityOrderDuration"`
	DefaultEquityOrderMarketSession  string `json:"defaultEquityOrderMarketSession"`
	DefaultEquityQuantity            int    `json:"defaultEquityQuantity"`
	MutualFundTaxLotMethod           string `json:"mutualFundTaxLotMethod"`
	OptionTaxLotMethod               string `json:"optionTaxLotMethod"`
	EquityTaxLotMethod               string `json:"equityTaxLotMethod"`
	DefaultAdvancedToolLaunch        string `json:"defaultAdvancedToolLaunch"`
	AuthTokenTimeout                 string `json:"authTokenTimeout"`
}

type PriceHistory

type PriceHistory struct {
	Candles []struct {
		Close    float64 `json:"close"`
		Datetime int     `json:"datetime"`
		High     float64 `json:"high"`
		Low      float64 `json:"low"`
		Open     float64 `json:"open"`
		Volume   float64 `json:"volume"`
	} `json:"candles"`
	Empty  bool   `json:"empty"`
	Symbol string `json:"symbol"`
}

type PriceHistoryOptions

type PriceHistoryOptions struct {
	PeriodType            string    `url:"periodType"`
	Period                int       `url:"period"`
	FrequencyType         string    `url:"frequencyType"`
	Frequency             int       `url:"frequency"`
	EndDate               time.Time `url:"endDate"`
	StartDate             time.Time `url:"startDate"`
	NeedExtendedHoursData *bool     `url:"needExtendedHoursData"`
}

PriceHistoryOptions is parsed and translated to query options in the https request

type PriceHistoryService

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

PriceHistoryService handles communication with the marketdata related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/price-history/apis

func (*PriceHistoryService) PriceHistory

func (s *PriceHistoryService) PriceHistory(ctx context.Context, symbol string, opts *PriceHistoryOptions) (*PriceHistory, *Response, error)

PriceHistory get the price history for a symbol TDAmeritrade API Docs: https://developer.tdameritrade.com/price-history/apis/get/marketdata/%7Bsymbol%7D/pricehistory

type Quote

type Quote struct {
	AssetType                          string  `json:"assetType"`
	AssetMainType                      string  `json:"assetMainType"`
	Cusip                              string  `json:"cusip"`
	AssetSubType                       string  `json:"assetSubType"`
	Symbol                             string  `json:"symbol"`
	Description                        string  `json:"description"`
	BidPrice                           float64 `json:"bidPrice"`
	BidSize                            float64 `json:"bidSize"`
	BidID                              string  `json:"bidId"`
	AskPrice                           float64 `json:"askPrice"`
	AskSize                            float64 `json:"askSize"`
	AskID                              string  `json:"askId"`
	LastPrice                          float64 `json:"lastPrice"`
	LastSize                           float64 `json:"lastSize"`
	LastID                             string  `json:"lastId"`
	OpenPrice                          float64 `json:"openPrice"`
	HighPrice                          float64 `json:"highPrice"`
	LowPrice                           float64 `json:"lowPrice"`
	BidTick                            string  `json:"bidTick"`
	ClosePrice                         float64 `json:"closePrice"`
	NetChange                          float64 `json:"netChange"`
	TotalVolume                        float64 `json:"totalVolume"`
	QuoteTimeInLong                    int64   `json:"quoteTimeInLong"`
	TradeTimeInLong                    int64   `json:"tradeTimeInLong"`
	Mark                               float64 `json:"mark"`
	Exchange                           string  `json:"exchange"`
	ExchangeName                       string  `json:"exchangeName"`
	Marginable                         bool    `json:"marginable"`
	Shortable                          bool    `json:"shortable"`
	Volatility                         float64 `json:"volatility"`
	Digits                             int     `json:"digits"`
	Five2WkHigh                        float64 `json:"52WkHigh"`
	Five2WkLow                         float64 `json:"52WkLow"`
	NAV                                float64 `json:"nAV"`
	PeRatio                            float64 `json:"peRatio"`
	DivAmount                          float64 `json:"divAmount"`
	DivYield                           float64 `json:"divYield"`
	DivDate                            string  `json:"divDate"`
	SecurityStatus                     string  `json:"securityStatus"`
	RegularMarketLastPrice             float64 `json:"regularMarketLastPrice"`
	RegularMarketLastSize              int     `json:"regularMarketLastSize"`
	RegularMarketNetChange             float64 `json:"regularMarketNetChange"`
	RegularMarketTradeTimeInLong       int64   `json:"regularMarketTradeTimeInLong"`
	NetPercentChangeInDouble           float64 `json:"netPercentChangeInDouble"`
	MarkChangeInDouble                 float64 `json:"markChangeInDouble"`
	MarkPercentChangeInDouble          float64 `json:"markPercentChangeInDouble"`
	RegularMarketPercentChangeInDouble float64 `json:"regularMarketPercentChangeInDouble"`
	Delayed                            bool    `json:"delayed"`
}

type QuoteDelays

type QuoteDelays struct {
	IsNyseDelayed   bool `json:"isNyseDelayed"`
	IsNasdaqDelayed bool `json:"isNasdaqDelayed"`
	IsOpraDelayed   bool `json:"isOpraDelayed"`
	IsAmexDelayed   bool `json:"isAmexDelayed"`
	IsCmeDelayed    bool `json:"isCmeDelayed"`
	IsIceDelayed    bool `json:"isIceDelayed"`
	IsForexDelayed  bool `json:"isForexDelayed"`
}

type Quotes

type Quotes map[string]*Quote

type QuotesService

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

QuotesService handles communication with the marketdata related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/quotes/apis

func (*QuotesService) GetQuotes

func (s *QuotesService) GetQuotes(ctx context.Context, symbols string) (*Quotes, *Response, error)

type Response

type Response struct {
	*http.Response
}

type SecuritiesAccount

type SecuritiesAccount struct {
	Type                    string  `json:"type"`
	AccountID               string  `json:"accountId"`
	RoundTrips              float64 `json:"roundTrips"`
	IsDayTrader             bool    `json:"isDayTrader"`
	IsClosingOnlyRestricted bool    `json:"isClosingOnlyRestricted"`
	Positions               []struct {
		ShortQuantity                  float64    `json:"shortQuantity"`
		AveragePrice                   float64    `json:"averagePrice"`
		CurrentDayProfitLoss           float64    `json:"currentDayProfitLoss"`
		CurrentDayProfitLossPercentage float64    `json:"currentDayProfitLossPercentage"`
		LongQuantity                   float64    `json:"longQuantity"`
		SettledLongQuantity            float64    `json:"settledLongQuantity"`
		SettledShortQuantity           float64    `json:"settledShortQuantity"`
		AgedQuantity                   float64    `json:"agedQuantity"`
		Instrument                     Instrument `json:"instrument"`
		MarketValue                    float64    `json:"marketValue"`
	} `json:"positions"`
	OrderStrategies []struct {
		Session    string `json:"session"`
		Duration   string `json:"duration"`
		OrderType  string `json:"orderType"`
		CancelTime struct {
			Date        string `json:"date"`
			ShortFormat bool   `json:"shortFormat"`
		} `json:"cancelTime"`
		ComplexOrderStrategyType string  `json:"complexOrderStrategyType"`
		Quantity                 float64 `json:"quantity"`
		FilledQuantity           float64 `json:"filledQuantity"`
		RemainingQuantity        float64 `json:"remainingQuantity"`
		RequestedDestination     string  `json:"requestedDestination"`
		DestinationLinkName      string  `json:"destinationLinkName"`
		ReleaseTime              string  `json:"releaseTime"`
		StopPrice                float64 `json:"stopPrice"`
		StopPriceLinkBasis       string  `json:"stopPriceLinkBasis"`
		StopPriceLinkType        string  `json:"stopPriceLinkType"`
		StopPriceOffset          float64 `json:"stopPriceOffset"`
		StopType                 string  `json:"stopType"`
		PriceLinkBasis           string  `json:"priceLinkBasis"`
		PriceLinkType            string  `json:"priceLinkType"`
		Price                    float64 `json:"price"`
		TaxLotMethod             string  `json:"taxLotMethod"`
		OrderLegCollection       []struct {
			OrderLegType   string  `json:"orderLegType"`
			LegID          int64   `json:"legId"`
			Instrument     string  `json:"instrument"`
			Instruction    string  `json:"instruction"`
			PositionEffect string  `json:"positionEffect"`
			Quantity       float64 `json:"quantity"`
			QuantityType   string  `json:"quantityType"`
		} `json:"orderLegCollection"`
		ActivationPrice          float64  `json:"activationPrice"`
		SpecialInstruction       string   `json:"specialInstruction"`
		OrderStrategyType        string   `json:"orderStrategyType"`
		OrderID                  int64    `json:"orderId"`
		Cancelable               bool     `json:"cancelable"`
		Editable                 bool     `json:"editable"`
		Status                   string   `json:"status"`
		EnteredTime              string   `json:"enteredTime"`
		CloseTime                string   `json:"closeTime"`
		Tag                      string   `json:"tag"`
		AccountID                int64    `json:"accountId"`
		OrderActivityCollection  []string `json:"orderActivityCollection"`
		ReplacingOrderCollection []struct {
		} `json:"replacingOrderCollection"`
		ChildOrderStrategies []struct {
		} `json:"childOrderStrategies"`
		StatusDescription string `json:"statusDescription"`
	} `json:"orderStrategies"`
	InitialBalances   Balance `json:"initialBalances"`
	CurrentBalances   Balance `json:"currentBalances"`
	ProjectedBalances Balance `json:"projectedBalances"`
}

type SessionHours

type SessionHours struct {
	PreMarket     []Period `json:"preMarket"`
	RegularMarket []Period `json:"regularMarket"`
	PostMarket    []Period `json:"postMarket"`
}

type StoredWatchlist

type StoredWatchlist []struct {
	Name           string                `json:"name"`
	WatchlistID    string                `json:"watchlistId"`
	AccountID      string                `json:"accountId"`
	Status         string                `json:"status"`
	WatchlistItems []StoredWatchlistItem `json:"watchlistItems"`
}

StoredWatchlist is an existing watchlist in a user's account.

type StoredWatchlistInstrument

type StoredWatchlistInstrument struct {
	Symbol      string `json:"symbol"`
	Description string `json:"description"`
	AssetType   string `json:"assetType"`
}

StoredWatchlistInstrument is an investment instrument in a user's watchlist.

type StoredWatchlistItem

type StoredWatchlistItem struct {
	SequenceID    int                       `json:"sequenceId"`
	Quantity      int                       `json:"quantity"`
	AveragePrice  int                       `json:"averagePrice"`
	Commission    int                       `json:"commission"`
	PurchasedDate string                    `json:"purchasedDate"`
	Instrument    StoredWatchlistInstrument `json:"instrument"`
	Status        string                    `json:"status"`
}

StoredWatchlistItem is an item in the user's existing watchlist.

type StreamerInfo

type StreamerInfo struct {
	StreamerBinaryURL string `json:"streamerBinaryUrl"`
	StreamerSocketURL string `json:"streamerSocketUrl"`
	Token             string `json:"token"`
	TokenTimestamp    string `json:"tokenTimestamp"`
	UserGroup         string `json:"userGroup"`
	AccessLevel       string `json:"accessLevel"`
	ACL               string `json:"acl"`
	AppID             string `json:"appId"`
}

type StreamerSubscriptionKeys

type StreamerSubscriptionKeys struct {
	Keys []KeyEntry `json:"keys"`
}

type Transaction

type Transaction struct {
	Type                          string          `json:"type"`
	ClearingReferenceNumber       string          `json:"clearingReferenceNumber"`
	SubAccount                    string          `json:"subAccount"`
	SettlementDate                string          `json:"settlementDate"`
	OrderID                       string          `json:"orderId"`
	SMA                           float64         `json:"sma"`
	RequirementReallocationAmount float64         `json:"requirementReallocationAmount"`
	DayTradeBuyingPowerEffect     float64         `json:"dayTradeBuyingPowerEffect"`
	NetAmount                     float64         `json:"netAmount"`
	TransactionDate               string          `json:"transactionDate"`
	OrderDate                     string          `json:"orderDate"`
	TransactionSubType            string          `json:"transactionSubType"`
	TransactionID                 int64           `json:"transactionId"`
	CashBalanceEffectFlag         bool            `json:"cashBalanceEffectFlag"`
	Description                   string          `json:"description"`
	ACHStatus                     string          `json:"achStatus"`
	AccruedInterest               float64         `json:"accruedInterest"`
	Fees                          TransactionFees `json:"fees"`
	TransactionItem               TransactionItem `json:"transactionItem"`
}

Transaction represents a single transaction

type TransactionFees

type TransactionFees struct {
	AdditionalFee float64 `json:"additionalFee"`
	CdscFee       float64 `json:"cdscFee"`
	Commission    float64 `json:"commission"`
	OptRegFee     float64 `json:"optRegFee"`
	OtherCharges  float64 `json:"otherCharges"`
	RFee          float64 `json:"rFee"`
	RegFee        float64 `json:"regFee"`
	SecFee        float64 `json:"secFee"`
}

TransactionFees contains fees related to the transaction

type TransactionHistoryOptions

type TransactionHistoryOptions struct {
	Type   string `url:"type,omitempty"`
	Symbol string `url:"symbol,omitempty"`
	// ISO8601 format, day granularity yyyy-MM-dd
	StartDate string `url:"startDate,omitempty"`
	// ISO8601 format, day granularity yyyy-MM-dd
	EndDate string `url:"endDate,omitempty"`
}

TransactionHistoryOptions is parsed and translated to query options in the https request

type TransactionHistoryService

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

TransactionHistoryService handles communication with the transaction history related methods of the TDAmeritrade API.

TDAmeritrade API docs: https://developer.tdameritrade.com/transaction-history/apis

func (*TransactionHistoryService) GetTransaction

func (s *TransactionHistoryService) GetTransaction(ctx context.Context, accountID string, transactionID string) (*Transaction, *Response, error)

GetTransaction gets a specific transaction by account TDAmeritrade API Docs: https://developer.tdameritrade.com/transaction-history/apis/get/accounts/%7BaccountId%7D/transactions/%7BtransactionId%7D-0

func (*TransactionHistoryService) GetTransactions

func (s *TransactionHistoryService) GetTransactions(ctx context.Context, accountID string, opts *TransactionHistoryOptions) (*Transactions, *Response, error)

GetTransactions gets all transaction by account TDAmeritrade API Docs: https://developer.tdameritrade.com/transaction-history/apis/get/accounts/%7BaccountId%7D/transactions-0

type TransactionInstrument

type TransactionInstrument struct {
	Symbol               string  `json:"symbol"`
	UnderlyingSymbol     string  `json:"underlyingSymbol"`
	OptionExpirationDate string  `json:"optionExpirationDate"`
	OptionStrikePrice    float64 `json:"optionStrikePrice"`
	PutCall              string  `json:"putCall"`
	CUSIP                string  `json:"cusip"`
	Description          string  `json:"description"`
	AssetType            string  `json:"assetType"`
	BondMaturityDate     string  `json:"bondMaturityDate"`
	BondInterestRate     float64 `json:"bondInterestRate"`
}

TransactionInstrument is the instrumnet traded within a transaction

type TransactionItem

type TransactionItem struct {
	AccountID            int32                 `json:"accountId"`
	Amount               float64               `json:"amount"`
	Price                float64               `json:"price"`
	Cost                 float64               `json:"cost"`
	ParentOrderKey       int32                 `json:"parentOrderKey"`
	ParentChildIndicator string                `json:"parentChildIndicator"`
	Instruction          string                `json:"instruction"`
	PositionEffect       string                `json:"positionEffect"`
	Instrument           TransactionInstrument `json:"instrument"`
}

TransactionItem is an item within a transaction response

type Transactions

type Transactions []*Transaction

Transactions is a slice of transactions

type Underlying

type Underlying struct {
	Symbol            string  `json:"symbol"`
	Description       string  `json:"description"`
	Change            float64 `json:"change"`
	PercentChange     float64 `json:"percentChange"`
	Close             float64 `json:"close"`
	QuoteTime         int     `json:"quoteTime"`
	TradeTime         int     `json:"tradeTime"`
	Bid               float64 `json:"bid"`
	Ask               float64 `json:"ask"`
	Last              float64 `json:"last"`
	Mark              float64 `json:"mark"`
	MarkChange        float64 `json:"markChange"`
	MarkPercentChange float64 `json:"markPercentChange"`
	BidSize           int     `json:"bidSize"`
	AskSize           int     `json:"askSize"`
	HighPrice         float64 `json:"highPrice"`
	LowPrice          float64 `json:"lowPrice"`
	OpenPrice         float64 `json:"openPrice"`
	TotalVolume       int     `json:"totalVolume"`
	ExchangeName      string  `json:"exchangeName"`
	FiftyTwoWeekHigh  float64 `json:"fiftyTwoWeekHigh"`
	FiftyTwoWeekLow   float64 `json:"fiftyTwoWeekLow"`
	Delayed           bool    `json:"delayed"`
}

type UserAccountInfo

type UserAccountInfo struct {
	AccountID         string         `json:"accountId"`
	Description       string         `json:"description"`
	DisplayName       string         `json:"displayName"`
	AccountCdDomainID string         `json:"accountCdDomainId"`
	Company           string         `json:"company"`
	Segment           string         `json:"segment"`
	SurrogateIds      string         `json:"surrogateIds"`
	Preferences       Preferences    `json:"preferences"`
	ACL               string         `json:"acl"`
	Authorizations    Authorizations `json:"authorizations"`
}

type UserPrincipal

type UserPrincipal struct {
	AuthToken                string                   `json:"authToken"`
	UserID                   string                   `json:"userId"`
	UserCdDomainID           string                   `json:"userCdDomainId"`
	PrimaryAccountID         string                   `json:"primaryAccountId"`
	LastLoginTime            string                   `json:"lastLoginTime"`
	TokenExpirationTime      string                   `json:"tokenExpirationTime"`
	LoginTime                string                   `json:"loginTime"`
	AccessLevel              string                   `json:"accessLevel"`
	StalePassword            bool                     `json:"stalePassword"`
	StreamerInfo             StreamerInfo             `json:"streamerInfo"`
	ProfessionalStatus       string                   `json:"professionalStatus"`
	Quotes                   QuoteDelays              `json:"quotes"`
	StreamerSubscriptionKeys StreamerSubscriptionKeys `json:"streamerSubscriptionKeys"`
	Accounts                 []UserAccountInfo        `json:"accounts"`
}

type UserService

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

UserService exposes operations on a user's preferences. See https://developer.tdameritrade.com/user-principal/apis.

func (*UserService) GetPreferences

func (s *UserService) GetPreferences(ctx context.Context, accountID string) (*Preferences, *Response, error)

GetPreferences returns Preferences for a specific account. See https://developer.tdameritrade.com/user-principal/apis/get/accounts/%7BaccountId%7D/preferences-0

func (*UserService) GetStreamerSubscriptionKeys

func (s *UserService) GetStreamerSubscriptionKeys(ctx context.Context, accountIDs ...string) (*StreamerSubscriptionKeys, *Response, error)

GetStreamerSubscriptionKeys returns Subscription Keys for provided accounts or default accounts. See https://developer.tdameritrade.com/user-principal/apis/get/userprincipals/streamersubscriptionkeys-0

func (*UserService) GetUserPrincipals

func (s *UserService) GetUserPrincipals(ctx context.Context, fields ...string) (*UserPrincipal, *Response, error)

GetUserPrincipals returns User Principal details. Valid values for `fields` are "streamerSubscriptionKeys", "streamerConnectionInfo", "preferences" and "surrogateIds" See https://developer.tdameritrade.com/user-principal/apis/get/userprincipals-0

func (*UserService) UpdatePreferences

func (s *UserService) UpdatePreferences(ctx context.Context, accountID string, newPreferences *Preferences) (*Response, error)

UpdatePreferences updates Preferences for a specific account. Please note that the directOptionsRouting and directEquityRouting values cannot be modified via this operation, even though they are in the request body. See https://developer.tdameritrade.com/user-principal/apis/put/accounts/%7BaccountId%7D/preferences-0

type WatchlistInstrument

type WatchlistInstrument struct {
	Symbol    string `json:"symbol"`
	AssetType string `json:"assetType"`
}

WatchlistInstrument is the specific information about the security being added to the watchlist.

type WatchlistItem

type WatchlistItem struct {
	Quantity      int                 `json:"quantity"`
	AveragePrice  int                 `json:"averagePrice"`
	Commission    int                 `json:"commission"`
	PurchasedDate string              `json:"purchasedDate"`
	Instrument    WatchlistInstrument `json:"instrument"`
}

WatchlistItem is a security to be added to a NewWatchlist.

type WatchlistService

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

WatchlistService allows CRUD operations on watchlists in a user's account. See https://developer.tdameritrade.com/watchlist/apis.

func (*WatchlistService) CreateWatchlist

func (s *WatchlistService) CreateWatchlist(ctx context.Context, accountID string, newWatchlist *NewWatchlist) (*Response, error)

CreateWatchlist adds a new watchlist to a user's account See https://developer.tdameritrade.com/watchlist/apis/post/accounts/%7BaccountId%7D/watchlists-0

func (*WatchlistService) DeleteWatchlist

func (s *WatchlistService) DeleteWatchlist(ctx context.Context, accountID, watchlistID string) (*Response, error)

DeleteWatchlist removes a watchlist from a user's account See https://developer.tdameritrade.com/watchlist/apis/delete/accounts/%7BaccountId%7D/watchlists/%7BwatchlistId%7D-0

func (*WatchlistService) GetAllWatchlists

func (s *WatchlistService) GetAllWatchlists(ctx context.Context) (*[]StoredWatchlist, *Response, error)

GetAllWatchlists returns all watchlists for all of a user's linked accounts. See https://developer.tdameritrade.com/watchlist/apis/get/accounts/watchlists-0

func (*WatchlistService) GetAllWatchlistsForAccount

func (s *WatchlistService) GetAllWatchlistsForAccount(ctx context.Context, accountID string) (*[]StoredWatchlist, *Response, error)

GetAllWatchlistsForAccount returns all watchlists for a single user account. See https://developer.tdameritrade.com/watchlist/apis/get/accounts/%7BaccountId%7D/watchlists-0

func (*WatchlistService) GetWatchlist

func (s *WatchlistService) GetWatchlist(ctx context.Context, accountID, watchlistID string) (*StoredWatchlist, *Response, error)

GetWatchlist returns a single watchlist in a user's account See https://developer.tdameritrade.com/watchlist/apis/get/accounts/%7BaccountId%7D/watchlists/%7BwatchlistId%7D-0

func (*WatchlistService) ReplaceWatchlist

func (s *WatchlistService) ReplaceWatchlist(ctx context.Context, accountID, watchlistID string, newWatchlist *NewWatchlist) (*Response, error)

ReplaceWatchlist replaces a watchlist in an account with a new watchlist. It does not verify that symbols are valid. See https://developer.tdameritrade.com/watchlist/apis/put/accounts/%7BaccountId%7D/watchlists/%7BwatchlistId%7D-0

func (*WatchlistService) UpdateWatchlist

func (s *WatchlistService) UpdateWatchlist(ctx context.Context, accountID, watchlistID string, newWatchlist *NewWatchlist) (*Response, error)

UpdateWatchlist partially updates watchlist for a specific account. Callers can:

  • change the watchlist's name
  • add to the beginning/end of a watchlist
  • update or delete items in a watchlist

This method does not verify that the symbol or asset type are valid. See https://developer.tdameritrade.com/watchlist/apis/patch/accounts/%7BaccountId%7D/watchlists/%7BwatchlistId%7D-0

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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