Documentation
¶
Overview ¶
Package tda 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 ¶
- Variables
- func ConvertToEpoch(t time.Time) int64
- func PrintRequest(r *http.Request) string
- type Account
- type AccountOptions
- type Accounts
- type AccountsService
- func (s *AccountsService) CancelOrder(ctx context.Context, accountID, orderID string) (*Response, error)
- func (s *AccountsService) CreateSavedOrder(ctx context.Context, accountID string, order *Order) (*Response, error)
- func (s *AccountsService) DeleteSavedOrder(ctx context.Context, accountID, savedOrderID string) (*Response, error)
- func (s *AccountsService) GetAccount(ctx context.Context, accountID string, opts *AccountOptions) (*Account, *Response, error)
- func (s *AccountsService) GetAccounts(ctx context.Context, opts *AccountOptions) (*Accounts, *Response, error)
- func (s *AccountsService) GetOrder(ctx context.Context, accountID, orderID string) (*Response, error)
- func (s *AccountsService) GetOrderByPath(ctx context.Context, accountID string, orderParams *OrderParams) (*Response, error)
- func (s *AccountsService) GetOrdersByQuery(ctx context.Context, orderParams *OrderParams) (*Orders, *Response, error)
- func (s *AccountsService) GetSavedOrder(ctx context.Context, accountID, savedOrderID string, orderParams *OrderParams) (*Response, error)
- func (s *AccountsService) PlaceOrder(ctx context.Context, accountID string, order Order) (*Response, error)
- func (s *AccountsService) ReplaceOrder(ctx context.Context, accountID string, orderID string, order *Order) (*Response, error)
- func (s *AccountsService) ReplaceSavedOrder(ctx context.Context, accountID, savedOrderID string, order *Order) (*Response, error)
- type Authenticator
- func (a *Authenticator) AuthenticatedClient(ctx context.Context, req *http.Request) (*Client, error)
- func (a *Authenticator) FinishOAuth2Flow(ctx context.Context, w http.ResponseWriter, req *http.Request) (*Client, error)
- func (a *Authenticator) StartOAuth2Flow(w http.ResponseWriter, req *http.Request) (string, error)
- type Authorizations
- type Balance
- type CancelTime
- type Chains
- type ChainsService
- type Client
- type Command
- type Equity
- type Execution
- type ExecutionLeg
- type ExpDateMap
- type ExpDateOption
- type Float64WithSpecial
- type Hours
- type Instrument
- type InstrumentInfo
- type InstrumentService
- type Instruments
- type KeyEntry
- type MarketHours
- type MarketHoursService
- type Mover
- type MoverOptions
- type MoverService
- type NewWatchlist
- type Option
- type OptionDeliverable
- type Order
- type OrderLegCollection
- type OrderParams
- type Orders
- type Period
- type PersistentStore
- type Preferences
- type PriceHistory
- type PriceHistoryOptions
- type PriceHistoryService
- type Quote
- type QuoteDelays
- type Quotes
- type QuotesService
- type Response
- type SecuritiesAccount
- type SessionHours
- type StoredWatchlist
- type StoredWatchlistInstrument
- type StoredWatchlistItem
- type StreamAuthCommand
- type StreamAuthParams
- type StreamAuthRequest
- type StreamAuthResponse
- type StreamAuthResponseBody
- type StreamAuthResponseContent
- type StreamParams
- type StreamRequest
- type StreamerInfo
- type StreamerSubscriptionKeys
- type StreamingClient
- func (s *StreamingClient) Authenticate(authCmd *StreamAuthCommand) error
- func (s *StreamingClient) Close() error
- func (s *StreamingClient) ReceiveText() (<-chan []byte, <-chan error)
- func (s *StreamingClient) SendCommand(command Command) error
- func (s *StreamingClient) SendText(payload []byte) error
- type Transaction
- type TransactionFees
- type TransactionHistoryOptions
- type TransactionHistoryService
- func (s *TransactionHistoryService) GetTransaction(ctx context.Context, accountID string, transactionID string) (*Transaction, *Response, error)
- func (s *TransactionHistoryService) GetTransactions(ctx context.Context, accountID string, opts *TransactionHistoryOptions) (*Transactions, *Response, error)
- type TransactionInstrument
- type TransactionItem
- type Transactions
- type Underlying
- type UserAccountInfo
- type UserPrincipal
- type UserService
- func (s *UserService) GetPreferences(ctx context.Context, accountID string) (*Preferences, *Response, error)
- func (s *UserService) GetStreamerSubscriptionKeys(ctx context.Context, accountIDs ...string) (*StreamerSubscriptionKeys, *Response, error)
- func (s *UserService) GetUserPrincipals(ctx context.Context, fields ...string) (*UserPrincipal, *Response, error)
- func (s *UserService) UpdatePreferences(ctx context.Context, accountID string, newPreferences *Preferences) (*Response, error)
- type WatchlistInstrument
- type WatchlistItem
- type WatchlistService
- func (s *WatchlistService) CreateWatchlist(ctx context.Context, accountID string, newWatchlist *NewWatchlist) (*Response, error)
- func (s *WatchlistService) DeleteWatchlist(ctx context.Context, accountID, watchlistID string) (*Response, error)
- func (s *WatchlistService) GetAllWatchlists(ctx context.Context) (*[]StoredWatchlist, *Response, error)
- func (s *WatchlistService) GetAllWatchlistsForAccount(ctx context.Context, accountID string) (*[]StoredWatchlist, *Response, error)
- func (s *WatchlistService) GetWatchlist(ctx context.Context, accountID, watchlistID string) (*StoredWatchlist, *Response, error)
- func (s *WatchlistService) ReplaceWatchlist(ctx context.Context, accountID, watchlistID string, newWatchlist *NewWatchlist) (*Response, error)
- func (s *WatchlistService) UpdateWatchlist(ctx context.Context, accountID, watchlistID string, newWatchlist *NewWatchlist) (*Response, error)
Constants ¶
This section is empty.
Variables ¶
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") )
var ( ChangeTypes = []string{"value", "percent"} DirectionTypes = []string{"up", "down"} )
Functions ¶
func ConvertToEpoch ¶
func PrintRequest ¶
Utility for printing out requests for debugging.
Types ¶
type Account ¶
type Account struct {
SecuritiesAccount `json:"securitiesAccount"`
}
type AccountOptions ¶
type AccountsService ¶
type AccountsService struct {
// contains filtered or unexported fields
}
AccountsService handles communication with the account related methods of the tda API.
tda API docs: https://developer.tda.com/account-access/apis
func (*AccountsService) CancelOrder ¶
func (*AccountsService) CreateSavedOrder ¶
func (*AccountsService) DeleteSavedOrder ¶
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) GetOrderByPath ¶
func (s *AccountsService) GetOrderByPath(ctx context.Context, accountID string, orderParams *OrderParams) (*Response, error)
func (*AccountsService) GetOrdersByQuery ¶
func (s *AccountsService) GetOrdersByQuery(ctx context.Context, orderParams *OrderParams) (*Orders, *Response, error)
func (*AccountsService) GetSavedOrder ¶
func (s *AccountsService) GetSavedOrder(ctx context.Context, accountID, savedOrderID string, orderParams *OrderParams) (*Response, error)
func (*AccountsService) PlaceOrder ¶
func (*AccountsService) ReplaceOrder ¶
func (*AccountsService) ReplaceSavedOrder ¶
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.tda.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 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 tda API.
tda API docs: https://developer.tda.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.tda.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 tda 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 ¶
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) NewRequest ¶
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 ¶
type Command ¶
type Command struct {
Requests []StreamRequest `json:"requests"`
}
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 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 Float64WithSpecial `json:"volatility"` Delta Float64WithSpecial `json:"delta"` Gamma Float64WithSpecial `json:"gamma"` Theta Float64WithSpecial `json:"theta"` Vega Float64WithSpecial `json:"vega"` Rho Float64WithSpecial `json:"rho"` OpenInterest int `json:"openInterest"` TimeValue float64 `json:"timeValue"` TheoreticalOptionValue Float64WithSpecial `json:"theoreticalOptionValue"` TheoreticalVolatility Float64WithSpecial `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 Float64WithSpecial ¶
type Float64WithSpecial float64
a float64 whose JSON unmarshaller supports NaN and Inf
func (Float64WithSpecial) MarshalJSON ¶
func (v Float64WithSpecial) MarshalJSON() ([]byte, error)
func (*Float64WithSpecial) UnmarshalJSON ¶
func (v *Float64WithSpecial) UnmarshalJSON(b []byte) error
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 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 tda API.
tda API docs: https://developer.tda.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 MarketHours ¶
type MarketHoursService ¶
type MarketHoursService struct {
// contains filtered or unexported fields
}
MarketHoursService handles communication with the marketdata related methods of the tda API.
tda API docs: https://developer.tda.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 MoverOptions ¶
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 NewWatchlist ¶
type NewWatchlist struct { Name string `json:"name"` WatchlistItems []WatchlistItem `json:"watchlistItems"` }
NewWatchlist is a watchlist to be created by a user.
type Option ¶
type Option 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 Order ¶
type Order struct { Session string `json:"session"` Duration string `json:"duration"` OrderType string `json:"orderType"` CancelTime string `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"` }
However, the actual response is simply a string: YYYY-MM-DD This will only apply to orders that are a limit order where the expiry is set.
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 float64 `json:"quantity"` QuantityType string `json:"quantityType,omitempty"` }
type OrderParams ¶
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 PriceHistoryOptions ¶
type PriceHistoryOptions struct { PeriodType string `url:"periodType,omitempty"` Period int `url:"period,omitempty"` FrequencyType string `url:"frequencyType,omitempty"` Frequency int `url:"frequency,omitempty"` EndDate int64 `url:"endDate,omitempty"` StartDate int64 `url:"startDate,omitempty"` NeedExtendedHoursData *bool `url:"needExtendedHoursData"` }
PriceHistoryOptions is parsed and translated to query options in the https request cannot use time.Time in StartDate and EndDate. Date must be Epoch time. Use new function ConvertToEpoch() which returns an int64. This is per the documentation from TD AMERITRADE. also, omitempty must be set because if you set a start and end date, you cannot send the "period" value or it will error.
type PriceHistoryService ¶
type PriceHistoryService struct {
// contains filtered or unexported fields
}
PriceHistoryService handles communication with the marketdata related methods of the tda API.
tda API docs: https://developer.tda.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 tda API Docs: https://developer.tda.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 QuotesService ¶
type QuotesService struct {
// contains filtered or unexported fields
}
QuotesService handles communication with the marketdata related methods of the tda API.
tda API docs: https://developer.tda.com/quotes/apis
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 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 StreamAuthCommand ¶
type StreamAuthCommand struct {
Requests []StreamAuthRequest `json:"requests"`
}
func NewStreamAuthCommand ¶
func NewStreamAuthCommand(userPrincipal *UserPrincipal, accountID string) (*StreamAuthCommand, error)
NewStreamAuthCommand creates a StreamAuthCommand from a TD Ameritrade UserPrincipal. It validates the account ID against the accounts in the UserPrincipal to avoid creating invalid messages unneccesarily.
type StreamAuthParams ¶
type StreamAuthRequest ¶
type StreamAuthResponse ¶
type StreamAuthResponse struct {
Response []StreamAuthResponseBody `json:"response"`
}
type StreamAuthResponseBody ¶
type StreamAuthResponseBody struct { Service string `json:"service"` Requestid string `json:"requestid"` Command string `json:"command"` Timestamp int64 `json:"timestamp"` Content StreamAuthResponseContent `json:"content"` }
type StreamParams ¶
type StreamRequest ¶
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 StreamingClient ¶
type StreamingClient struct {
// contains filtered or unexported fields
}
StreamingClient provides real time updates from TD Ameritrade's streaming API. See https://developer.tda.com/content/streaming-data for more information.
func NewAuthenticatedStreamingClient ¶
func NewAuthenticatedStreamingClient(userPrincipal *UserPrincipal, accountID string) (*StreamingClient, error)
NewAuthenticatedStreamingClient returns a client that will pull live updates for a TD Ameritrade account. It sends an initial authentication message to TD Ameritrade and waits for a response before returning. Use NewUnauthenticatedStreamingClient if you want to handle authentication yourself. You'll need to Close a StreamingClient to free up the underlying resources.
func NewUnauthenticatedStreamingClient ¶
func NewUnauthenticatedStreamingClient(userPrincipal *UserPrincipal) (*StreamingClient, error)
NewUnauthenticatedStreamingClient returns an unauthenticated streaming client that has a connection to the TD Ameritrade websocket. You can get an authenticated streaming client with NewAuthenticatedStreamingClient. To authenticate manually, send a JSON serialized StreamAuthCommand message with the StreamingClient's Authenticate method. You'll need to Close a streaming client to free up the underlying resources.
func (*StreamingClient) Authenticate ¶
func (s *StreamingClient) Authenticate(authCmd *StreamAuthCommand) error
func (*StreamingClient) Close ¶
func (s *StreamingClient) Close() error
Close closes the underlying websocket connection.
func (*StreamingClient) ReceiveText ¶
func (s *StreamingClient) ReceiveText() (<-chan []byte, <-chan error)
ReceiveText returns read-only channels with the raw byte responses from TD Ameritrade and errors generated while streaming. Callers should select over both of these channels to avoid blocking one. Callers are able to handle errors how thes see fit. All errors will be from Gorilla's websocket library and implement the net.Error interface.
func (*StreamingClient) SendCommand ¶
func (s *StreamingClient) SendCommand(command Command) error
SendCommand serializes and sends a Command struct to TD Ameritrade. It is a wrapper around SendText.
func (*StreamingClient) SendText ¶
func (s *StreamingClient) SendText(payload []byte) error
SendText sends a byte payload to TD Ameritrade's websocket. TD Ameritrade commands are JSON encoded payloads. You should generally be using SendCommand to send commands to TD Ameritrade.
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 tda API.
tda API docs: https://developer.tda.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 tda API Docs: https://developer.tda.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 tda API Docs: https://developer.tda.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 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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.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.tda.com/watchlist/apis/patch/accounts/%7BaccountId%7D/watchlists/%7BwatchlistId%7D-0