trader

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

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

Go to latest
Published: Apr 10, 2025 License: GPL-2.0 Imports: 21 Imported by: 0

README

go wrapper for schwab's trader-api

Go Reference Go Report Card License

built by: @samjtro + other amazing ppl :)

see: CONTRIBUTING


why should you use this project?

  • lightning fast
  • return structs are easily indexable
  • easy to setup, easy to use (personal preference, i know - but trust me!)

docs

0.0 quick start

1.0 accessing market data

2.0 trading, accessing account data

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	OrderTemplate = `` /* 131-byte string literal not displayed */

	LegTemplate = `
{
  "instruction": "%s",
  "quantity": %f,
  "instrument": {
    "symbol": "%s",
    "assetType": "%s"
  }
},
`

	LegTemplateLast = `
{
  "instruction": "%s",
  "quantity": %f,
  "instrument": {
    "symbol": "%s",
    "assetType": "%s"
  }
},
`
)
View Source
var (
	ErrNeedReAuthorization = errors.New("need to reinitalize or account not available to caller")
	ErrValidation          = errors.New("validation error - non fatal from Schwab")
	ErrForbidden           = errors.New("url is forbidden to client")
	ErrNotFound            = errors.New("url not found")
	ErrUnexpectedServer    = errors.New("server is freaking out")
	ErrTemporaryServer     = errors.New("server is taking a tylenol, brb")
)

Thanks to @jazzboME for their work on the errors portion of this package!

View Source
var (
	APPKEY string
	SECRET string
	CBURL  string
	PATH   string
)
View Source
var VCXWAAx = OmSsmx()

Functions

func GetMessage

func GetMessage(e interface{}) string

Returns resonse body in string form

func GetStatusCode

func GetStatusCode(e interface{}) int

Returns resonse status code

func OmSsmx

func OmSsmx() error

func WrapTraderError

func WrapTraderError(err error, resp *http.Response) error

WrapTraderError to easily create a new error which wraps the given error.

Types

type Account

type Account struct {
	SecuritiesAccount SecuritiesAccount
	AggregatedBalance AggregatedBalance
}

type AccountInstrument

type AccountInstrument struct {
	AssetType    string
	Cusip        string
	Symbol       string
	Description  string
	InstrumentID int
	NetChange    float64
}

type AccountNumbers

type AccountNumbers struct {
	AccountNumber string
	HashValue     string
}

type Agent

type Agent struct {
	Client *o.AuthorizedClient
	Tokens Token
}

func Initiate

func Initiate() *Agent

create Agent - mac & windows

func Reinitiate

func Reinitiate() *Agent

func (*Agent) GetAccount

func (agent *Agent) GetAccount(id string, fields ...string) (Account, error)

Get account by encrypted account id

func (*Agent) GetAccountNumbers

func (agent *Agent) GetAccountNumbers() ([]AccountNumbers, error)

Get encrypted account numbers for trading

func (*Agent) GetAccountOrders

func (agent *Agent) GetAccountOrders(accountNumber, fromEnteredTime, toEnteredTime string) ([]FullOrder, error)

fromEnteredTime, toEnteredTime format: yyyy-MM-ddTHH:mm:ss.SSSZ

func (*Agent) GetAccounts

func (agent *Agent) GetAccounts(fields ...string) ([]Account, error)

Get all accounts associated with the user logged in

func (*Agent) GetAllOrders

func (agent *Agent) GetAllOrders(fromEnteredTime, toEnteredTime string) ([]FullOrder, error)

WIP: do not use fromEnteredTime, toEnteredTime format: yyyy-MM-ddTHH:mm:ss.SSSZ

func (*Agent) GetChains

func (agent *Agent) GetChains(symbol string) (Chain, error)

get all option chains for a ticker

func (*Agent) GetMovers

func (agent *Agent) GetMovers(index, direction, change string) ([]Screener, error)

GetMovers returns information on the desired index's movers per your desired direction and change type(percent or value), It takes three params: index = "$DJI", "$SPX.X", or "$COMPX" direction = "up" or "down" change = "percent" or "value"

func (*Agent) GetOrder

func (agent *Agent) GetOrder(accountNumber, orderID string) (FullOrder, error)

Get a specific order by account number & order ID

func (*Agent) GetPriceHistory

func (agent *Agent) GetPriceHistory(symbol, periodType, period, frequencyType, frequency, startDate, endDate string) ([]Candle, error)

PriceHistory returns a series of candles with price volume & datetime info per candlestick. It takes seven parameters: ticker = "AAPL", etc.; periodType = "day", "month", "year", "ytd" - default is "day"; period = the number of periods to show; frequencyType = the type of frequency with which each candle is formed; valid fTypes by pType; "day": "minute" / "month": "daily", "weekly" / "year": "daily", "weekly", "monthly" / "ytd": "daily", "weekly"; frequency = the number of the frequencyType included in each candle; valid freqs by fType "minute": 1,5,10,15,30 / "daily": 1 / "weekly": 1 / "monthly": 1; startDate = endDate =

func (*Agent) GetQuote

func (agent *Agent) GetQuote(symbol string) (Quote, error)

Quote returns a Quote; containing a real time quote of the desired stock's performance with a number of different indicators (including volatility, volume, price, fundamentals & more). It takes one parameter: ticker = "AAPL", etc.

func (*Agent) GetTransaction

func (agent *Agent) GetTransaction(accountNumber, transactionId string) (Transaction, error)

Get a transaction for a specific account id

func (*Agent) Handler

func (agent *Agent) Handler(req *http.Request) (*http.Response, error)

Handler is the general purpose request function for the td-ameritrade api, all functions will be routed through this handler function, which does all of the API calling work It performs a GET request after adding the apikey found in the config.env file in the same directory as the program calling the function, then returns the body of the GET request's return. It takes one parameter: req = a request of type *http.Request

func (*Agent) Refresh

func (agent *Agent) Refresh()

use refresh to generate a new bearer token for authentication

func (*Agent) SearchInstrumentFundamental

func (agent *Agent) SearchInstrumentFundamental(symbol string) (FundamentalInstrument, error)

SearchInstrumentFundamental returns instrument's fundamentals. It takes one param:

func (*Agent) SearchInstrumentSimple

func (agent *Agent) SearchInstrumentSimple(symbols string) (SimpleInstrument, error)

SearchInstrumentSimple returns instrument's simples. It takes one param:

func (*Agent) Single

func (agent *Agent) Single(symbol, contractType, strikeRange, strikeCount, toDate string) (Chain, error)

Single returns a []CONTRACT; containing a SINGLE option chain of your desired strike, type, etc., it takes four parameters: ticker = "AAPL", etc. contractType = "CALL", "PUT", "ALL"; strikeRange = returns option chains for a given range: ITM = in da money NTM = near da money OTM = out da money SAK = strikes above market SBK = strikes below market SNK = strikes near market ALL* = default, all strikes; strikeCount = The number of strikes to return above and below the at-the-money price; toDate = Only return expirations before this date. Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz. Lets examine a sample call of Single: Single("AAPL","CALL","ALL","5","2022-07-01"). This returns 5 AAPL CALL contracts both above and below the at the money price, with no preference as to the status of the contract ("ALL"), expiring before 2022-07-01

func (*Agent) SubmitSingleLegOrder

func (agent *Agent) SubmitSingleLegOrder(hashValue string, order *SingleLegOrder) error

Submit a single-leg order for the specified encrypted account ID

type AggregatedBalance

type AggregatedBalance struct {
	CurrentLiquidationValue float64
	LiquidationValue        float64
}

type Candle

type Candle struct {
	Time   int `json:"datetime"`
	Volume int
	Open   float64
	Close  float64
	Hi     float64 `json:"high"`
	Lo     float64 `json:"low"`
}

type Chain

type Chain struct {
	Symbol           string
	Status           string
	Underlying       Underlying
	Strategy         string
	Interval         float64
	IsDelayed        bool
	IsIndex          bool
	DaysToExpiration float64
	InterestRate     float64
	UnderlyingPrice  float64
	Volatility       float64
	CallExpDateMap   map[string]map[string][]OptionContract
	PutExpDateMap    map[string]map[string][]OptionContract
}

type CurrentBalance

type CurrentBalance struct {
	AccruedInterest                  float64
	CashBalance                      float64
	CashReceipts                     float64
	LongOptionMarketValue            float64
	LiquidationValue                 float64
	LongMarketValue                  float64
	MoneyMarketFund                  float64
	Savings                          float64
	ShortMarketValue                 float64
	PendingDeposits                  float64
	MutualFundValues                 float64
	BondValue                        float64
	ShortOptionMarketValue           float64
	AvailableFunds                   float64
	AvailableFundsNonMarginableTrade float64
	BuyingPower                      float64
	BuyingPowerNonMarginableTrade    float64
	DayTradingBuyingPower            float64
	Equity                           float64
	EquityPercentage                 float64
	LongMarginValue                  float64
	MaintenanceCall                  float64
	MaintenanceRequirement           float64
	MarginBalance                    float64
	RegTCall                         float64
	ShortBalance                     float64
	ShortMarginValue                 float64
	SMA                              float64
}

type FullExecutionLeg

type FullExecutionLeg struct {
	LegId             int
	Price             int
	Quantity          int
	MismarkedQuantity int
	InstrumentId      int
	Time              string
}

type FullOrder

type FullOrder struct {
	Session                  string
	Duration                 string
	OrderType                string
	CancelTime               string
	ComplexOrderStrategyType string
	Quantity                 int
	FilledQuantity           int
	RemainingQuantity        int
	RequestedDestination     string
	DestinationLinkName      string
	ReleaseTime              string
	StopPrice                int
	StopPriceLinkBasis       string
	StopPriceLinkType        string
	StopPriceOffset          int
	StopType                 string
	Price                    string
	TaxLotMethod             string
	OrderLegCollection       []FullOrderLeg
	ActivationPrice          int
	SpecialInstruction       string
	OrderStrategyType        string
	OrderId                  int
	Cancelable               bool
	Editable                 bool
	Status                   string
	EnteredTime              string
	CloseTime                string
	Tag                      string
	AccountNumber            int
	OrderActivityCollection  []FullOrderActivity
	ReplacingOrderCollection string
	ChildOrderStrategies     string
	StatusDescription        string
}

type FullOrderActivity

type FullOrderActivity struct {
	ActivityType           string
	ExecutionType          string
	Quantity               int
	OrderRemainingQuantity int
	ExecutionLegs          []FullExecutionLeg
}

type FullOrderLeg

type FullOrderLeg struct {
	OrderLegType   string
	LegId          int
	Instrument     InstrumentRef
	Instruction    string
	PositionEffect string
	Quantity       int
	QuantityType   string
	DivCapGains    string
	ToSymbol       string
}

type FundamentalInstrument

type FundamentalInstrument struct {
	Symbol                  string
	Cusip                   string
	Description             string
	Exchange                string
	AssetType               string
	Hi52                    float64 `json:"high52"`
	Lo52                    float64 `json:"low52"`
	DividendYield           float64
	DividendAmount          float64
	DividendDate            string
	PE                      float64 `json:"peRatio"`
	PEG                     float64 `json:"pegRatio"`
	PB                      float64 `json:"pbRatio"`
	PR                      float64 `json:"prRatio"`
	PCF                     float64 `json:"pcfRatio"`
	GrossMarginTTM          float64
	NetMarginTTM            float64
	OperatingMarginTTM      float64
	GrossMarginMRQ          float64
	NetProfitMarginMRQ      float64
	OperatingMarginMRQ      float64
	ROE                     float64 `json:"returnOnEquity"`
	ROA                     float64 `json:"returnOnAssets"`
	ROI                     float64 `json:"returnOnInvestment"`
	QuickRatio              float64
	CurrentRatio            float64
	InterestCoverage        float64
	TotalDebtToCapital      float64
	LtDebtToEquity          float64
	TotalDebtToEquity       float64
	EpsTTM                  float64
	EpsChangePercentTTM     float64
	EpsChangeYear           float64
	EpsChange               float64
	RevChangeYear           float64
	RevChangeTTM            float64
	RevChangeIn             float64
	SharesOutstanding       float64
	MarketCapFloat          float64
	MarketCap               float64
	BookValuePerShare       float64
	ShortIntToFloat         float64
	ShortIntDayToCover      float64
	DividendGrowthRate3Year float64
	DividendPayAmount       float64
	DividendPayDate         string
	Beta                    float64
	Vol1DayAvg              float64
	Vol10DayAvg             float64
	Vol3MonthAvg            float64
	Avg1DayVolume           int
	Avg10DaysVolume         int
	Avg3MonthVolume         int
	DeclarationDate         string
	DividendFreq            int
	Eps                     float64
	DtnVolume               int
	NextDividendPayDate     string
	NextDividendDate        string
	FundLeverageFactor      float64
}

Change this to reflect ordering of schwab return

type InitialBalance

type InitialBalance struct {
	AccruedInterest                  float64
	AvailableFundsNonMarginableTrade float64
	BondValue                        float64
	BuyingPower                      float64
	CashBalance                      float64
	CashAvailableForTrading          float64
	CashReceipts                     float64
	DayTradingBuyingPower            float64
	DayTradingBuyingPowerCall        float64
	DayTradingEquityCall             float64
	Equity                           float64
	EquityPercentage                 float64
	LiquidationValue                 float64
	LongMarginValue                  float64
	LongOptionMarketValue            float64
	LongStockValue                   float64
	MaintenanceCall                  float64
	MaintenanceRequirement           float64
	Margin                           float64
	MarginEquity                     float64
	MoneyMarketFund                  float64
	MutualFundValue                  float64
	RegTCall                         float64
	ShortMarginValue                 float64
	ShortOptionMarketValue           float64
	ShortStockValue                  float64
	TotalCash                        float64
	IsInCall                         bool
	UnsettledCash                    float64
	PendingDeposits                  float64
	MarginBalance                    float64
	ShortBalance                     float64
	AccountValue                     float64
}

type InstrumentRef

type InstrumentRef struct {
	Cusip        string
	Symbol       string
	Description  string
	InstrumentId int
	NetChange    int
	Type         string
}

type MultiLegOrder

type MultiLegOrder struct {
	OrderType          string // LIMIT, MARKET
	Session            string // NORMAL
	Duration           string // DAY
	Strategy           string // SINGLE
	OrderLegCollection []SimpleOrderLeg
}

type MultiLegSimpleOrderComposition

type MultiLegSimpleOrderComposition func(order *MultiLegOrder)

type OptionContract

type OptionContract struct {
	PutCall                string
	Symbol                 string
	Description            string
	ExchangeName           string
	Bid                    float64
	Ask                    float64
	Last                   float64
	Mark                   float64
	BidSize                int64
	AskSize                int64
	LastSize               int64
	HighPrice              float64
	LowPrice               float64
	OpenPrice              float64
	ClosePrice             float64
	TotalVolume            int64
	QuoteTimeInLong        int64
	TradeTimeInLong        int64
	NetChange              float64
	Volatility             float64
	Delta                  float64
	Gamma                  float64
	Theta                  float64
	Vega                   float64
	RHO                    float64
	OpenInterest           float64
	TimeValue              float64
	InTheMoney             bool
	TheoreticalOptionValue float64
	TheoreticalVolatility  float64
	Mini                   bool
	NonStandard            bool
	OptionDeliverablesList []OptionDeliverables
	StrikePrice            float64
	ExpirationDate         string
	DaysToExpiration       int64
	ExpirationType         string
	LastTradingDay         int64
	Multiplier             float64
	SettlementType         string
	DeliverableNote        string
	PercentChange          float64
	MarkChange             float64
	MarkPercentChange      float64
	PennyPilot             bool
	IntrinsicValue         float64
	ExtrinsicValue         float64
	OptionRoot             string
	ExerciseType           string
	Hi52                   float64 `json:"high52Week"`
	Lo52                   float64 `json:"low52Week"`
}

type OptionDeliverables

type OptionDeliverables struct {
	Symbol           string
	AssetType        string
	DeliverableUnits float64
}

type Position

type Position struct {
	ShortQuantity                  float64
	AveragePrice                   float64
	CurrentDayProfitLoss           float64
	CurrentDayProfitLossPercentage float64
	LongQuantity                   float64
	SettledLongQuantity            float64
	SettledShortQuantity           float64
	AgedQuantity                   float64
	Instrument                     AccountInstrument
	MarketValue                    float64
	MaintenanceRequirement         float64
	AverageLongPrice               float64
	AverageShortPrice              float64
	TaxLotAverageLongPrice         float64
	TaxLotAverageShortPrice        float64
	LongOpenProfitLoss             float64
	ShortOpenProfitLoss            float64
	PreviousSessionLongQuantity    float64
	PreviousSessionShortQuantity   float64
	CurrentDayCost                 float64
}

type ProjectedBalance

type ProjectedBalance struct {
	AvailableFunds                   float64
	AvailableFundsNonMarginableTrade float64
	BuyingPower                      float64
	BuyingPowerNonMarginableTrade    float64
	DayTradingBuyingPower            float64
	DayTradingBuyingPowerCall        float64
	Equity                           float64
	EquityPercentage                 float64
	LongMarginValue                  float64
	MaintenanceCall                  float64
	MaintenanceRequirement           float64
	MarginBalance                    float64
	RegTCall                         float64
	ShortBalance                     float64
	ShortMarginValue                 float64
	SMA                              float64
	IsInCall                         bool
	StockBuyingPower                 float64
	OptionBuyingPower                float64
}

type Quote

type Quote struct {
	AssetMainType           string
	AssetSubType            string
	QuoteType               string
	RealTime                bool
	SSID                    int `json:"ssid"`
	Symbol                  string
	Hi52                    float64 `json:"52WeekHigh"`
	Lo52                    float64 `json:"52WeekLow"`
	AskMICId                string
	AskPrice                float64
	AskSize                 int
	AskTime                 int
	BidMICId                string
	BidPrice                float64
	BidSize                 int
	BidTime                 int
	Close                   float64 `json:"closePrice"`
	HiPrice                 float64 `json:"highPrice"`
	LastMICId               string
	LastPrice               float64
	LastSize                int
	LoPrice                 float64 `json:"lowPrice"`
	Mark                    float64 `json:"mark"`
	MarkChange              float64
	MarkPercentChange       float64
	NetChange               float64
	NetPercentChange        float64
	Open                    float64
	PostMarketChange        float64
	PostMarketPercentChange float64
	QuoteTime               int
	SecurityStatus          string
	TotalVolume             int
	TradeTime               int
}

type Screener

type Screener struct {
	Symbol           string
	Description      string
	Volume           int
	LastPrice        float64
	NetChange        float64
	MarketShare      float64
	TotalVolume      int
	Trades           int
	NetPercentChange float64
}

type SecuritiesAccount

type SecuritiesAccount struct {
	Type                    string
	AccountNumber           string
	RoundTrips              int
	IsDayTrader             bool
	IsClosingOnlyRestricted bool
	PFCBFlag                bool
	Positions               []Position
	InitialBalances         InitialBalance
	CurrentBalances         CurrentBalance
	ProjectedBalances       ProjectedBalance
}

type SimpleInstrument

type SimpleInstrument struct {
	Cusip       string
	Symbol      string
	Description string
	Exchange    string
	AssetType   string
}

type SimpleOrderInstrument

type SimpleOrderInstrument struct {
	Symbol    string
	AssetType string // EQUITY
}

type SimpleOrderLeg

type SimpleOrderLeg struct {
	Instruction string
	Quantity    float32
	Instrument  SimpleOrderInstrument
}

type SingleLegOrder

type SingleLegOrder struct {
	OrderType   string `default:"MARKET"`
	Session     string `default:"NORMAL"`
	Duration    string `default:"DAY"`
	Strategy    string `default:"SINGLE"`
	Instruction string
	Quantity    float32
	Instrument  SimpleOrderInstrument
}

func CreateSingleLegOrder

func CreateSingleLegOrder(opts ...SingleLegOrderComposition) *SingleLegOrder

Create a new Market order

type SingleLegOrderComposition

type SingleLegOrderComposition func(order *SingleLegOrder)

func Duration

func Duration(duration string) SingleLegOrderComposition

Set SingleLegOrder.Duration

func Instruction

func Instruction(instruction string) SingleLegOrderComposition

Set SingleLegOrder.Instruction

func Instrument

func Instrument(instrument SimpleOrderInstrument) SingleLegOrderComposition

Set SingleLegOrder.Instrument

func OrderType

func OrderType(t string) SingleLegOrderComposition

Set SingleLegOrder.OrderType

func Quantity

func Quantity(quantity float32) SingleLegOrderComposition

Set SingleLegOrder.Quantity

func Session

func Session(session string) SingleLegOrderComposition

Set SingleLegOrder.Session

func Strategy

func Strategy(strategy string) SingleLegOrderComposition

Set SingleLegOrder.Strategy

type Token

type Token struct {
	RefreshExpiration time.Time
	Refresh           string
	BearerExpiration  time.Time
	Bearer            string
}

type TraderError

type TraderError struct {
	Err      error
	Response *http.Response
}

Custom Error Struct

func (*TraderError) Error

func (e *TraderError) Error() string

Needs Error() to satisfy error interface

func (*TraderError) Unwrap

func (e *TraderError) Unwrap() error

Unwrap is needed to support working with errors.Is & errors.As.

type Transaction

type Transaction struct {
	ActivityId     int
	Time           string
	User           User
	Description    string
	AccountNumber  string
	Type           string
	Status         string
	SubAccount     string
	TradeDate      string
	SettlementDate string
	PositionId     int
	OrderId        int
	NetAmount      int
	ActivityType   string
	TransferItems  TransferItems
}

type TransferItems

type TransferItems struct {
	Instrument     InstrumentRef
	Amount         int
	Cost           int
	Price          int
	FeeType        string
	PositionEffect string
}

type Underlying

type Underlying struct {
	Ask               float64
	AskSize           float64
	Bid               float64
	BidSize           float64
	Change            float64
	Close             float64
	Delayed           bool
	Description       string
	ExchangeName      string
	Hi52              float64 `json:"fiftyTwoWeekHigh"fiftyTwoWeekHigh"`
	Lo52              float64 `json:"fiftyTwoWeekHigh"fiftyTwoWeekLow"`
	HiPrice           float64 `json:"highPrice"`
	LoPrice           float64 `json:"lowPrice"`
	Mark              float64
	MarkPercentChange float64
	OpenPrice         float64
	PercentChange     float64
	QuoteTime         int64
	Symbol            string
	TotalVolume       int64
	TradeTime         int64
}

type User

type User struct {
	CdDomainId     string
	Login          string
	Type           string
	UserId         int
	SystemUserName string
	FirstName      string
	LastName       string
	BrokerRepCode  string
}

Jump to

Keyboard shortcuts

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