### Install alpaca-trade-api-go Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/README.md Use 'go get' to install the latest version of the library. ```bash go get -u github.com/alpacahq/alpaca-trade-api-go/v3/alpaca ``` -------------------------------- ### Full Feature Client Setup Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/README.md This snippet demonstrates a comprehensive setup including trading, market data, and streaming clients. It imports multiple packages for full API access. ```go import ( "github.com/alpacahq/alpaca-trade-api-go/v3/alpaca" "github.com/alpacahq/alpaca-trade-api-go/v3/marketdata" "github.com/alpacahq/alpaca-trade-api-go/v3/marketdata/stream" ) tradingClient := alpaca.NewClient(alpaca.ClientOpts{}) dataClient := marketdata.NewClient(marketdata.ClientOpts{}) streamClient := stream.NewStocksClient(marketdata.SIP) ``` -------------------------------- ### Minimal Trading Client Setup Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/README.md Use this snippet for a basic trading client setup. It imports only the necessary trading package and initializes the client. ```go import "github.com/alpacahq/alpaca-trade-api-go/v3/alpaca" client := alpaca.NewClient(alpaca.ClientOpts{}) account, _ := client.GetAccount() ``` -------------------------------- ### Get Option Bars Example Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Fetches and prints aggregated price bars for a single option symbol. Ensure you have initialized the client and imported necessary packages. ```go bars, err := client.GetOptionBars("TSLA250221P00200000", marketdata.GetOptionBarsRequest{ TimeFrame: marketdata.OneDay, Start: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), End: time.Now(), TotalLimit: 30, }) for _, bar := range bars { fmt.Printf("O%.2f H%.2f L%.2f C%.2f\n", bar.Open, bar.High, bar.Low, bar.Close) } ``` -------------------------------- ### Pagination Example Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Demonstrates how to use pagination parameters to retrieve historical data in manageable chunks. ```APIDOC ## Pagination Historical data endpoints support pagination for large result sets. ### Parameters - **TotalLimit**: Total results across all pages (0 = unlimited). - **PageLimit**: Results per page (default is API default). - **NextPageToken**: Returned automatically when more results are available. - Automatic paging is enabled when limits are used. ### Example This example shows how to request up to 1000 bars, with 100 bars per page: ```go bars, err := client.GetBars("IBM", marketdata.GetBarsRequest{ TimeFrame: marketdata.OneDay, Start: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), End: time.Now(), TotalLimit: 1000, // Request up to 1000 bars PageLimit: 100, // 100 bars per page }) // Returns up to 1000 bars across multiple API calls ``` ``` -------------------------------- ### Get Asset Information (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Retrieve details about a specific asset by its symbol. This example shows how to fetch and print asset properties like symbol, exchange, tradability, and marginability. ```go package main import ( "fmt" "log" "github.com/alpacahq/alpaca-trade-api-go/v3/alpaca" ) func main() { client := alpaca.NewClient(alpaca.ClientOpts{}) asset, err := client.GetAsset("AAPL") if err != nil { log.Fatal(err) } fmt.Printf("Symbol: %s\n", asset.Symbol) fmt.Printf("Exchange: %s\n", asset.Exchange) fmt.Printf("Tradable: %v\n", asset.Tradable) fmt.Printf("Marginable: %v\n", asset.Marginable) } ``` -------------------------------- ### Get Bars with Pagination Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Example of fetching historical bars with specified total and page limits for pagination. ```go bars, err := client.GetBars("IBM", marketdata.GetBarsRequest{ TimeFrame: marketdata.OneDay, Start: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), End: time.Now(), TotalLimit: 1000, // Request up to 1000 bars PageLimit: 100, // 100 bars per page }) // Returns up to 1000 bars across multiple API calls ``` -------------------------------- ### Combine Adjustments Example Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Demonstrates how to combine multiple adjustment types using the CombineAdjustments function. ```go marketdata.CombineAdjustments(AdjustmentSplit, AdjustmentDividend) ``` -------------------------------- ### Get Account Information - Go Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves the user's account information. Ensure the client is initialized before calling. ```go func (c *Client) GetAccount() (*Account, error) func GetAccount() (*Account, error) ``` ```go account, err := client.GetAccount() if err != nil { log.Fatal(err) } fmt.Printf("Buying Power: %s\n", account.BuyingPower.String()) ``` -------------------------------- ### Create Custom TimeFrame Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/04-types.md Example of creating a custom TimeFrame using the NewTimeFrame constructor. ```go marketdata.NewTimeFrame(5, marketdata.Hour) ``` -------------------------------- ### Get Account Configurations - Go Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Fetches the current account configuration settings. This includes options like DTBP check, shorting, and trading confirmations. ```go func (c *Client) GetAccountConfigurations() (*AccountConfigurations, error) func GetAccountConfigurations() (*AccountConfigurations, error) ``` -------------------------------- ### Get All Open Positions Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves all currently open positions in the trading account. Use this to get a snapshot of your active holdings. ```go positions, err := client.GetPositions() if err != nil { log.Fatal(err) } for _, pos := range positions { fmt.Printf("%s: %s shares\n", pos.Symbol, pos.Qty.String()) } ``` -------------------------------- ### Initialize Client with Credentials Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/07-errors.md Initializes a new Alpaca client using environment variables for API key and secret, and specifies the base URL for paper trading. This is a common setup for authentication. ```go client := alpaca.NewClient(alpaca.ClientOpts{ APIKey: os.Getenv("APCA_API_KEY_ID"), APISecret: os.Getenv("APCA_API_SECRET_KEY"), BaseURL: "https://paper-api.alpaca.markets", }) if client.GetAccount() == nil { log.Fatal("authentication failed") } ``` -------------------------------- ### Combine Market Data Adjustments Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/04-types.md Example of combining multiple adjustment types for market data retrieval. ```go CombineAdjustments(AdjustmentSplit, AdjustmentDividend) ``` -------------------------------- ### Get Account Positions in Go Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Fetches and displays all current open positions for the authenticated account. Shows the symbol and quantity for each position. ```go package main import ( "fmt" "log" "github.com/alpacahq/alpaca-trade-api-go/v3/alpaca" ) func main() { client := alpaca.NewClient(alpaca.ClientOpts{}) positions, err := client.GetPositions() if err != nil { log.Fatal(err) } for _, pos := range positions { fmt.Printf("%s: %s shares\n", pos.Symbol, pos.Qty.String()) } } ``` -------------------------------- ### Get All Watchlists Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves a list of all watchlists associated with the account. No parameters are required. ```go func (c *Client) GetWatchlists() ([]Watchlist, error) func GetWatchlists() ([]Watchlist, error) ``` -------------------------------- ### Get Portfolio History - Go Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves historical portfolio values and profit/loss data. Allows specifying a period, timeframe, and end date for the history query. ```go func (c *Client) GetPortfolioHistory(req GetPortfolioHistoryRequest) (*PortfolioHistory, error) func GetPortfolioHistory(req GetPortfolioHistoryRequest) (*PortfolioHistory, error) ``` -------------------------------- ### Get Trading Calendar (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Fetches the market trading calendar, providing specific open and close times for trading days within a given date range. Useful for planning trades around market hours or holidays. ```go req := alpaca.GetCalendarRequest{ Start: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), End: time.Date(2023, 1, 31, 0, 0, 0, 0, time.UTC), } calendar, err := client.GetCalendar(req) if err != nil { log.Fatal(err) } for _, day := range calendar { fmt.Printf("%s: Open %v, Close %v\n", day.Date, day.Open, day.Close) } ``` -------------------------------- ### Handle Server Errors Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/07-errors.md Illustrates how to detect and handle server-side errors (HTTP 5xx) from the Alpaca API. The library automatically retries, but this example shows how to provide user feedback for persistent issues. ```go trades, err := client.StreamTradeUpdates(ctx, handler, req) if err != nil { if apiErr, ok := err.(*alpaca.APIError); ok && apiErr.StatusCode >= 500 { log.Println("Server error, please retry later") } } ``` -------------------------------- ### Get Market Clock Status (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves the current market clock status, including whether the market is open or closed and the times for the next opening and closing. Use this to check real-time market availability. ```go clock, err := client.GetClock() if err != nil { log.Fatal(err) } fmt.Printf("Market Open: %v\n", clock.IsOpen) ``` -------------------------------- ### Configure Stocks Client with Options Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/06-marketdata-streaming.md Demonstrates setting up a stocks client with common configuration options like trade and quote handlers, and reconnection settings. ```go client := stream.NewStocksClient(marketdata.SIP, stream.WithTradeHandler(tradeHandler), stream.WithQuoteHandler(quoteHandler), stream.WithReconnectLimit(10), stream.WithReconnectDelay(5*time.Second), ) ``` -------------------------------- ### Initialize Client with Broker Credentials Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Use this for broker partners, white-label integrations, and sandbox testing with broker-specific APIs. ```go client := alpaca.NewClient(alpaca.ClientOpts{ BrokerKey: "CK...", BrokerSecret: "...", BaseURL: "https://broker-api.alpaca.markets", }) ``` -------------------------------- ### Create Alpaca Client with Environment Variables Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Initialize the Alpaca client using default options, which will pick up credentials from environment variables. ```go client := alpaca.NewClient(alpaca.ClientOpts{}) ``` -------------------------------- ### Initialize Market Data Client with Environment Variables Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Initialize the Market Data client using environment variables for API keys and secrets. Set the BaseURL and default feed. Ensure environment variables are set before running. ```go client := marketdata.NewClient(marketdata.ClientOpts{ APIKey: os.Getenv("APCA_API_KEY_ID"), APISecret: os.Getenv("APCA_API_SECRET_KEY"), BaseURL: "https://data.alpaca.markets", Feed: marketdata.SIP, // Default to SIP feed Currency: "USD", // Default currency }) ``` -------------------------------- ### Create Alpaca Client with Explicit Configuration Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Initialize the Alpaca client by explicitly providing API key, secret key, and base URL in ClientOpts. ```go client := alpaca.NewClient(alpaca.ClientOpts{ APIKey: "your_api_key", APISecret: "your_api_secret", BaseURL: "https://paper-api.alpaca.markets", }) ``` -------------------------------- ### Configure Market Data Stream Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Set up a new stocks client with various options including logger, handlers, reconnection settings, performance tuning, and connection callbacks. ```go client := stream.NewStocksClient(marketdata.SIP, // Logger configuration stream.WithLogger(customLogger), // Handlers stream.WithTradeHandler(handleTrade), stream.WithQuoteHandler(handleQuote), stream.WithBarHandler(handleBar), // Reconnection stream.WithReconnectLimit(10), stream.WithReconnectDelay(5*time.Second), // Performance stream.WithProcessorCount(4), stream.WithBufferSize(1000), // Callbacks stream.WithConnectCallback(onConnect), stream.WithDisconnectCallback(onDisconnect), ) ``` -------------------------------- ### Initialize Client with API Key/Secret Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Use this method for personal trading, single-user applications, and development/testing. Ensure keys are not committed to version control and are rotated regularly. ```go client := alpaca.NewClient(alpaca.ClientOpts{ APIKey: "PK...", APISecret: "...", }) ``` -------------------------------- ### Initialize Market Data Client with Broker Auth Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/README.md Create a market data client using broker credentials and a sandbox URL. Ensure you use the correct base URL for production or sandbox environments. ```go client := marketdata.NewClient(marketdata.ClientOpts{ BrokerKey: "CK...", // Sandbox broker key BrokerSecret: "", // Sandbox broker secret BaseURL: "https://data.sandbox.alpaca.markets", // Sandbox url }) ``` -------------------------------- ### Get Specific Announcement Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Fetches a single announcement by its unique ID. Pass the announcement ID as a string. ```go func (c *Client) GetAnnouncement(announcementID string) (*Announcement, error) func GetAnnouncement(announcementID string) (*Announcement, error) ``` -------------------------------- ### Initialize Client with OAuth Token Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Recommended for multi-user applications, delegated access, and mobile/web apps where users authenticate via OAuth. ```go client := alpaca.NewClient(alpaca.ClientOpts{ OAuth: "Bearer your_oauth_token", }) ``` -------------------------------- ### Client Initialization Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Creates a new market data client with the provided configuration. It can be configured using environment variables or explicit options. ```APIDOC ## NewClient() ### Description Creates a new market data client with the provided configuration. ### Signature ```go func NewClient(opts ClientOpts) *Client ``` ### Parameters #### Path Parameters - **opts** (ClientOpts) - Required - Configuration options for the client. ### Returns - **`*Client`** - A new market data client instance. ### Environment Variables - `APCA_API_KEY_ID` — API key ID - `APCA_API_SECRET_KEY` — API secret key - `APCA_API_OAUTH` — OAuth token - `APCA_API_DATA_URL` — Base URL (defaults to `https://data.alpaca.markets`) ### Example ```go client := marketdata.NewClient(marketdata.ClientOpts{ APIKey: "YOUR_API_KEY", APISecret: "YOUR_API_SECRET", BaseURL: "https://data.alpaca.markets", Feed: marketdata.SIP, }) ``` ``` -------------------------------- ### Handle Missing Symbol Error Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/07-errors.md Example of how to check if an error returned from AddSymbolToWatchlist is the specific ErrSymbolMissing error. ```go _, err := client.AddSymbolToWatchlist("watchlist-id", alpaca.AddSymbolToWatchlistRequest{Symbol: ""}) if errors.Is(err, alpaca.ErrSymbolMissing) { log.Println("Must provide a symbol") } ``` -------------------------------- ### Initialize Market Data Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Creates a new market data client using provided configuration options. Supports API keys, OAuth, and custom base URLs. Environment variables can also be used for configuration. ```go client := marketdata.NewClient(marketdata.ClientOpts{ APIKey: "YOUR_API_KEY", APISecret: "YOUR_API_SECRET", BaseURL: "https://data.alpaca.markets", Feed: marketdata.SIP, }) ``` -------------------------------- ### Get Specific Watchlist Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves the details of a specific watchlist using its unique ID. Pass the watchlist ID as a string. ```go func (c *Client) GetWatchlist(watchlistID string) (*Watchlist, error) func GetWatchlist(watchlistID string) (*Watchlist, error) ``` -------------------------------- ### Get Latest Trade (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Retrieves the most recent trade for a specified stock symbol. Ensure the client is initialized before use. ```go func (c *Client) GetLatestTrade(symbol string) (*Trade, error) ``` ```go trade, err := client.GetLatestTrade("NVDA") if err != nil { log.Fatal(err) } fmt.Printf("Last trade: %.2f\n", trade.Price) ``` -------------------------------- ### Initialize Alpaca Trade Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/README.md Create a new Alpaca client instance. API keys can be provided directly or via environment variables. Set the BaseURL for paper trading. ```go package main import ( "fmt" "github.com/alpacahq/alpaca-trade-api-go/v3/alpaca" ) func main() { client := alpaca.NewClient(alpaca.ClientOpts{ // Alternatively you can set your key and secret using the // APCA_API_KEY_ID and APCA_API_SECRET_KEY environment variables APIKey: "YOUR_API_KEY", APISecret: "YOUR_API_SECRET", BaseURL: "https://paper-api.alpaca.markets", }) acct, err := client.GetAccount() if err != nil { panic(err) } fmt.Printf("%+v\n", *acct) } ``` -------------------------------- ### Get Option Trades Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Retrieves historical trade data for a specific option symbol within a given time range. ```APIDOC ## Get Option Trades ### Description Retrieves historical trade data for a specific option symbol. ### Method `GetOptionTrades` ### Parameters #### Path Parameters - **symbol** (string) - Required - The option symbol (e.g., "SPY250321C00600500"). #### Query Parameters - **Start** (time.Time) - Required - The start of the time range. - **End** (time.Time) - Required - The end of the time range. - **TotalLimit** (int) - Optional - The maximum number of trades to return. ### Request Example ```go trades, err := client.GetOptionTrades("SPY250321C00600500", marketdata.GetOptionTradesRequest{ Start: time.Now().Add(-7 * 24 * time.Hour), End: time.Now(), TotalLimit: 1000, }) // Analyze trade flow var buyVolume, sellVolume uint32 for _, trade := range trades { if trade.TakerSide == marketdata.TakerSideBuy { buyVolume += trade.Size } else if trade.TakerSide == marketdata.TakerSideSell { sellVolume += trade.Size } } fmt.Printf("Buy volume: %d, Sell volume: %d\n", buyVolume, sellVolume) ``` ### Response #### Success Response (200) A slice of trade objects. - **Trade Object**: - **Price** (float64) - The price of the trade. - **Size** (uint32) - The size of the trade. - **Timestamp** (time.Time) - The timestamp of the trade. - **Exchange** (string) - The exchange where the trade occurred. - **TakerSide** (string) - The side of the taker (e.g., `marketdata.TakerSideBuy`, `marketdata.TakerSideSell`). #### Response Example ```json [ { "price": 5.10, "size": 10, "timestamp": "2023-10-26T14:30:00Z", "exchange": "N", "taker_side": "buy" }, { "price": 5.12, "size": 5, "timestamp": "2023-10-26T14:31:00Z", "exchange": "N", "taker_side": "sell" } ] ``` ``` -------------------------------- ### Place a New Order with Go Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Submits a new order to buy or sell an asset. Ensure that Qty and Notional are mutually exclusive. Use this for market, limit, stop, and other order types. ```go func (c *Client) PlaceOrder(req PlaceOrderRequest) (*Order, error) func PlaceOrder(req PlaceOrderRequest) (*Order, error) ``` ```go qty := decimal.NewFromInt(1) order, err := client.PlaceOrder(alpaca.PlaceOrderRequest{ Symbol: "AAPL", Qty: &qty, Side: alpaca.Buy, Type: alpaca.Market, TimeInForce: alpaca.Day, }) ``` -------------------------------- ### Get Active US Equity Assets Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves a list of active US equity assets. Ensure the client is initialized before use. ```go assets, err := client.GetAssets(alpaca.GetAssetsRequest{ Status: "active", AssetClass: "us_equity", }) ``` -------------------------------- ### Get Latest Option Quotes Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Retrieves the latest quotes for multiple option symbols simultaneously. This is useful for monitoring an option chain. ```APIDOC ## Get Latest Option Quotes ### Description Retrieves the latest quotes for multiple option symbols. ### Method `GetLatestOptionQuotes` ### Parameters #### Path Parameters - **symbols** ([]string) - Required - A slice of option symbols (e.g., `["AAPL250117C00140000", "AAPL250117C00150000"]`). #### Query Parameters - **feed** (string) - Optional - The data feed to use (e.g., `marketdata.OPRA`). Defaults to OPRA if not specified. ### Request Example ```go symbols := []string{ "AAPL250117C00140000", "AAPL250117C00150000", "AAPL250117C00160000", } quotes, err := client.GetLatestOptionQuotes(symbols, marketdata.GetLatestOptionQuoteRequest{ Feed: marketdata.OPRA, }) for sym, quote := range quotes { fmt.Printf("%s: %.2f/%.2f\n", sym, quote.BidPrice, quote.AskPrice) } ``` ### Response #### Success Response (200) A map where keys are option symbols and values are quote objects. - **Quote Object**: - **BidPrice** (float64) - The bid price. - **AskPrice** (float64) - The ask price. - **Symbol** (string) - The option symbol. - **Timestamp** (time.Time) - The timestamp of the quote. #### Response Example ```json { "AAPL250117C00140000": { "bid_price": 1.20, "ask_price": 1.25, "symbol": "AAPL250117C00140000", "timestamp": "2023-10-27T10:05:00Z" }, "AAPL250117C00150000": { "bid_price": 1.50, "ask_price": 1.55, "symbol": "AAPL250117C00150000", "timestamp": "2023-10-27T10:05:00Z" } } ``` ``` -------------------------------- ### Initialize Alpaca Trading Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Creates a new Alpaca trading client instance using provided configuration options. API keys and base URL can be set directly or via environment variables. ```go client := alpaca.NewClient(alpaca.ClientOpts{ APIKey: "YOUR_API_KEY", APISecret: "YOUR_API_SECRET", BaseURL: "https://paper-api.alpaca.markets", }) ``` -------------------------------- ### Get Latest Option Quotes (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Fetches the latest quotes for multiple option symbols at once. The result is a map keyed by symbol. ```Go func (c *Client) GetLatestOptionQuotes(symbols []string, req GetLatestOptionQuoteRequest) (map[string]OptionQuote, error) ``` -------------------------------- ### Configure HTTP Proxy with Custom Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Set up an HTTP proxy for the Alpaca client by creating a custom http.Transport and http.Client. ```go proxyUrl, _ := url.Parse("http://proxy.example.com:8080") transport := &http.Transport{ Proxy: http.ProxyURL(proxyUrl), } httpClient := &http.Client{ Transport: transport, } client := alpaca.NewClient(alpaca.ClientOpts{ HTTPClient: httpClient, }) ``` -------------------------------- ### Get Alpaca Account Information Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Fetch and display details of the Alpaca trading account, including ID, buying power, and cash balance. ```go package main import ( "fmt" "log" "github.com/alpacahq/alpaca-trade-api-go/v3/alpaca" ) func main() { client := alpaca.NewClient(alpaca.ClientOpts{}) account, err := client.GetAccount() if err != nil { log.Fatal(err) } fmt.Printf("Account: %s\n", account.ID) fmt.Printf("Buying Power: %s\n", account.BuyingPower) fmt.Printf("Cash: %s\n", account.Cash) } ``` -------------------------------- ### Get Announcements Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves corporate action announcements with optional filtering by type, date, symbol, CUSIP, or date type. Requires a GetAnnouncementsRequest object. ```go func (c *Client) GetAnnouncements(req GetAnnouncementsRequest) ([]Announcement, error) func GetAnnouncements(req GetAnnouncementsRequest) ([]Announcement, error) ``` -------------------------------- ### ClientOpts Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Configuration options for initializing the Alpaca trading client. ```APIDOC ## ClientOpts ### Description Configuration options for the Alpaca trading client. ### Fields - **APIKey** (string) - API key ID for authentication. - **APISecret** (string) - API secret key for authentication. - **BrokerKey** (string) - Broker API key (alternative auth). - **BrokerSecret** (string) - Broker API secret (alternative auth). - **OAuth** (string) - OAuth bearer token (alternative auth). - **BaseURL** (string) - API endpoint base URL. Defaults to `https://api.alpaca.markets`. - **RetryLimit** (int) - Maximum number of retries on 429 (too many requests). Defaults to 3. - **RetryDelay** (time.Duration) - Delay between retry attempts. Defaults to 1 second. - **HTTPClient** (*http.Client) - Custom HTTP client for requests. Defaults to a client with a 10s timeout. ``` -------------------------------- ### Get Specific Position by Symbol Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Fetches the details for a specific stock position using its symbol. Ensure the symbol is correct to retrieve the intended position. ```go func (c *Client) GetPosition(symbol string) (*Position, error) ``` -------------------------------- ### Manage Multiple Market Data Streams Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/06-marketdata-streaming.md Illustrates how to manage multiple, independent market data streams by creating separate clients for different data feeds (e.g., SIP and IEX) and symbols. ```go // Stock stream (SIP feed) stockClient := stream.NewStocksClient(marketdata.SIP, stream.WithTradeHandler(handleStockTrade), ) stockClient.Connect(context.Background()) stockClient.SubscribeToTrades("AAPL", "MSFT") // IEX-only stream iexClient := stream.NewStocksClient(marketdata.IEX, stream.WithTradeHandler(handleIexTrade), ) iexClient.Connect(context.Background()) iexClient.SubscribeToTrades("TSLA") ``` -------------------------------- ### Get Account Activities - Go Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves account activities such as trades, dividends, and interest. Supports filtering by activity type, date range, and pagination. ```go func (c *Client) GetAccountActivities(req GetAccountActivitiesRequest) ([]AccountActivity, error) func GetAccountActivities(req GetAccountActivitiesRequest) ([]AccountActivity, error) ``` -------------------------------- ### Configure HTTP Proxy with Environment Variables Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Configure HTTP and HTTPS proxies for the Alpaca client using environment variables. ```bash export HTTP_PROXY="http://proxy.example.com:8080" export HTTPS_PROXY="https://proxy.example.com:8080" ``` -------------------------------- ### Set Alpaca Credentials via Environment Variables Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Configure API key, secret key, and base URL using environment variables for client initialization. ```bash export APCA_API_KEY_ID="your_api_key" export APCA_API_SECRET_KEY="your_api_secret" export APCA_API_BASE_URL="https://paper-api.alpaca.markets" ``` -------------------------------- ### Get Latest Quotes (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Fetches the latest quotes for a list of stock symbols. The result is a map associating each symbol with its latest quote data. ```go func (c *Client) GetLatestQuotes(symbols []string) (map[string]Quote, error) ``` -------------------------------- ### NewStocksClient Configuration Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/06-marketdata-streaming.md Demonstrates how to configure a new stock client with various options such as handlers for trades, quotes, bars, and connection callbacks, along with reconnection settings and buffer sizes. ```APIDOC ## NewStocksClient Configuration Options ### Description Allows for detailed configuration of the `NewStocksClient` to customize its behavior, including setting event handlers, logger, reconnection attempts, and buffer sizes. ### Options - `WithTradeHandler(func(Trade))` — Set trade handler - `WithQuoteHandler(func(Quote))` — Set quote handler - `WithBarHandler(func(Bar))` — Set bar handler - `WithLogger(Logger)` — Set custom logger - `WithReconnectLimit(int)` — Max reconnection attempts - `WithReconnectDelay(time.Duration)` — Delay between reconnects - `WithProcessorCount(int)` — Number of message processors - `WithBufferSize(int)` — Message buffer size - `WithConnectCallback(func())` — Called on successful connection - `WithDisconnectCallback(func())` — Called on disconnection ### Example ```go client := stream.NewStocksClient(marketdata.SIP, stream.WithTradeHandler(tradeHandler), stream.WithQuoteHandler(quoteHandler), stream.WithReconnectLimit(10), stream.WithReconnectDelay(5*time.Second), ) ``` ``` -------------------------------- ### Get Bars for a Symbol Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Retrieves aggregated price bars (OHLCV) for a single stock symbol. Supports various timeframes, adjustments, and data feeds. ```go bars, err := client.GetBars("SPY", marketdata.GetBarsRequest{ TimeFrame: marketdata.OneDay, Adjustment: marketdata.AdjustmentAll, Start: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), End: time.Now(), TotalLimit: 252, // 1 year of trading days }) for _, bar := range bars { fmt.Printf("%v: O%.2f H%.2f L%.2f C%.2f V%d\n", bar.Timestamp, bar.Open, bar.High, bar.Low, bar.Close, bar.Volume) } ``` -------------------------------- ### Get Latest Option Quote Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Retrieves the latest quote for a specific option symbol. You can specify the data feed to use, such as OPRA for real-time data. ```APIDOC ## Get Latest Option Quote ### Description Retrieves the latest quote for a specific option symbol. ### Method `GetLatestOptionQuote` ### Parameters #### Path Parameters - **symbol** (string) - Required - The option symbol (e.g., "AAPL250117C00150000"). #### Query Parameters - **feed** (string) - Optional - The data feed to use (e.g., `marketdata.OPRA`). Defaults to OPRA if not specified. ### Request Example ```go quote, err := client.GetLatestOptionQuote("AAPL250117C00150000", marketdata.GetLatestOptionQuoteRequest{ Feed: marketdata.OPRA, }) if err != nil { log.Fatal(err) } spread := quote.AskPrice - quote.BidPrice fmt.Printf("Bid: %.2f Ask: %.2f Spread: %.2f\n", quote.BidPrice, quote.AskPrice, spread) ``` ### Response #### Success Response (200) - **BidPrice** (float64) - The bid price of the option. - **AskPrice** (float64) - The ask price of the option. - **BidSize** (uint32) - The bid size. - **AskSize** (uint32) - The ask size. - **LastPrice** (float64) - The last traded price. - **LastSize** (uint32) - The size of the last trade. - **TradeCount** (uint32) - The number of trades. - **Volume** (uint32) - The total volume. - **Symbol** (string) - The option symbol. - **Timestamp** (time.Time) - The timestamp of the quote. #### Response Example ```json { "bid_price": 1.50, "ask_price": 1.55, "bid_size": 100, "ask_size": 50, "last_price": 1.52, "last_size": 25, "trade_count": 5, "volume": 1000, "symbol": "AAPL250117C00150000", "timestamp": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Context with Timeout for API Requests Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Demonstrates how to use context.WithTimeout to set a deadline for API requests, preventing indefinite waits. Ensure to defer the cancel function. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) def cancel() trades, err := client.GetTrades("AAPL", marketdata.GetTradesRequest{ Start: time.Now().Add(-24*time.Hour), End: time.Now(), }) ``` -------------------------------- ### Get Latest Option Quote (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Retrieves the most recent quote for a specific option symbol. This includes bid, ask, and last trade information. ```Go func (c *Client) GetLatestOptionQuote(symbol string, req GetLatestOptionQuoteRequest) (*OptionQuote, error) ``` -------------------------------- ### Get Latest Option Trade (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Retrieves the most recent trade for a specific option symbol. Supports specifying the feed (e.g., 'opra' or 'indicative'). ```Go func (c *Client) GetLatestOptionTrade(symbol string, req GetLatestOptionTradeRequest) (*OptionTrade, error) ``` -------------------------------- ### Client Configuration Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Defines the configuration options available for initializing the market data client. ```APIDOC ### ClientOpts #### Description Configuration options for the Market Data client. #### Fields - **APIKey** (string) - API key ID. - **APISecret** (string) - API secret key. - **BrokerKey** (string) - Broker API key. - **BrokerSecret** (string) - Broker API secret. - **OAuth** (string) - OAuth bearer token. - **BaseURL** (string) - API endpoint. Defaults to `https://data.alpaca.markets`. - **RetryLimit** (int) - Max retries on 429/500 errors. Defaults to 10. - **RetryDelay** (time.Duration) - Delay between retries. Defaults to 1 second. - **Feed** (Feed) - Default stock data feed. - **CryptoFeed** (CryptoFeed) - Default crypto data feed. - **Currency** (string) - Default currency for prices. - **HTTPClient** (*http.Client) - Custom HTTP client. - **RequestHost** (string) - Custom Host header. ``` -------------------------------- ### Tune Stream Client for Low-Bandwidth Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Adjust processor count and buffer size for low-bandwidth environments to conserve resources. ```go // Low-bandwidth environment client := stream.NewStocksClient(marketdata.SIP, stream.WithProcessorCount(1), // Single processor stream.WithBufferSize(100), // Small buffer ) ``` -------------------------------- ### Get Market Data (REST) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/10-quick-start.md Fetches the last 5 trades for a given symbol within a specified time range. Requires the marketdata client. ```go package main import ( "fmt" "log" "time" "github.com/alpacahq/alpaca-trade-api-go/v3/marketdata" ) func main() { client := marketdata.NewClient(marketdata.ClientOpts{}) now := time.Now() oneDay := now.Add(-24 * time.Hour) trades, err := client.GetTrades("AAPL", marketdata.GetTradesRequest{ Start: oneDay, End: now, Feed: marketdata.SIP, }) if err != nil { log.Fatal(err) } for _, trade := range trades[:5] { fmt.Printf("%.2f x %d @ %v\n", trade.Price, trade.Size, trade.Timestamp) } } ``` -------------------------------- ### Create Watchlist Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Creates a new watchlist with a specified name and an optional list of initial symbols. Requires a CreateWatchlistRequest object. ```go func (c *Client) CreateWatchlist(req CreateWatchlistRequest) (*Watchlist, error) func CreateWatchlist(req CreateWatchlistRequest) (*Watchlist, error) ``` -------------------------------- ### Get Latest Quote (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Retrieves the most recent quote (bid and ask prices) for a given stock symbol. This is useful for understanding the current market spread. ```go func (c *Client) GetLatestQuote(symbol string) (*Quote, error) ``` -------------------------------- ### Import Alpaca Market Data Streaming Package Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/README.md Import the `marketdata/stream` package for real-time WebSocket-based market data subscriptions, including trades, quotes, and bars. ```go import "github.com/alpacahq/alpaca-trade-api-go/v3/marketdata/stream" ``` -------------------------------- ### Get Latest Trades (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Fetches the latest trades for multiple stock symbols simultaneously. Returns a map where keys are symbols and values are their respective latest trades. ```go func (c *Client) GetLatestTrades(symbols []string) (map[string]Trade, error) ``` -------------------------------- ### Multiple Streams (Separate Clients) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/06-marketdata-streaming.md Illustrates how to manage multiple market data streams concurrently by creating separate `StocksClient` instances for different data feeds (e.g., SIP and IEX). ```APIDOC ## Multiple Streams (Separate Clients) ### Description Manages multiple market data streams simultaneously by instantiating separate `StocksClient` objects for different data feeds, such as the SIP feed and the IEX-only feed. Each client can be configured independently. ### Usage 1. Create a `StocksClient` for the SIP feed, configuring its handlers and connecting. 2. Subscribe to desired symbols for the SIP stream. 3. Create a separate `StocksClient` for the IEX feed, configuring its handlers and connecting. 4. Subscribe to desired symbols for the IEX stream. ### Example ```go // Stock stream (SIP feed) stockClient := stream.NewStocksClient(marketdata.SIP, stream.WithTradeHandler(handleStockTrade), ) stockClient.Connect(context.Background()) stockClient.SubscribeToTrades("AAPL", "MSFT") // IEX-only stream inexClient := stream.NewStocksClient(marketdata.IEX, stream.WithTradeHandler(handleIexTrade), ) inexClient.Connect(context.Background()) inexClient.SubscribeToTrades("TSLA") ``` ``` -------------------------------- ### Configure Alpaca Client with Custom HTTP Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Instantiate the Alpaca client using a custom http.Client for advanced network configurations like timeouts and connection pooling. ```go httpClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 10, DialContext: (&net.Dialer{ Timeout: 5 * time.Second, }).DialContext, }, } client := alpaca.NewClient(alpaca.ClientOpts{ APIKey: "...", APISecret: "...", HTTPClient: httpClient, }) ``` -------------------------------- ### Get Quotes for a Symbol Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Fetches quote data (bid/ask snapshots) for a single stock symbol. Allows specifying time range, limits, feed, and sort order. ```go quotes, err := client.GetQuotes("TSLA", marketdata.GetQuotesRequest{ Start: time.Now().Add(-1 * time.Hour), End: time.Now(), TotalLimit: 50, }) for _, q := range quotes { fmt.Printf("Bid: %.2f @ %d / Ask: %.2f @ %d\n", q.BidPrice, q.BidSize, q.AskPrice, q.AskSize) } ``` -------------------------------- ### Get Trades for a Symbol Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Retrieves trades for a single stock symbol within a specified time range. Supports filtering by date, limit, feed, and sort order. ```go now := time.Now() start := now.Add(-24 * time.Hour) trades, err := client.GetTrades("AAPL", marketdata.GetTradesRequest{ Start: start, End: now, TotalLimit: 100, Feed: marketdata.SIP, }) if err != nil { log.Fatal(err) } for _, trade := range trades { fmt.Printf("%.2f @ %d\n", trade.Price, trade.Size) } ``` -------------------------------- ### NewClient() Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Creates a new Alpaca trading client with the provided configuration options. It can utilize environment variables for authentication and base URL if not explicitly provided. ```APIDOC ## NewClient() ### Description Creates a new Alpaca trading client with the provided configuration options. ### Signature ```go func NewClient(opts ClientOpts) *Client ``` ### Parameters #### Path Parameters This function does not have path parameters. #### Query Parameters This function does not have query parameters. #### Request Body This function does not have a request body. ### Returns - `*Client` — A new trading client instance. ### Environment Variables - `APCA_API_KEY_ID` — API key ID (used if `opts.APIKey` is empty) - `APCA_API_SECRET_KEY` — API secret key (used if `opts.APISecret` is empty) - `APCA_API_OAUTH` — OAuth token (used if `opts.OAuth` is empty) - `APCA_API_BASE_URL` — Base URL (defaults to `https://api.alpaca.markets` if not set) ### Example ```go client := alpaca.NewClient(alpaca.ClientOpts{ APIKey: "YOUR_API_KEY", APISecret: "YOUR_API_SECRET", BaseURL: "https://paper-api.alpaca.markets", }) ``` ``` -------------------------------- ### Create New Stocks Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/06-marketdata-streaming.md Creates a new WebSocket client for streaming stock market data. Specify the data feed and optional handlers for trades, quotes, etc. ```go client := stream.NewStocksClient(marketdata.SIP, stream.WithTradeHandler(func(t stream.Trade) { fmt.Printf("%s: %.2f\n", t.Symbol, t.Price) }), ) ``` -------------------------------- ### Get Latest Option Trades (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/05-options-marketdata.md Fetches the latest trades for multiple option symbols simultaneously. Returns a map where keys are symbols and values are the latest trades. ```Go func (c *Client) GetLatestOptionTrades(symbols []string, req GetLatestOptionTradeRequest) (map[string]OptionTrade, error) ``` -------------------------------- ### Connect Stocks Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/06-marketdata-streaming.md Establishes a WebSocket connection to the stream server. This should only be called once. The connection will automatically attempt to reestablish on errors. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defunc() { cancel() } err := client.Connect(ctx) if err != nil { log.Fatal("Failed to connect:", err) } ``` -------------------------------- ### Get USTreasuries() - Go Client Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/01-trading-client.md Retrieves available US Treasury securities. Requires a GetUSTreasuriesRequest object to specify filtering options such as subtype, bond status, CUSIPs, and ISINs. ```go func (c *Client) GetUSTreasuries(req GetUSTreasuriesRequest) ([]USTreasury, error) ``` ```go func GetUSTreasuries(req GetUSTreasuriesRequest) ([]USTreasury, error) ``` -------------------------------- ### ClientOpts Structure Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/09-configuration.md Defines the structure for configuring the Market Data client. Use this to set API keys, secrets, data endpoints, retry logic, default feeds, and currency. ```go type ClientOpts struct { APIKey string APISecret string BrokerKey string BrokerSecret string OAuth string BaseURL string RetryLimit int RetryDelay time.Duration Feed Feed // Default stock feed CryptoFeed CryptoFeed // Default crypto feed Currency string // Default currency for prices HTTPClient *http.Client RequestHost string // Custom Host header } ``` -------------------------------- ### Get Latest Bars (Go) Source: https://github.com/alpacahq/alpaca-trade-api-go/blob/master/_autodocs/03-marketdata-client.md Fetches the latest OHLC bars for multiple stock symbols. The function returns a map where keys are symbols and values are their corresponding latest bars. ```go func (c *Client) GetLatestBars(symbols []string) (map[string]Bar, error) ```