alpaca-trade-api-go

repository·master·Indexed 19 days ago

https://github.com/alpacahq/alpaca-trade-api-go

A Go library providing access to Alpaca's trading and market data APIs. It supports RESTful requests and real-time streaming interfaces for stocks, crypto, options, and news. The library includes functionality for managing accounts, placing orders, and implementing trading strategies such as Mean Reversion and Long-Short Equity.

Tokens
2.8K
Snippets
8
Records
14
Agent score
65%

What's inside alpaca-trade-api-go

  1. Authenticate with the Alpaca API

    master

    The Alpaca API requires an API key ID and a secret key. You can provide these to the SDK in two ways:

    1. Environment Variables

    Set the following environment variables in your shell:

    • APCA_API_KEY_ID
    • APCA_API_SECRET_KEY
    • APCA_API_BASE_URL (optional, used to specify the base URL, e.g., for paper trading)
    export APCA_API_KEY_ID=xxxxx
    export APCA_API_SECRET_KEY=yyyyy
    export APCA_API_BASE_URL=https://paper-api.alpaca.markets

    2. Code Configuration

    Pass the credentials directly into the alpaca.ClientOpts struct when initializing a new client.

    client := alpaca.NewClient(alpaca.ClientOpts{
        APIKey:    "YOUR_API_KEY",
        APISecret: "YOUR_API_SECRET",
        BaseURL:   "https://paper-api.alpaca.markets",
    })
  2. Run example trading algorithms

    master

    The examples in this repository are simple Go executables designed to connect to the Alpaca paper-trading API. To use them, you must install the Alpaca Go package, then build and run the specific Go executable.

    Authentication

    You can authenticate the scripts using one of two methods:

    1. Hardcoded Parameters: Replace the API_KEY and API_SECRET variables at the top of the specific example file with your credentials from the Alpaca dashboard.
    2. Environment Variables: Set the following environment variables in your shell, and the scripts will automatically detect them:
      • APCA_API_KEY_ID
      • APCA_API_SECRET_KEY
    WARNING

    The performance of these scripts in a real trading environment is not guaranteed. These are provided for educational purposes to demonstrate SDK usage and are not financial advice.

  3. How market data streaming clients work

    master

    Alpaca streaming clients follow a specific lifecycle and architectural pattern:

    1. Construction: Use NewStocksClient, NewCryptoClient, etc., to create a client instance with desired handlers.
    2. Connection: Call Connect(ctx). This starts internal goroutines for:
      • connPinger: Keeps the connection alive.
      • connReader: Reads raw messages from the socket.
      • connWriter: Sends subscription changes to the server.
      • messageProcessor: Deserializes and dispatches messages to your handlers.
    3. Subscription: Once connected, use SubscribeTo... or UnsubscribeFrom... methods to start receiving specific data.
    4. Termination: If the connection fails irrecoverably or the context is cancelled, the client enters a terminated state. You must monitor Terminated() to know when to clean up.
  4. Use the Trading REST API

    master

    To interact with the Alpaca trading REST endpoints (e.g., managing accounts), initialize an alpaca.Client and call its methods. Ensure you use the correct BaseURL for your environment (e.g., https://paper-api.alpaca.markets for paper trading).

    package main
    
    import (
    	"fmt"
    
    	"github.com/alpacahq/alpaca-trade-api-go/v3/alpaca"
    )
    
    func main() {
    	client := alpaca.NewClient(alpaca.ClientOpts{
    		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)
    }
  5. Stream trade updates

    master

    You can listen to real-time trade updates using alpaca.StreamTradeUpdatesInBackground. This function runs in the background with unlimited reconnection logic. You provide a handler function that accepts an alpaca.TradeUpdate object.

    // Listen to trade updates in the background (with unlimited reconnect)
    alpaca.StreamTradeUpdatesInBackground(context.TODO(), func(tu alpaca.TradeUpdate) {
    	log.Printf("TRADE UPDATE: %+v\n", tu)
    })
    
    // Send a single AAPL order
    qty := decimal.NewFromInt(1)
    if _, err := alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
    	Symbol:      "AAPL",
    	Qty:         &qty,
    	Side:        "buy",
    	Type:        "market",
    	TimeInForce: "day",
    }); err != nil {
    	log.Fatalf("failed place order: %v", err)
    }
    log.Println("order sent")
    
    select {}
  6. Mean Reversion strategy pattern

    master

    The Mean Reversion example demonstrates a strategy based on the theory that stock prices will eventually correct to their mean (running average).

    Logic Flow:

    1. Calculate a running average of a stock price (e.g., a 20-minute average for "AAPL").
    2. Execute Long: If the current stock price is below the running average.
    3. Execute Short/Sell: If the current stock price is above the running average.
    4. Re-evaluate: The algorithm re-calculates the mean and checks position requirements every minute.
  7. Long-Short Equity strategy pattern

    master

    The Long-Short Equity example demonstrates a strategy that ranks a universe of stocks and takes opposing positions based on those rankings.

    Logic Flow:

    1. Ranking: Uses the percent change in stock price over the past 10 minutes to rank a universe of stocks.
    2. Positioning: Implements a 130/30 percent equity split (130% equity for longs, 30% for shorts).
    3. Selection: Selects the top 25% of ranked stocks to long and the bottom 25% to short.
    4. Execution: Purchases equal quantities across the long bucket and equal quantities across the short bucket.
    5. Handling Constraints: If certain stocks cannot be shorted, the algorithm uses the leftover equity to increase short positions in stocks that are available to be shorted.
    6. Re-evaluate: Re-ranks stocks and adjusts positions every minute.
  8. Authenticate with the Broker API

    master

    When working with Broker APIs, use BrokerKey and BrokerSecret instead of standard API keys. You must also ensure you are using the correct Broker-specific base URLs.

    client := marketdata.NewClient(marketdata.ClientOpts{
    	BrokerKey:    "CK...",                               // Sandbox broker key
    	BrokerSecret: "<your secret>",                       // Sandbox broker secret
    	BaseURL:      "https://data.sandbox.alpaca.markets", // Sandbox url
    })
  9. Stream Crypto, Options, or News data

    master

    The library provides specialized clients for different asset classes, each with its own set of handlers and configuration options:

    • NewCryptoClient(feed marketdata.CryptoFeed, opts ...CryptoOption): For cryptocurrency data. Supports handlers for trades, quotes, bars, orderbooks, and futures pricing.
    • NewOptionClient(feed marketdata.OptionFeed, opts ...OptionOption): For options data. Supports handlers for trades and quotes.
    • NewNewsClient(opts ...NewsOption): For news stream data. Supports a newsHandler.
  10. Monitor client termination via Terminated()

    master

    The Terminated() method returns a read-only channel (<-chan error). This channel is used to detect when the client has stopped running due to an irrecoverable error or when the connection process has exhausted its retry limit.

    • When the client terminates, the channel is closed.
    • If the termination was caused by an error, the error is sent on the channel before it is closed.
    // Monitor termination in a separate goroutine
    go func() {
        if err := <-client.Terminated(); err != nil {
            fmt.Printf("Client terminated with error: %v\n", err)
        } else {
            fmt.Println("Client terminated gracefully")
        }
    }()