You've successfully subscribed to Alpaca Learn | Developer-First API for Crypto and Stocks
Great! Next, complete checkout for full access to Alpaca Learn | Developer-First API for Crypto and Stocks
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.
Search
Trading API

How to Access Alpaca Trading API and Market Data API Using Golang

Oluebube Princess Egbuna
Oluebube Princess Egbuna

This article will teach you how to use the Alpaca library for the Golang programming language. Golang is a fast, easy-to-learn and rapidly growing programming language that is often used to build scalable server-side applications. If you’re building the server-side component of a trading application, the alpaca-trade-api-go would be an excellent library to consider using.

This tutorial assumes that you have an Alpaca account and a basic knowledge of the Golang programming language. If you do not have an Alpaca account, you can sign up here and use the Paper API for free. You'll also need to download and set up the Golang compiler on your computer.

Creating a Golang Project

First, create a directory to store your project files.

Launch your computer’s terminal, as you will be executing go commands from the terminal as you follow the hands-on steps to build your application.  

Execute the two commands below through the launched terminal to create a directory ( alpaca-golang-demo) for storing the Golang project files and change (cd) into the alpaca-golang-demo directory.

mkdir alpaca-golang-demo && cd alpaca-golang-demo 

Next, execute the mod command below to initialize the Golang project’s module. The command will create a go.mod file in the project root directory to track the libraries installed within the project.

go mod init alpaca-golang-demo  

Open the alpaca-golang-demo project in your preferred Integrated Development Environment (IDE) for building Golang applications.

Create a main.go file that will contain the main package for the Golang application.

Add the boilerplate Golang code below into the main.go file to build the main package.

package main

import "fmt"

func main () {
  fmt.Println("Hello World, \n Welcome to Alpaca Golang Demo!")
}

When compiled with the go run command, the Go code below will print out a string with the value of “Hello World, Welcome to Alpaca Golang Demo!”

Building the Golang Application

Up to this point, you have built a Golang application that prints out a string value. You will now proceed to implement the logic of the Golang application to access the Alpaca Trade API.

Installing Program Libraries

The alpacahq/alpaca-trade-api-go and godotenv libraries are not a part of the Golang standard library. Hence, they need to be installed in your Golang project before they can be used.

Execute the command below to install the two external libraries. The alpacahq/alpaca-trade-api-go library will be used to access the Alpaca Trading API, while godotenv will be used to securely access your Alpaca keys from environment variables.

go get go get -v github.com/joho/godotenv github.com/alpacahq/alpaca-trade-api-go/v2/alpaca 

Let’s proceed to use the godotenv library in the next section.

Storing Alpaca API Keys as Environment Credentials

Hard coding your Alpaca API keys in your project file to access the Alpaca API is not a recommended practice. When pushed to a public repository, the API key values will be leaked.

To prevent this, you will store the API keys as environment variables and access them through the godotenv library that was installed.  

Create a file named .env and add your Alpaca Access ID and Access Secret credentials into the file in the format below:

Note: Replace the ACCESS_ID and ACCESS_SECRET placeholders with their corresponding Alpaca API credentials.

ALPACA_ACCESS_ID=ACCESS_IDALPACA_SECRET_KEY=SECRET_KEY

Placing a Single Trade Order

With the Alpaca library installed and API keys stored securely from the two previous sections, your Golang project is ready to establish a connection with the Alpaca trading API through the alpacahq/alpaca-trade-api-go library.

Open the main.go file in your Golang IDE as you will modify it through the following steps

  1. Add the content of the code block below to include the libraries that will be used in the main package.
import (
  "fmt"
  "github.com/alpacahq/alpaca-trade-api-go/v2/alpaca"
  "github.com/joho/godotenv"
  "log"
  "os"
)

2. Add the code below into the body of the main function to load the Alpaca API keys in the .env file as environment variables through the godotenv library.


func main () {
  fmt.Println("Hello World, \nWelcome to Alpaca Golang Demo!")

envErr := godotenv.Load()
if envErr != nil {
  log.Fatal("Error loading Alpaca API keys from .env file")
}
  
}

3. Add the code below into the existing codes in the main function body. The code will create a client to establish a connection with Alpaca through the endpoint specified in the BaseUrl field.

Note that the value of the BaseUrl field below is the endpoint of the Alpaca Paper API. This ensures that no charges will occur while you develop your Golang application.

func main () {
  fmt.Println("Hello World, \nWelcome to Alpaca Golang Demo!")
  err := godotenv.Load()
  if err != nil {
     log.Fatal("Error loading Alpaca API keys from .env file")
  }

  alpacaClient := alpaca.NewClient(alpaca.ClientOpts{
     ApiKey:    os.Getenv("ALPACA_ACCESS_ID"),
     ApiSecret: os.Getenv("ALPACA_SECRET_KEY"),
     BaseURL:   "https://paper-api.alpaca.markets",
  })  
}


4. Add the code below into the main function. The highlighted code uses the PlaceOrder method on the alpacaClient to place an order of five Amazon (AMZN) stocks.

func main () {
  // existing code 

  symbol := "AMZN"
  qty := decimal.NewFromInt(5)

  order, err := alpacaClient.PlaceOrder(alpaca.PlaceOrderRequest{
     AssetKey:    &symbol,
     Qty:         &qty,
     Side:        "buy",
     Type:        "market",
     TimeInForce: "day",
  })

  if err != nil {
     log.Fatalf("failed place order: %v", err)
  }

  fmt.Printf("Your %v order of %v was placed successully at %v", order.Qty, order.Symbol,  order.CreatedAt)
}


With the steps completed, execute the command below to run the alpaca-golang-demo program.

go run main.go 

If the order was successful, a string containing the order details will be printed out as the last result of the program.

Confirm that the order placed from your Golang application was successful by navigating to the dashboard overview page of your Alpaca dashboard.

You will find the most recent order from the alpaca-golang-demo program listed in the order history.

Congratulations! You've successfully built a Golang program that uses the Alpaca library.

Within this tutorial, you used the PlaceOrders method to place an order against the Paper API. You can go through the documentation of the alpacahq/alpaca-trade-api-go library to learn about other available methods. The documentation also contains code examples on how to stream market data using the alpacahq/alpaca-trade-api-go library.


Please note that this article is for general informational purposes only. All screenshots are for illustrative purposes only. Alpaca does not recommend any specific securities or investment strategies.

Alpaca does not prepare, edit, or endorse Third Party Content. Alpaca does not guarantee the accuracy, timeliness, completeness or usefulness of Third Party Content, and is not responsible or liable for any content, advertising, products, or other materials on or available from third party sites.

All investments involve risk and the past performance of a security, or financial product does not guarantee future results or returns.There is no guarantee that any investment strategy will be successful in achieving its investment objectives. Diversification does not ensure a profit or protection against a loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.

Cryptocurrency is highly speculative in nature, involves a high degree of risks, such as volatile market price swings, market manipulation, flash crashes, and cybersecurity risks. Cryptocurrency is not regulated or is lightly regulated in most countries. Cryptocurrency trading can lead to large, immediate and permanent loss of financial value. You should have appropriate knowledge and experience before engaging in cryptocurrency trading. For additional information, please click here.

Please see alpaca.markets and Alpaca’s Disclosure Library for more information.







Trading APIMarket Data APICommunity Examples