robinhood

package module
v4.0.0-...-aff5d70 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2021 License: Apache-2.0 Imports: 21 Imported by: 0

README

Go Reference

Robinhood the rich and feeding the poor, now automated

Even though robinhood makes me poor

Notice

If you have used this library before, and use credential caching, you will need to remove any credential cache and rebuild if you experience errors.

General usage

cli, err := robinhood.Dial(&robinhood.OAuth{
  Username: "andrewstuart",
  Password: "mypasswordissecure",
})

// err

i, err := cli.GetInstrumentForSymbol("SPY")

// err

o, err := cli.Order(i, robinhood.OrderOpts{
  Price: 100.0,
  Side: robinhood.Buy,
  Quantity: 1,
})

// err

time.Sleep(5*time.Second) //Let me think about it some more...

// Ah crap, I need to buy groceries.

err := o.Cancel()

if err != nil {
  // Oh well
}

Documentation

Index

Constants

View Source
const (
	EPBase                  = "https://api.robinhood.com/"
	EPCryptoBase            = "https://nummus.robinhood.com/"
	PhoenixEPBase           = "https://phoenix.robinhood.com/"
	PhoenixEPAccountUnified = "accounts/unified/"
	EPCryptoOrders          = EPCryptoBase + "orders/"
	EPCryptoAccount         = EPCryptoBase + "accounts/"
	EPCryptoCurrencyPairs   = EPCryptoBase + "currency_pairs/"
	EPCryptoHoldings        = EPCryptoBase + "holdings/"
	EPCryptoPortfolio       = EPCryptoBase + "portfolios/"
	EPLogin                 = EPBase + "oauth2/token/"
	EPAccounts              = EPBase + "accounts/"
	EPQuotes                = EPBase + "quotes/"
	EPPortfolios            = EPBase + "portfolios/"
	EPPositions             = EPBase + "positions/"
	EPWatchlists            = EPBase + "watchlists/"
	EPInstruments           = EPBase + "instruments/"
	EPFundamentals          = EPBase + "fundamentals/"
	EPOrders                = EPBase + "orders/"
	EPOptions               = EPBase + "options/"
	EPMarket                = EPBase + "marketdata/"
	EPOptionQuote           = EPMarket + "options/"
)

Endpoints for the Robinhood API

View Source
const (
	HrExtendedOpen    = 4
	HrRHExtendedOpen  = 9
	HrClose           = 12 + 4
	HrRHExtendedClose = 12 + 6
	HrExtendedClose   = 12 + 8

	MinExtendedOpen    = HrExtendedOpen * 60
	MinRHExtendedOpen  = HrRHExtendedOpen * 60
	MinOpen            = 9*60 + 30
	MinClose           = HrClose * 60
	MinRHExtendedClose = HrRHExtendedClose * 60
	MinExtendedClose   = HrExtendedClose * 60
)

Common constants for hours and minutes from midnight at which market events occur.

View Source
const DefaultClientID = "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS"

DefaultClientID is used by the website.

Variables

View Source
var ErrMFARequired = fmt.Errorf("Two Factor Auth code required and not supplied")

ErrMFARequired indicates the MFA was required but not provided.

Functions

func IsExtendedTradingTime

func IsExtendedTradingTime() bool

IsExtendedTradingTime returns whether or not extended hours equity will be updated because extended-hours trades may still be allowed in the markets.

func IsRegularTradingTime

func IsRegularTradingTime() bool

IsRegularTradingTime returns whether or not the markets are currently open for regular trading.

func IsRobinhoodExtendedTradingTime

func IsRobinhoodExtendedTradingTime() bool

IsRobinhoodExtendedTradingTime returns whether or not trades can still be placed during the robinhood gold extended trading hours.

func IsWeekDay

func IsWeekDay(t time.Time) bool

IsWeekDay returns whether the given time is a regular weekday

func MinuteOfDay

func MinuteOfDay(t time.Time) int

MinuteOfDay returns the minute of the day for a given time.Time (hr * 60 + min).

func NextMarketClose

func NextMarketClose() time.Time

NextMarketClose returns the time of the next market close.

func NextMarketExtendedClose

func NextMarketExtendedClose() time.Time

NextMarketExtendedClose returns the time of the next extended market close, when stock equity numbers will stop being updated until the next extended open.

func NextMarketExtendedOpen

func NextMarketExtendedOpen() time.Time

NextMarketExtendedOpen returns the time of the next extended opening time, when stock equity may begin to fluctuate again.

func NextMarketOpen

func NextMarketOpen() time.Time

NextMarketOpen returns the time of the next opening bell, when regular trading begins.

func NextRobinhoodExtendedClose

func NextRobinhoodExtendedClose() time.Time

NextRobinhoodExtendedClose returns the time of the next robinhood extended closing time, when robinhood users must place their last extended-hours trade.

func NextRobinhoodExtendedOpen

func NextRobinhoodExtendedOpen() time.Time

NextRobinhoodExtendedOpen returns the time of the next robinhood extended opening time, when robinhood users can make trades.

func NextWeekday

func NextWeekday() time.Time

NextWeekday returns the next weekday.

Types

type Account

type Account struct {
	Meta
	AccountNumber              string         `json:"account_number"`
	BuyingPower                float64        `json:"buying_power,string"`
	Cash                       float64        `json:"cash,string"`
	CashAvailableForWithdrawal float64        `json:"cash_available_for_withdrawal,string"`
	CashBalances               CashBalances   `json:"cash_balances"`
	CashHeldForOrders          float64        `json:"cash_held_for_orders,string"`
	Deactivated                bool           `json:"deactivated"`
	DepositHalted              bool           `json:"deposit_halted"`
	MarginBalances             MarginBalances `json:"margin_balances"`
	MaxAchEarlyAccessAmount    string         `json:"max_ach_early_access_amount"`
	OnlyPositionClosingTrades  bool           `json:"only_position_closing_trades"`
	Portfolio                  string         `json:"portfolio"`
	Positions                  string         `json:"positions"`
	Sma                        interface{}    `json:"sma"`
	SmaHeldForOrders           interface{}    `json:"sma_held_for_orders"`
	SweepEnabled               bool           `json:"sweep_enabled"`
	Type                       string         `json:"type"`
	UnclearedDeposits          float64        `json:"uncleared_deposits,string"`
	UnsettledFunds             float64        `json:"unsettled_funds,string"`
	User                       string         `json:"user"`
	WithdrawalHalted           bool           `json:"withdrawal_halted"`
}

Account holds the basic account details relevant to the RobinHood API

type AssetCurrency

type AssetCurrency struct {
	BrandColor string  `json:"brand_color"`
	Code       string  `json:"code"`
	ID         string  `json:"id"`
	Increment  float64 `json:"increment,string"`
	Name       string  `json:"name"`
}

AssetCurrency has code and id of cryptocurrency

type CashBalances

type CashBalances struct {
	Meta
	BuyingPower                float64 `json:"buying_power,string"`
	Cash                       float64 `json:"cash,string"`
	CashAvailableForWithdrawal float64 `json:"cash_available_for_withdrawal,string"`
	CashHeldForOrders          float64 `json:"cash_held_for_orders,string"`
	UnclearedDeposits          float64 `json:"uncleared_deposits,string"`
	UnsettledFunds             float64 `json:"unsettled_funds,string"`
}

CashBalances reflect the amount of cash available

type Client

type Client struct {
	Token         string
	Account       *Account
	CryptoAccount *CryptoAccount
	*http.Client
}

A Client is a helpful abstraction around some common metadata required for API operations.

func Dial

func Dial(ctx context.Context, s oauth2.TokenSource) (*Client, error)

Dial returns a client given a TokenGetter. TokenGetter implementations are available in this package, including a Cookie-based cache.

func (*Client) AllOrders

func (c *Client) AllOrders(ctx context.Context) ([]OrderOutput, error)

AllOrders returns all orders made by this client.

func (*Client) CryptoOrder

func (c *Client) CryptoOrder(ctx context.Context, cryptoPair CryptoCurrencyPair, o CryptoOrderOpts) (*CryptoOrderOutput, error)

CryptoOrder will actually place the order

func (*Client) DoAndDecode

func (c *Client) DoAndDecode(ctx context.Context, req *http.Request, dest interface{}) error

DoAndDecode provides useful abstractions around common errors and decoding issues.

func (*Client) GetAccounts

func (c *Client) GetAccounts(ctx context.Context) ([]Account, error)

GetAccounts returns all the accounts associated with a login/client.

func (*Client) GetAndDecode

func (c *Client) GetAndDecode(ctx context.Context, url string, dest interface{}) error

GetAndDecode retrieves from the endpoint and unmarshals resulting json into the provided destination interface, which must be a pointer.

func (*Client) GetCryptoAccounts

func (c *Client) GetCryptoAccounts(ctx context.Context) ([]CryptoAccount, error)

GetCryptoAccounts will return associated cryto account

func (*Client) GetCryptoCurrencyPairs

func (c *Client) GetCryptoCurrencyPairs(ctx context.Context) ([]CryptoCurrencyPair, error)

GetCryptoCurrencyPairs will give which crypto currencies are tradeable and corresponding ids

func (*Client) GetCryptoHistoricals

func (c *Client) GetCryptoHistoricals(ctx context.Context, cryptoID string, interval string, span string, bounds string) (HistoricalData, error)

GetCryptoHistoricals will give the high low open, close data fro the given symbol and span

func (*Client) GetCryptoInstrument

func (c *Client) GetCryptoInstrument(ctx context.Context, symbol string) (*CryptoCurrencyPair, error)

GetCryptoInstrument will take standard crypto symbol and return usable information to place the order

func (*Client) GetCryptoOrder

func (c *Client) GetCryptoOrder(ctx context.Context, orderID string) (*CryptoOrderOutput, error)

GetCryptoOrder will get the order info from robinhood

func (*Client) GetCryptoPortfolios

func (c *Client) GetCryptoPortfolios(ctx context.Context) (CryptoPortfolio, error)

GetCryptoPortfolios returns crypto portfolio info

func (*Client) GetCryptoPositions

func (c *Client) GetCryptoPositions(ctx context.Context) ([]CryptoPosition, error)

GetCryptoPositions returns all positions associated with the account

func (*Client) GetCryptoQuote

func (c *Client) GetCryptoQuote(ctx context.Context, cryptoIds ...string) ([]CryptoQuote, error)

GetCryptoQuote will return an array of current quotes these will change almost every second

func (*Client) GetDailyHistoricals

func (c *Client) GetDailyHistoricals(ctx context.Context, cryptoID string) (HistoricalData, error)

GetDailyHistoricals will give daily high, low, ope, close data for the given symbol

func (*Client) GetFundamentals

func (c *Client) GetFundamentals(ctx context.Context, stocks ...string) ([]Fundamental, error)

GetFundamentals returns fundamental data for the list of stocks provided.

func (*Client) GetInstrument

func (c *Client) GetInstrument(ctx context.Context, instURL string) (*Instrument, error)

GetInstrument returns an Instrument given a URL

func (*Client) GetInstrumentForSymbol

func (c *Client) GetInstrumentForSymbol(ctx context.Context, sym string) (*Instrument, error)

GetInstrumentForSymbol returns an Instrument given a ticker symbol

func (*Client) GetOptionChains

func (c *Client) GetOptionChains(ctx context.Context, is ...*Instrument) ([]*OptionChain, error)

GetOptionChains returns options for the given instruments

func (*Client) GetOptionPositions

func (c *Client) GetOptionPositions(ctx context.Context) ([]OptionPostion, error)

GetPositions returns all the positions associated with an account.

func (*Client) GetOptionPositionsParams

func (c *Client) GetOptionPositionsParams(ctx context.Context, p PositionParams) ([]OptionPostion, error)

GetPositionsParams returns all the positions associated with a count, but passes the encoded PositionsParams object along to the RobinHood API as part of the query string.

func (*Client) GetOptionsOrders

func (c *Client) GetOptionsOrders(ctx context.Context) (json.RawMessage, error)

GetOptionsOrders returns all outstanding options orders

func (*Client) GetPortfolios

func (c *Client) GetPortfolios(ctx context.Context) ([]Portfolio, error)

GetPortfolios returns all the portfolios associated with a client's credentials and accounts

func (*Client) GetPositions

func (c *Client) GetPositions(ctx context.Context) ([]Position, error)

GetPositions returns all the positions associated with an account.

func (*Client) GetPositionsParams

func (c *Client) GetPositionsParams(ctx context.Context, p PositionParams) ([]Position, error)

GetPositionsParams returns all the positions associated with a count, but passes the encoded PositionsParams object along to the RobinHood API as part of the query string.

func (*Client) GetQuote

func (c *Client) GetQuote(ctx context.Context, stocks ...string) ([]Quote, error)

GetQuote returns all the latest stock quotes for the list of stocks provided

func (*Client) GetUnifiedAccount

func (c *Client) GetUnifiedAccount(ctx context.Context) (*UnifiedAccount, error)

GetUnifiedAccount will return account information we can use

func (*Client) GetWatchlists

func (c *Client) GetWatchlists(ctx context.Context) ([]Watchlist, error)

GetWatchlists retrieves the watchlists for a given set of credentials/accounts.

func (*Client) MarketData

func (c *Client) MarketData(ctx context.Context, opts ...*OptionInstrument) ([]*MarketData, error)

MarketData returns market data for all the listed Option instruments

func (*Client) Order

func (c *Client) Order(ctx context.Context, i *Instrument, o OrderOpts) (*OrderOutput, error)

Order places an order for a given instrument. Cancellation of the given context cancels only the _http request_ and not any orders that may have been created regardless of the cancellation.

func (*Client) OrderOptions

OrderOptions places a new order for options. Cancellation of the context.Context will cancel the _http request_, never the order itself if it has already been created.

func (*Client) Pricebook

func (c *Client) Pricebook(ctx context.Context, instrumentID string) (*PriceBookData, error)

Pricebook get the current snapshot of the pricebook data

func (*Client) RecentOrders

func (c *Client) RecentOrders(ctx context.Context) ([]OrderOutput, error)

RecentOrders returns any recent orders made by this client.

type CostBases

type CostBases struct {
	CurrencyID      string  `json:"currency_id"`
	DirectCostBasis float64 `json:"direct_cost_basis,string"`
	DirectQuantity  float64 `json:"direct_quantity,string"`
	ID              string  `json:"id"`
}

CostBases represents the actual cost the robinhood user paid for asset

type CredsCacher

type CredsCacher struct {
	Creds oauth2.TokenSource
	Path  string
}

A CredsCacher takes user credentials and a file path. The token obtained from the RobinHood API will be cached at the file path, and a new token will not be obtained.

func (*CredsCacher) Token

func (c *CredsCacher) Token() (*oauth2.Token, error)

Token implements TokenSource. It may fail if an error is encountered checking the file path provided, or if the underlying creds return an error when retrieving their token.

type CryptoAccount

type CryptoAccount struct {
	ID     string `json:"id"`
	Status string `json:"status"`
	UserID string `json:"user_id"`
}

CryptoAccount holds the basic account details relevant to robinhood API

type CryptoCurrency

type CryptoCurrency struct {
	BrandColor string  `json:"brand_color"`
	Code       string  `json:"code"`
	ID         string  `json:"id"`
	Increment  float64 `json:"increment,string"`
	Name       string  `json:"name"`
	Type       string  `json:"type"`
}

CryptoCurrency represents a sub object listed in CryptoPosition

type CryptoCurrencyPair

type CryptoCurrencyPair struct {
	CyrptoAssetCurrency    AssetCurrency `json:"asset_currency"`
	ID                     string        `json:"id"`
	MaxOrderSize           float64       `json:"max_order_size,string"`
	MinOrderPriceIncrement float64       `json:"min_order_price_increment,string"`
	MinOrderSize           float64       `json:"min_order_size,string"`
	Name                   string        `json:"name"`
	CrytoQuoteCurrency     QuoteCurrency `json:"quote_currency"`
	Symbol                 string        `json:"symbol"`
	Tradability            string        `json:"tradability"`
}

CryptoCurrencyPair represent all availabe crypto currencies and whether they are tradeable or not

type CryptoOrder

type CryptoOrder struct {
	AccountID      string  `json:"account_id,omitempty"`
	CurrencyPairID string  `json:"currency_pair_id,omitempty"`
	Price          float64 `json:"price,omitempty"`
	RefID          string  `json:"ref_id,omitempty"`
	Side           string  `json:"side,omitempty"`
	TimeInForce    string  `json:"time_in_force,omitempty"`
	Quantity       float64 `json:"quantity,omitempty"`
	Type           string  `json:"type,omitempty"`
}

CryptoOrder is the payload to create a crypto currency order

type CryptoOrderOpts

type CryptoOrderOpts struct {
	Side            OrderSide
	Type            OrderType
	AmountInDollars float64
	Quantity        float64
	Price           float64
	TimeInForce     TimeInForce
	ExtendedHours   bool
	Stop, Force     bool
}

CryptoOrderOpts encapsulates differences between order types

type CryptoOrderOutput

type CryptoOrderOutput struct {
	Meta
	Account            string      `json:"account_id"`
	AveragePrice       float64     `json:"average_price,string"`
	CancelURL          string      `json:"cancel_url"`
	CumulativeQuantity string      `json:"cumulative_quantity"`
	CurrencyPairID     string      `json:"currency_pair_id"`
	Executions         []Execution `json:"executions"`
	ID                 string      `json:"id"`
	LastTransactionAt  string      `json:"last_transaction_at"`
	Price              float64     `json:"price,string"`
	Quantity           string      `json:"quantity"`
	RejectReason       string      `json:"reject_reason"`
	Side               string      `json:"side"`
	State              string      `json:"state"`
	StopPrice          float64     `json:"stop_price,string"`
	TimeInForce        string      `json:"time_in_force"`
	Type               string      `json:"type"`
	// contains filtered or unexported fields
}

CryptoOrderOutput holds the response from api

func (CryptoOrderOutput) Cancel

func (o CryptoOrderOutput) Cancel(ctx context.Context) error

Cancel will cancel the order.

type CryptoPortfolio

type CryptoPortfolio struct {
	AccountID                string  `json:"account_id"`
	Equity                   float64 `json:"equity,string"`
	ExtendedHoursEquity      float64 `json:"extended_hours_equity,string"`
	ExtendedHoursMarketValue float64 `json:"extended_hours_market_value,string"`
	ID                       string  `json:"id"`
	MarketValue              float64 `json:"market_value,string"`
}

CryptoPortfolio returns all the portfolio associated with a client's account

type CryptoPosition

type CryptoPosition struct {
	Meta
	AccountID           string         `json:"account_id"`
	ID                  string         `json:"id"`
	Currency            CryptoCurrency `json:"currency"`
	Cost                []CostBases    `json:"cost_bases"`
	Quantity            float64        `json:"quantity,string"`
	QuantityAvailable   float64        `json:"quantity_available,string"`
	QuantityHeldForBuy  float64        `json:"quantity_held_for_buy,string"`
	QuantityHeldForSell float64        `json:"quantity_held_for_sell,string"`
}

CryptoPosition returns all crypto position associated with an account

type CryptoQuote

type CryptoQuote struct {
	AskPrice  float64 `json:"ask_price,string"`
	BidPrice  float64 `json:"bid_price,string"`
	HighPrice float64 `json:"high_price,string"`
	ID        string  `json:"id"`
	LowPrice  float64 `json:"low_price,string"`
	MarkPrice float64 `json:"mark_price,string"`
	OpenPrice float64 `json:"open_price,string"`
	Symbol    string  `json:"symbol"`
	Volume    string  `json:"volume"`
}

CryptoQuote is a representation of data returned by robinhood api for cryto quote

type Date

type Date struct {
	time.Time
}

Date is a specific json time format for dates only

func NewDate

func NewDate(y, m, d int) Date

NewDate returns a new Date in the local time zone

func NewZonedDate

func NewZonedDate(y, m, d int, z *time.Location) Date

NewZonedDate returns a date with a zone.

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (Date) String

func (d Date) String() string

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(bs []byte) error

UnmarshalJSON implements json.Unmarshaler

type EntryPrice

type EntryPrice struct {
	Amount        string
	Currency_code string
}

type ErrorMap

type ErrorMap map[string]interface{}

ErrorMap encapsulates the helpful error messages returned by the API server

func (ErrorMap) Error

func (e ErrorMap) Error() string

type Execution

type Execution struct {
	EffectivePrice float64 `json:"effective_Price,string"`
	ID             string  `json:"id"`
	Quantity       float64 `json:"quantity,string"`
	Timestamp      string  `json:"timestamp"`
}

type Fundamental

type Fundamental struct {
	Open          float64 `json:"open,string"`
	High          float64 `json:"high,string"`
	Low           float64 `json:"low,string"`
	Volume        float64 `json:"volume,string"`
	AverageVolume float64 `json:"average_volume,string"`
	High52Weeks   float64 `json:"high_52_weeks,string"`
	DividendYield float64 `json:"dividend_yield,string"`
	Low52Weeks    float64 `json:"low_52_weeks,string"`
	MarketCap     float64 `json:"market_cap,string"`
	PERatio       float64 `json:"pe_ratio,string"`
	Description   string  `json:"description"`
	Instrument    string  `json:"instrument"`
}

type Historical

type Historical struct {
	BeginsAt     string  `json:"begins_at"`
	OpenPrice    float64 `json:"open_price,string"`
	ClosePrice   float64 `json:"close_price,string"`
	HighPrice    float64 `json:"high_price,string"`
	LowPrice     float64 `json:"low_price,string"`
	Volume       int     `json:"volume"`
	Session      string  `json:"session"`
	Interpolated bool    `json:"interpolated"`
}

Historical data represents class ohlc data i.e open, high, low, close

type HistoricalData

type HistoricalData struct {
	DataPoints []Historical `json:"data_points"`
	Bounds     string       `json:"bounds"`
	Interval   string       `json:"interval"`
	Symbol     string       `json:"symbol"`
	ID         string       `json:"id"`
}

HistoricalData represents class ohlc data i.e open, high, low, close

type Instrument

type Instrument struct {
	BloombergUnique       string      `json:"bloomberg_unique"`
	Country               string      `json:"country"`
	DayTradeRatio         string      `json:"day_trade_ratio"`
	DefaultCollarFraction string      `json:"default_collar_fraction"`
	FractionalTradability string      `json:"fractional_tradability"`
	Fundamentals          string      `json:"fundamentals"`
	ID                    string      `json:"id"`
	ListDate              string      `json:"list_date"`
	MaintenanceRatio      string      `json:"maintenance_ratio"`
	MarginInitialRatio    string      `json:"margin_initial_ratio"`
	Market                string      `json:"market"`
	MinTickSize           interface{} `json:"min_tick_size"`
	Name                  string      `json:"name"`
	Quote                 string      `json:"quote"`
	RhsTradability        string      `json:"rhs_tradability"`
	SimpleName            interface{} `json:"simple_name"`
	Splits                string      `json:"splits"`
	State                 string      `json:"state"`
	Symbol                string      `json:"symbol"`
	Tradeable             bool        `json:"tradeable"`
	Tradability           string      `json:"tradability"`
	TradableChainID       string      `json:"tradable_chain_id"`
	Type                  string      `json:"type"`
	URL                   string      `json:"url"`
}

Instrument is a type to represent the "instrument" API type in the unofficial robinhood API.

func (Instrument) OrderSymbol

func (i Instrument) OrderSymbol() string

func (Instrument) OrderURL

func (i Instrument) OrderURL() string

type Leg

type Leg struct {
	Option         string    `json:"option"`
	PositionEffect string    `json:"position_effect"`
	RatioQuantity  float64   `json:"ratio_quantity,string"`
	Side           OrderSide `json:"side"`
}

A Leg is a single option contract that will be purchased as part of a single order. Transactions! Lower Risk!

type LegPosition

type LegPosition struct {
	Id             string `json:"id"`
	Position       string `json:"position"`
	PositionType   string `json:"position_type"`
	Option         string `json:"option"`
	RatioQuantity  string `json:"ratio_quantity"`
	ExpirationDate string `json:"expiration_date"`
	StrikePrice    string `json:"strike_price"`
	OptionType     string `json:"option_type"`
}

type MarginBalances

type MarginBalances struct {
	Meta
	Cash                              float64 `json:"cash,string"`
	CashAvailableForWithdrawal        float64 `json:"cash_available_for_withdrawal,string"`
	CashHeldForOrders                 float64 `json:"cash_held_for_orders,string"`
	DayTradeBuyingPower               float64 `json:"day_trade_buying_power,string"`
	DayTradeBuyingPowerHeldForOrders  float64 `json:"day_trade_buying_power_held_for_orders,string"`
	DayTradeRatio                     float64 `json:"day_trade_ratio,string"`
	MarginLimit                       float64 `json:"margin_limit,string"`
	MarkedPatternDayTraderDate        string  `json:"marked_pattern_day_trader_date"`
	OvernightBuyingPower              float64 `json:"overnight_buying_power,string"`
	OvernightBuyingPowerHeldForOrders float64 `json:"overnight_buying_power_held_for_orders,string"`
	OvernightRatio                    float64 `json:"overnight_ratio,string"`
	UnallocatedMarginCash             float64 `json:"unallocated_margin_cash,string"`
	UnclearedDeposits                 float64 `json:"uncleared_deposits,string"`
	UnsettledFunds                    float64 `json:"unsettled_funds,string"`
}

MarginBalances reflect the balance available in margin accounts

type MarketData

type MarketData struct {
	AdjustedMarkPrice   float64 `json:"adjusted_mark_price,string"`
	AskPrice            float64 `json:"ask_price,string"`
	AskSize             int     `json:"ask_size"`
	BidPrice            float64 `json:"bid_price,string"`
	BidSize             int     `json:"bid_size"`
	BreakEvenPrice      float64 `json:"break_even_price,string"`
	ChanceOfProfitLong  float64 `json:"chance_of_profit_long,string"`
	ChanceOfProfitShort float64 `json:"chance_of_profit_short,string"`
	Delta               float64 `json:"delta,string"`
	Gamma               float64 `json:"gamma,string"`
	HighPrice           float64 `json:"high_price,string"`
	ImpliedVolatility   string  `json:"implied_volatility"`
	Instrument          string  `json:"instrument"`
	LastTradePrice      float64 `json:"last_trade_price,string"`
	LastTradeSize       int     `json:"last_trade_size"`
	LowPrice            float64 `json:"low_price,string"`
	MarkPrice           float64 `json:"mark_price,string"`
	OpenInterest        int     `json:"open_interest"`
	PreviousCloseDate   Date    `json:"previous_close_date"`
	PreviousClosePrice  float64 `json:"previous_close_price,string"`
	Rho                 string  `json:"rho"`
	Theta               string  `json:"theta"`
	Vega                string  `json:"vega"`
	Volume              int     `json:"volume"`
}

MarketData is the current pricing data and greeks for a given option at a given time.

type Meta

type Meta struct {
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	URL       string    `json:"url"`
}

Meta holds metadata common to many RobinHood types.

type MinTicks

type MinTicks struct {
	AboveTick   float64 `json:"above_tick,string"`
	BelowTick   float64 `json:"below_tick,string"`
	CutoffPrice float64 `json:"cutoff_price,string"`
}

MinTicks probably is important.

type OAuth

type OAuth struct {
	Endpoint, ClientID, Username, Password, MFA string
}

OAuth implements oauth2 using the robinhood implementation

func (*OAuth) Token

func (p *OAuth) Token() (*oauth2.Token, error)

Token implements TokenSource

type OptionChain

type OptionChain struct {
	CanOpenPosition       bool                   `json:"can_open_position"`
	CashComponent         interface{}            `json:"cash_component"`
	ExpirationDates       []string               `json:"expiration_dates"`
	ID                    string                 `json:"id"`
	MinTicks              MinTicks               `json:"min_ticks"`
	Symbol                string                 `json:"symbol"`
	TradeValueMultiplier  float64                `json:"trade_value_multiplier,string"`
	UnderlyingInstruments []UnderlyingInstrument `json:"underlying_instruments"`
	// contains filtered or unexported fields
}

OptionChain represents the data the RobinHood API holds behind options chains

func (*OptionChain) GetInstrument

func (o *OptionChain) GetInstrument(ctx context.Context, tradeType string, date Date) ([]*OptionInstrument, error)

GetInstrument returns a list of option-typed instruments given a list of expiration dates for a given trade type. The request will continue until the provided context is cancelled. This is done to mimic the way the web UI fetches many, many options instruments repeatedly, since I haven't yet figured out how/when they decide to stop.

type OptionDirection

type OptionDirection int

OptionDirection is a type for whether an option order is opening or closing an option position

const (
	Debit OptionDirection = iota
	Credit
)

The two directions

func (OptionDirection) MarshalJSON

func (o OptionDirection) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (OptionDirection) String

func (i OptionDirection) String() string

type OptionInstrument

type OptionInstrument struct {
	ChainID        string   `json:"chain_id"`
	ChainSymbol    string   `json:"chain_symbol"`
	CreatedAt      string   `json:"created_at"`
	ExpirationDate Date     `json:"expiration_date"`
	ID             string   `json:"id"`
	IssueDate      string   `json:"issue_date"`
	MinTicks       MinTicks `json:"min_ticks"`
	RHSTradability string   `json:"rhs_tradability"`
	State          string   `json:"state"`
	StrikePrice    float64  `json:"strike_price,string"`
	Tradability    string   `json:"tradability"`
	Type           string   `json:"type"`
	UpdatedAt      string   `json:"updated_at"`
	URL            string   `json:"url"`
	// contains filtered or unexported fields
}

An OptionInstrument can have a quote

func OIsForDate

func OIsForDate(os []*OptionInstrument, d Date) []*OptionInstrument

OIsForDate filters OptionInstruments for expiration date.

type OptionPostion

type OptionPostion struct {
	Chain                    string        `json:"chain"`
	AverageOpenPrice         string        `json:"average_open_price"`
	Symbol                   string        `json:"symbol"`
	Quantity                 string        `json:"quantity"`
	Direction                string        `json:"direction"`
	IntradayDirection        string        `json:"intraday_direction"`
	TradeValueMultiplier     string        `json:"trade_value_multiplier"`
	Account                  string        `json:"account"`
	Strategy                 string        `json:"strategy"`
	Legs                     []LegPosition `json:"legs"`
	IntradayQuantity         string        `json:"intraday_quantity"`
	UpdatedAt                string        `json:"updated_at"`
	Id                       string        `json:"id"`
	IntradayAverageOpenPrice string        `json:"intraday_average_open_price"`
	CreatedAt                string        `json:"created_at"`
}

type OptionsOrderOpts

type OptionsOrderOpts struct {
	Quantity    float64
	Price       float64
	Direction   OptionDirection
	TimeInForce TimeInForce
	Type        OrderType
	Side        OrderSide
}

OptionsOrderOpts encapsulates common Options order choices

type OrderOpts

type OrderOpts struct {
	Side          OrderSide
	Type          OrderType
	Quantity      uint64
	Price         float64
	TimeInForce   TimeInForce
	ExtendedHours bool
	Stop, Force   bool
}

OrderOpts encapsulates differences between order types

type OrderOutput

type OrderOutput struct {
	Meta
	Account                string        `json:"account"`
	AveragePrice           float64       `json:"average_price,string"`
	CancelURL              string        `json:"cancel"`
	CumulativeQuantity     string        `json:"cumulative_quantity"`
	Executions             []interface{} `json:"executions"`
	ExtendedHours          bool          `json:"extended_hours"`
	Fees                   string        `json:"fees"`
	ID                     string        `json:"id"`
	Instrument             string        `json:"instrument"`
	LastTransactionAt      string        `json:"last_transaction_at"`
	OverrideDayTradeChecks bool          `json:"override_day_trade_checks"`
	OverrideDtbpChecks     bool          `json:"override_dtbp_checks"`
	Position               string        `json:"position"`
	Price                  float64       `json:"price,string"`
	Quantity               string        `json:"quantity"`
	RejectReason           string        `json:"reject_reason"`
	Side                   string        `json:"side"`
	State                  string        `json:"state"`
	StopPrice              float64       `json:"stop_price,string"`
	TimeInForce            string        `json:"time_in_force"`
	Trigger                string        `json:"trigger"`
	Type                   string        `json:"type"`
	// contains filtered or unexported fields
}

OrderOutput is the response from the Order api

func (OrderOutput) Cancel

func (o OrderOutput) Cancel(ctx context.Context) error

Cancel attempts to cancel an odrer

func (*OrderOutput) Update

func (o *OrderOutput) Update(ctx context.Context) error

Update returns any errors and updates the item with any recent changes.

type OrderSide

type OrderSide int

OrderSide is which side of the trade an order is on

const (
	Sell OrderSide = iota + 1
	Buy
)

Buy/Sell

func (OrderSide) MarshalJSON

func (o OrderSide) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (OrderSide) String

func (i OrderSide) String() string

type OrderType

type OrderType int

OrderType represents a Limit or Market order

const (
	Market OrderType = iota
	Limit
)

Well-known order types. Default is Market.

func (OrderType) MarshalJSON

func (o OrderType) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (OrderType) String

func (i OrderType) String() string

type Pager

type Pager struct {
	Next, Previous string
}

func (*Pager) GetNext

func (p *Pager) GetNext(ctx context.Context, c *Client, out interface{}) error

func (Pager) HasMore

func (p Pager) HasMore() bool

type Portfolio

type Portfolio struct {
	Account                                string  `json:"account"`
	AdjustedEquityPreviousClose            float64 `json:"adjusted_equity_previous_close,string"`
	Equity                                 float64 `json:"equity,string"`
	EquityPreviousClose                    float64 `json:"equity_previous_close,string"`
	ExcessMaintenance                      float64 `json:"excess_maintenance,string"`
	ExcessMaintenanceWithUnclearedDeposits float64 `json:"excess_maintenance_with_uncleared_deposits,string"`
	ExcessMargin                           float64 `json:"excess_margin,string"`
	ExcessMarginWithUnclearedDeposits      float64 `json:"excess_margin_with_uncleared_deposits,string"`
	ExtendedHoursEquity                    float64 `json:"extended_hours_equity,string"`
	ExtendedHoursMarketValue               float64 `json:"extended_hours_market_value,string"`
	LastCoreEquity                         float64 `json:"last_core_equity,string"`
	LastCoreMarketValue                    float64 `json:"last_core_market_value,string"`
	MarketValue                            float64 `json:"market_value,string"`
	StartDate                              string  `json:"start_date"`
	UnwithdrawableDeposits                 float64 `json:"unwithdrawable_deposits,string"`
	UnwithdrawableGrants                   float64 `json:"unwithdrawable_grants,string"`
	URL                                    string  `json:"url"`
	WithdrawableAmount                     float64 `json:"withdrawable_amount,string"`
}

Portfolio holds all information regarding the portfolio

type Position

type Position struct {
	Meta
	Account                 string  `json:"account"`
	AverageBuyPrice         float64 `json:"average_buy_price,string"`
	Instrument              string  `json:"instrument"`
	IntradayAverageBuyPrice float64 `json:"intraday_average_buy_price,string"`
	IntradayQuantity        float64 `json:"intraday_quantity,string"`
	Quantity                float64 `json:"quantity,string"`
	SharesHeldForBuys       float64 `json:"shares_held_for_buys,string"`
	SharesHeldForSells      float64 `json:"shares_held_for_sells,string"`
}

type PositionParams

type PositionParams struct {
	NonZero bool
}

PositionParams encapsulates parameters known to the RobinHood positions API endpoint.

type PriceBookData

type PriceBookData struct {
	Asks []PriceBookEntry `json:"asks"`
	Bids []PriceBookEntry `json:"bids"`

	InstrumentID string `json:"instrument_id"`
	UpdatedAt    string `json:"updated_at"`
}

type PriceBookEntry

type PriceBookEntry struct {
	Side     string
	Price    EntryPrice
	Quantity float64
}

type Quote

type Quote struct {
	AdjustedPreviousClose       float64 `json:"adjusted_previous_close,string"`
	AskPrice                    float64 `json:"ask_price,string"`
	AskSize                     int     `json:"ask_size"`
	BidPrice                    float64 `json:"bid_price,string"`
	BidSize                     int     `json:"bid_size"`
	LastExtendedHoursTradePrice float64 `json:"last_extended_hours_trade_price,string"`
	LastTradePrice              float64 `json:"last_trade_price,string"`
	PreviousClose               float64 `json:"previous_close,string"`
	PreviousCloseDate           string  `json:"previous_close_date"`
	Symbol                      string  `json:"symbol"`
	TradingHalted               bool    `json:"trading_halted"`
	UpdatedAt                   string  `json:"updated_at"`
}

A Quote is a representation of the data returned by the Robinhood API for current stock quotes

func (Quote) Price

func (q Quote) Price() float64

Price returns the proper stock price even after hours

type QuoteCurrency

type QuoteCurrency struct {
	Code      string  `json:"code"`
	ID        string  `json:"id"`
	Increment float64 `json:"increment,string"`
	Name      string  `json:"name"`
	Type      string  `json:"type"`
}

QuoteCurrency holds info about currency you can use to buy the cyrpto currency

type TimeInForce

type TimeInForce int

TimeInForce is the time in force for an order.

const (
	// GTC means Good 'Til Cancelled.
	GTC TimeInForce = iota
	// GFD means Good For Day.
	GFD
	// IOC means Immediate Or Cancel.
	IOC
	// OPG means Opening (of market).
	OPG
	// FOK means Fill Or Kill.
	FOK
)

Well-known values for TimeInForce

func (TimeInForce) MarshalJSON

func (t TimeInForce) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (TimeInForce) String

func (i TimeInForce) String() string

type UnderlyingInstrument

type UnderlyingInstrument struct {
	ID         string `json:"id"`
	Instrument string `json:"instrument"`
	Quantity   int    `json:"quantity"`
}

UnderlyingInstrument is the type that represents a link from an option back to its standard financial instrument (stock)

type UnifiedAccount

type UnifiedAccount struct {
	AccountBuyingPower struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"account_buying_power"`
	CashAvailableFromInstantDeposits struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"cash_available_from_instant_deposits"`
	CashHeldForCurrencyOrders struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"cash_held_for_currency_orders"`
	CashHeldForDividends struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"cash_held_for_dividends"`
	CashHeldForEquityOrders struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"cash_held_for_equity_orders"`
	CashHeldForOptionsCollateral struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"cash_held_for_options_collateral"`
	CashHeldForOrders struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"cash_held_for_orders"`
	CryptoBuyingPower struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"crypto_buying_power"`
	PortfolioEquity struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"portfolio_equity"`
	UninvestedCash struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"uninvested_cash"`
	WithdrawableCash struct {
		Amount       string `json:"amount,float64"`
		CurrencyCode string `json:"currency_code"`
		CurrencyID   string `json:"currency_id"`
	} `json:"withdrawable_cash"`
}

UnifiedAccount gives you the whole account info

type Unknown

type Unknown interface{}

type Watchlist

type Watchlist struct {
	Name string `json:"name"`
	URL  string `json:"url"`
	User string `json:"user"`

	Client *Client `json:",ignore"`
}

A Watchlist is a list of stock Instruments that an investor is tracking in his Robinhood portfolio/app.

func (*Watchlist) GetInstruments

func (w *Watchlist) GetInstruments(ctx context.Context) ([]Instrument, error)

GetInstruments returns the list of Instruments associated with a Watchlist.

Jump to

Keyboard shortcuts

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