alpaca

package
v2.0.0-...-eb91723 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2022 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OrderStatusNew                OrderStatus = "new"
	OrderStatusPartiallyFilled    OrderStatus = "partially_filled"
	OrderStatusFilled                         = "filled"
	OrderStatusDoneForDay                     = "done_for_day"
	OrderStatusCancelled                      = "canceled"
	OrderStatusExpired                        = "expired"
	OrderStatusReplaced                       = "replaced"
	OrderStatusPendingCancel                  = "pending_cancel"
	OrderStatusPendingReplace                 = "pending_replace"
	OrderStatusAccepted                       = "accepted"
	OrderStatusPendingNew                     = "pending_new"
	OrderStatusAcceptedForBidding             = "accepted_for_bidding"
	OrderStatusStopped                        = "stopped"
	OrderStatusRejected                       = "rejected"
	OrderStatusSuspended                      = "suspended"
	OrderStatusCalculated                     = "calculated"
)

Variables

View Source
var DefaultClient = NewClient(ClientOpts{})

DefaultClient uses options from environment variables, or the defaults.

Functions

func CancelOrder

func CancelOrder(orderID string) error

CancelOrder submits a request to cancel an open order with the default Alpaca client.

func StreamTradeUpdates

func StreamTradeUpdates(ctx context.Context, handler func(TradeUpdate)) error

StreamTradeUpdates streams the trade updates of the account. It blocks and keeps calling the handler function for each trade update until the context is cancelled.

func StreamTradeUpdatesInBackground

func StreamTradeUpdatesInBackground(ctx context.Context, handler func(TradeUpdate))

StreamTradeUpdatesInBackground streams the trade updates of the account. It runs in the background and keeps calling the handler function for each trade update until the context is cancelled. If an error happens it logs it and retries immediately.

Types

type APIError

type APIError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

APIError wraps the detailed code and message supplied by Alpaca's API for debugging purposes

func (*APIError) Error

func (e *APIError) Error() string

type Account

type Account struct {
	v2.Entity
	ID                    string          `json:"id"`
	AccountNumber         string          `json:"account_number"`
	CreatedAt             time.Time       `json:"created_at"`
	UpdatedAt             time.Time       `json:"updated_at"`
	DeletedAt             *time.Time      `json:"deleted_at"`
	Status                string          `json:"status"`
	Currency              string          `json:"currency"`
	Cash                  decimal.Decimal `json:"cash"`
	CashWithdrawable      decimal.Decimal `json:"cash_withdrawable"`
	TradingBlocked        bool            `json:"trading_blocked"`
	TransfersBlocked      bool            `json:"transfers_blocked"`
	AccountBlocked        bool            `json:"account_blocked"`
	ShortingEnabled       bool            `json:"shorting_enabled"`
	BuyingPower           decimal.Decimal `json:"buying_power"`
	PatternDayTrader      bool            `json:"pattern_day_trader"`
	DaytradeCount         int64           `json:"daytrade_count"`
	DaytradingBuyingPower decimal.Decimal `json:"daytrading_buying_power"`
	RegTBuyingPower       decimal.Decimal `json:"regt_buying_power"`
	Equity                decimal.Decimal `json:"equity"`
	LastEquity            decimal.Decimal `json:"last_equity"`
	Multiplier            string          `json:"multiplier"`
	InitialMargin         decimal.Decimal `json:"initial_margin"`
	MaintenanceMargin     decimal.Decimal `json:"maintenance_margin"`
	LastMaintenanceMargin decimal.Decimal `json:"last_maintenance_margin"`
	LongMarketValue       decimal.Decimal `json:"long_market_value"`
	ShortMarketValue      decimal.Decimal `json:"short_market_value"`
	PortfolioValue        decimal.Decimal `json:"portfolio_value"`
}

func GetAccount

func GetAccount() (*Account, error)

GetAccount returns the user's account information using the default Alpaca client.

type AccountActivitiesRequest

type AccountActivitiesRequest struct {
	v2.Entity
	ActivityTypes *[]string  `json:"activity_types"`
	Date          *time.Time `json:"date"`
	Until         *time.Time `json:"until"`
	After         *time.Time `json:"after"`
	Direction     *string    `json:"direction"`
	PageSize      *int       `json:"page_size"`
}

type AccountActivity

type AccountActivity struct {
	v2.Entity
	ID              string          `json:"id"`
	ActivityType    string          `json:"activity_type"`
	TransactionTime time.Time       `json:"transaction_time"`
	Type            string          `json:"type"`
	Price           decimal.Decimal `json:"price"`
	Qty             decimal.Decimal `json:"qty"`
	Side            string          `json:"side"`
	Symbol          string          `json:"symbol"`
	LeavesQty       decimal.Decimal `json:"leaves_qty"`
	CumQty          decimal.Decimal `json:"cum_qty"`
	Date            civil.Date      `json:"date"`
	NetAmount       decimal.Decimal `json:"net_amount"`
	Description     string          `json:"description"`
	PerShareAmount  decimal.Decimal `json:"per_share_amount"`
}

func GetAccountActivities

func GetAccountActivities(activityType *string, opts *AccountActivitiesRequest) ([]AccountActivity, error)

type AccountConfigurations

type AccountConfigurations struct {
	v2.Entity
	DtbpCheck            DtbpCheck         `json:"dtbp_check"`
	NoShorting           bool              `json:"no_shorting"`
	TradeConfirmEmail    TradeConfirmEmail `json:"trade_confirm_email"`
	TradeSuspendedByUser bool              `json:"trade_suspended_by_user"`
}

func GetAccountConfigurations

func GetAccountConfigurations() (*AccountConfigurations, error)

GetAccountConfigurations returns the account configs using the default Alpaca client.

func UpdateAccountConfigurations

func UpdateAccountConfigurations(newConfigs AccountConfigurationsRequest) (*AccountConfigurations, error)

UpdateAccountConfigurations changes the account configs and returns the new configs using the default Alpaca client

type AccountConfigurationsRequest

type AccountConfigurationsRequest struct {
	v2.Entity
	DtbpCheck            *string `json:"dtbp_check"`
	NoShorting           *bool   `json:"no_shorting"`
	TradeConfirmEmail    *string `json:"trade_confirm_email"`
	TradeSuspendedByUser *bool   `json:"trade_suspended_by_user"`
}

type AccountStatus

type AccountStatus string
const (
	AccountStatusOnboarding       AccountStatus = "ONBOARDING"
	AccountStatusSubmissionFailed AccountStatus = "SUBMISSION_FAILED"
	AccountStatusSubmitted        AccountStatus = "SUBMITTED"
	AccountStatusAccountUpdated   AccountStatus = "ACCOUNT_UPDATED"
	AccountStatusApprovalPending  AccountStatus = "APPROVAL_PENDING"
	AccountStatusActive           AccountStatus = "ACTIVE"
	AccountStatusRejected         AccountStatus = "REJECTED"
)

type Asset

type Asset struct {
	v2.Entity
	ID                string           `json:"id"`
	Name              string           `json:"name"`
	Exchange          string           `json:"exchange"`
	Class             string           `json:"class"`
	Symbol            string           `json:"symbol"`
	Status            string           `json:"status"`
	Tradable          bool             `json:"tradable"`
	Marginable        bool             `json:"marginable"`
	Shortable         bool             `json:"shortable"`
	EasyToBorrow      bool             `json:"easy_to_borrow"`
	Fractionable      bool             `json:"fractionable"`
	MinOrderSize      *decimal.Decimal `json:"min_order_size,omitempty"`
	MinTradeIncrement *decimal.Decimal `json:"min_trade_increment,omitempty"`
	PriceIncrement    *decimal.Decimal `json:"price_increment,omitempty"`
}

func GetAsset

func GetAsset(symbol string) (*Asset, error)

GetAsset returns an asset for the given symbol with the default Alpaca client.

func ListAssets

func ListAssets(status *string) ([]Asset, error)

ListAssets returns the list of assets, filtered by the input parameters with the default Alpaca client.

type AssetClass

type AssetClass string
const (
	USEquity AssetClass = "us_equity"
	Crypto   AssetClass = "crypto"
)

func (AssetClass) String

func (as AssetClass) String() string

type AssetStatus

type AssetStatus string
const (
	AssetStatusActive   AssetStatus = "active"
	AssetStatusInactive AssetStatus = "inactive"
)

type CalendarDay

type CalendarDay struct {
	v2.Entity
	Date  string `json:"date"`
	Open  string `json:"open"`
	Close string `json:"close"`
}

func GetCalendar

func GetCalendar(start, end *string) ([]CalendarDay, error)

GetCalendar returns the market calendar, sliced by the start and end dates using the default Alpaca client.

type Client

type Client interface {
	GetAccount() (*Account, error)
	GetAccountConfigurations() (*AccountConfigurations, error)
	UpdateAccountConfigurations(newConfigs AccountConfigurationsRequest) (*AccountConfigurations, error)
	GetAccountActivities(activityType *string, opts *AccountActivitiesRequest) ([]AccountActivity, error)
	GetPortfolioHistory(period *string, timeframe *RangeFreq, dateEnd *time.Time, extendedHours bool) (*PortfolioHistory, error)
	ListPositions() ([]Position, error)
	GetPosition(symbol string) (*Position, error)
	CloseAllPositions() error
	ClosePosition(symbol string) error
	GetClock() (*Clock, error)
	GetCalendar(start, end *string) ([]CalendarDay, error)
	ListOrders(status *string, until *time.Time, limit *int, nested *bool) ([]Order, error)
	ListOrdersWithRequest(req ListOrdersRequest) ([]Order, error)
	PlaceOrder(req PlaceOrderRequest) (*Order, error)
	GetOrder(orderID string) (*Order, error)
	GetOrderByClientOrderID(clientOrderID string) (*Order, error)
	ReplaceOrder(orderID string, req ReplaceOrderRequest) (*Order, error)
	CancelOrder(orderID string) error
	CancelAllOrders() error
	ListAssets(status *string) ([]Asset, error)
	GetAsset(symbol string) (*Asset, error)
	StreamTradeUpdates(ctx context.Context, handler func(TradeUpdate)) error
	StreamTradeUpdatesInBackground(ctx context.Context, handler func(TradeUpdate))
}

Client is the alpaca client.

func NewClient

func NewClient(opts ClientOpts) Client

NewClient creates a new Alpaca trading client using the given opts.

type ClientOpts

type ClientOpts struct {
	ApiKey    string
	ApiSecret string
	OAuth     string
	BaseURL   string
	// Timeout sets the HTTP timeout for each request.
	//
	// Deprecated: use HttpClient with its Timeout set instead.
	// If both are set, HttpClient has precedence.
	Timeout    time.Duration
	RetryLimit int
	RetryDelay time.Duration
	// HttpClient to be used for each http request.
	HttpClient *http.Client
}

ClientOpts contains options for the alpaca client

type Clock

type Clock struct {
	v2.Entity
	Timestamp time.Time `json:"timestamp"`
	IsOpen    bool      `json:"is_open"`
	NextOpen  time.Time `json:"next_open"`
	NextClose time.Time `json:"next_close"`
}

func GetClock

func GetClock() (*Clock, error)

GetClock returns the current market clock using the default Alpaca client.

type DtbpCheck

type DtbpCheck string
const (
	Entry DtbpCheck = "entry"
	Exit  DtbpCheck = "exit"
	Both  DtbpCheck = "both"
)

func (DtbpCheck) String

func (d DtbpCheck) String() string

type Fundamental

type Fundamental struct {
	v2.Entity
	AssetID           string          `json:"asset_id"`
	Symbol            string          `json:"symbol"`
	FullName          string          `json:"full_name"`
	IndustryName      string          `json:"industry_name"`
	IndustryGroup     string          `json:"industry_group"`
	Sector            string          `json:"sector"`
	PERatio           float32         `json:"pe_ratio"`
	PEGRatio          float32         `json:"peg_ratio"`
	Beta              float32         `json:"beta"`
	EPS               float32         `json:"eps"`
	MarketCap         int64           `json:"market_cap"`
	SharesOutstanding int64           `json:"shares_outstanding"`
	AvgVol            int64           `json:"avg_vol"`
	DivRate           float32         `json:"div_rate"`
	ROE               float32         `json:"roe"`
	ROA               float32         `json:"roa"`
	PS                float32         `json:"ps"`
	PC                float32         `json:"pc"`
	GrossMargin       float32         `json:"gross_margin"`
	FiftyTwoWeekHigh  decimal.Decimal `json:"fifty_two_week_high"`
	FiftyTwoWeekLow   decimal.Decimal `json:"fifty_two_week_low"`
	ShortDescription  string          `json:"short_description"`
	LongDescription   string          `json:"long_description"`
}

type ListOrdersRequest

type ListOrdersRequest struct {
	v2.Entity
	Status    *string    `json:"status"`
	After     *time.Time `json:"after"`
	Until     *time.Time `json:"until"`
	Limit     *int       `json:"limit"`
	Direction *string    `json:"direction"`
	Nested    *bool      `json:"nested"`
	Symbols   *string    `json:"symbols"`
}

type Order

type Order struct {
	v2.Entity
	ID             string           `json:"id"`
	ClientOrderID  string           `json:"client_order_id"`
	CreatedAt      time.Time        `json:"created_at"`
	UpdatedAt      time.Time        `json:"updated_at"`
	SubmittedAt    time.Time        `json:"submitted_at"`
	FilledAt       *time.Time       `json:"filled_at"`
	ExpiredAt      *time.Time       `json:"expired_at"`
	CanceledAt     *time.Time       `json:"canceled_at"`
	FailedAt       *time.Time       `json:"failed_at"`
	ReplacedAt     *time.Time       `json:"replaced_at"`
	Replaces       *string          `json:"replaces"`
	ReplacedBy     *string          `json:"replaced_by"`
	AssetID        string           `json:"asset_id"`
	Symbol         string           `json:"symbol"`
	Exchange       string           `json:"exchange"`
	Class          string           `json:"asset_class"`
	Qty            *decimal.Decimal `json:"qty"`
	Notional       *decimal.Decimal `json:"notional"`
	FilledQty      decimal.Decimal  `json:"filled_qty"`
	Type           OrderType        `json:"order_type"`
	Side           Side             `json:"side"`
	TimeInForce    TimeInForce      `json:"time_in_force"`
	LimitPrice     *decimal.Decimal `json:"limit_price"`
	FilledAvgPrice *decimal.Decimal `json:"filled_avg_price"`
	StopPrice      *decimal.Decimal `json:"stop_price"`
	TrailPrice     *decimal.Decimal `json:"trail_price"`
	TrailPercent   *decimal.Decimal `json:"trail_percent"`
	Hwm            *decimal.Decimal `json:"hwm"`
	Status         string           `json:"status"`
	ExtendedHours  bool             `json:"extended_hours"`
	Legs           *[]Order         `json:"legs"`
}

func GetOrder

func GetOrder(orderID string) (*Order, error)

GetOrder returns a single order for the given `orderID` using the default Alpaca client.

func GetOrderByClientOrderID

func GetOrderByClientOrderID(clientOrderID string) (*Order, error)

GetOrderByClientOrderID returns a single order for the given `clientOrderID` using the default Alpaca client.

func ListOrders

func ListOrders(status *string, until *time.Time, limit *int, nested *bool) ([]Order, error)

ListOrders returns the list of orders for an account, filtered by the input parameters using the default Alpaca client.

func PlaceOrder

func PlaceOrder(req PlaceOrderRequest) (*Order, error)

PlaceOrder submits an order request to buy or sell an asset with the default Alpaca client.

func ReplaceOrder

func ReplaceOrder(orderID string, req ReplaceOrderRequest) (*Order, error)

ReplaceOrder changes an order by order id using the default Alpaca client.

type OrderAttributes

type OrderAttributes struct {
	v2.Entity
	TakeProfitLimitPrice *decimal.Decimal `json:"take_profit_limit_price,omitempty"`
	StopLossStopPrice    *decimal.Decimal `json:"stop_loss_stop_price,omitempty"`
	StopLossLimitPrice   *decimal.Decimal `json:"stop_loss_limit_price,omitempty"`
}

type OrderClass

type OrderClass string
const (
	Bracket OrderClass = "bracket"
	Oto     OrderClass = "oto"
	Oco     OrderClass = "oco"
	Simple  OrderClass = "simple"
)

func (OrderClass) String

func (c OrderClass) String() string

type OrderStatus

type OrderStatus string

type OrderType

type OrderType string
const (
	Market       OrderType = "market"
	Limit        OrderType = "limit"
	Stop         OrderType = "stop"
	StopLimit    OrderType = "stop_limit"
	TrailingStop OrderType = "trailing_stop"
)

func (OrderType) String

func (t OrderType) String() string

type PlaceOrderRequest

type PlaceOrderRequest struct {
	v2.Entity
	AccountID     string           `json:"-"`
	AssetKey      *string          `json:"symbol"`
	Qty           *decimal.Decimal `json:"qty"`
	Notional      *decimal.Decimal `json:"notional"`
	Side          Side             `json:"side"`
	Type          OrderType        `json:"type"`
	TimeInForce   TimeInForce      `json:"time_in_force"`
	LimitPrice    *decimal.Decimal `json:"limit_price"`
	ExtendedHours bool             `json:"extended_hours"`
	StopPrice     *decimal.Decimal `json:"stop_price"`
	ClientOrderID string           `json:"client_order_id"`
	OrderClass    OrderClass       `json:"order_class"`
	TakeProfit    *TakeProfit      `json:"take_profit"`
	StopLoss      *StopLoss        `json:"stop_loss"`
	TrailPrice    *decimal.Decimal `json:"trail_price"`
	TrailPercent  *decimal.Decimal `json:"trail_percent"`
}

type PortfolioHistory

type PortfolioHistory struct {
	v2.Entity
	BaseValue     decimal.Decimal   `json:"base_value"`
	Equity        []decimal.Decimal `json:"equity"`
	ProfitLoss    []decimal.Decimal `json:"profit_loss"`
	ProfitLossPct []decimal.Decimal `json:"profit_loss_pct"`
	Timeframe     RangeFreq         `json:"timeframe"`
	Timestamp     []int64           `json:"timestamp"`
}

func GetPortfolioHistory

func GetPortfolioHistory(period *string, timeframe *RangeFreq, dateEnd *time.Time, extendedHours bool) (*PortfolioHistory, error)

type Position

type Position struct {
	v2.Entity
	AssetID        string           `json:"asset_id"`
	Symbol         string           `json:"symbol"`
	Exchange       string           `json:"exchange"`
	Class          string           `json:"asset_class"`
	AccountID      string           `json:"account_id"`
	EntryPrice     decimal.Decimal  `json:"avg_entry_price"`
	Qty            decimal.Decimal  `json:"qty"`
	Side           string           `json:"side"`
	MarketValue    *decimal.Decimal `json:"market_value"`
	CostBasis      decimal.Decimal  `json:"cost_basis"`
	UnrealizedPL   *decimal.Decimal `json:"unrealized_pl"`
	UnrealizedPLPC *decimal.Decimal `json:"unrealized_plpc"`
	CurrentPrice   *decimal.Decimal `json:"current_price"`
	LastdayPrice   *decimal.Decimal `json:"lastday_price"`
	ChangeToday    *decimal.Decimal `json:"change_today"`
}

func GetPosition

func GetPosition(symbol string) (*Position, error)

GetPosition returns the account's position for the provided symbol using the default Alpaca client.

func ListPositions

func ListPositions() ([]Position, error)

ListPositions lists the account's open positions using the default Alpaca client.

type RangeFreq

type RangeFreq string
const (
	Min1  RangeFreq = "1Min"
	Min5  RangeFreq = "5Min"
	Min15 RangeFreq = "15Min"
	Hour1 RangeFreq = "1H"
	Day1  RangeFreq = "1D"
)

func (RangeFreq) String

func (r RangeFreq) String() string

type ReplaceOrderRequest

type ReplaceOrderRequest struct {
	v2.Entity
	Qty           *decimal.Decimal `json:"qty"`
	LimitPrice    *decimal.Decimal `json:"limit_price"`
	StopPrice     *decimal.Decimal `json:"stop_price"`
	Trail         *decimal.Decimal `json:"trail"`
	TimeInForce   TimeInForce      `json:"time_in_force"`
	ClientOrderID string           `json:"client_order_id"`
}

type Side

type Side string
const (
	Buy  Side = "buy"
	Sell Side = "sell"
)

func (Side) String

func (s Side) String() string

type StopLoss

type StopLoss struct {
	v2.Entity
	LimitPrice *decimal.Decimal `json:"limit_price"`
	StopPrice  *decimal.Decimal `json:"stop_price"`
}

type TakeProfit

type TakeProfit struct {
	v2.Entity
	LimitPrice *decimal.Decimal `json:"limit_price"`
}

type TimeInForce

type TimeInForce string
const (
	Day TimeInForce = "day"
	GTC TimeInForce = "gtc"
	OPG TimeInForce = "opg"
	IOC TimeInForce = "ioc"
	FOK TimeInForce = "fok"
	GTX TimeInForce = "gtx"
	GTD TimeInForce = "gtd"
	CLS TimeInForce = "cls"
)

func (TimeInForce) String

func (tif TimeInForce) String() string

type TradeConfirmEmail

type TradeConfirmEmail string
const (
	None TradeConfirmEmail = "none"
	All  TradeConfirmEmail = "all"
)

func (TradeConfirmEmail) String

func (t TradeConfirmEmail) String() string

type TradeUpdate

type TradeUpdate struct {
	v2.Entity
	Event       string           `json:"event"`
	ExecutionID string           `json:"execution_id"`
	Order       Order            `json:"order"`
	PositionQty *decimal.Decimal `json:"position_qty"`
	Price       *decimal.Decimal `json:"price"`
	Qty         *decimal.Decimal `json:"qty"`
	Timestamp   *time.Time       `json:"timestamp"`
}

Jump to

Keyboard shortcuts

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