Golang

 

Introduction

In today’s digital world, having access to real-time stock data is essential for making informed investment decisions.
With the help of APIs, we can easily fetch and display live stock prices. This tutorial will show you how to write a simple
Go program to track and display stock prices using a public API.

Objective

The objective of this tutorial is to teach you how to:

  • Use a public stock price API to fetch live stock data
  • Parse JSON data in Go
  • Display real-time stock prices on the console

Code Example


package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type StockPrice struct {
    Symbol    string  `json:"symbol"`
    Company   string  `json:"companyName"`
    Price     float64 `json:"latestPrice"`
    Currency  string  `json:"currency"`
}

func getStockPrice(symbol string) (StockPrice, error) {
    url := fmt.Sprintf("https://cloud.iexapis.com/stable/stock/%s/quote?token=YOUR_API_KEY", symbol)
    resp, err := http.Get(url)
    if err != nil {
        return StockPrice{}, err
    }
    defer resp.Body.Close()

    var stock StockPrice
    if err := json.NewDecoder(resp.Body).Decode(&stock); err != nil {
        return StockPrice{}, err
    }

    return stock, nil
}

func main() {
    var symbol string
    fmt.Println("Enter stock symbol (e.g., AAPL for Apple):")
    fmt.Scanln(&symbol)

    stock, err := getStockPrice(symbol)
    if err != nil {
        log.Fatalf("Error fetching stock price: %v", err)
    }

    fmt.Printf("Stock Symbol: %s\n", stock.Symbol)
    fmt.Printf("Company: %s\n", stock.Company)
    fmt.Printf("Price: %.2f %s\n", stock.Price, stock.Currency)
}
        

Explanation of the Program Structure

The Go program is simple and efficient for tracking and displaying stock prices. Here is a breakdown of its structure:

  • Imports: The program imports necessary Go packages like net/http for making HTTP requests, encoding/json for parsing JSON data, and fmt for formatting and printing output.
  • StockPrice struct: This struct defines the fields that will hold stock data such as symbol, companyName, latestPrice, and currency.
  • getStockPrice function: This function takes a stock symbol as input, constructs an API request, and fetches the stock data from the API. It returns the data as a StockPrice object.
  • main function: The program prompts the user to enter a stock symbol (e.g., AAPL for Apple), fetches the stock price using the getStockPrice function, and then displays the result.

How to Run the Program

  1. Ensure you have Go installed on your system. You can download it from Go Downloads.
  2. Sign up for an API key from IEX Cloud or any other stock price API provider. Replace YOUR_API_KEY in the code with your actual API key.
  3. Save the code to a file named stock_tracker.go.
  4. Open your terminal and navigate to the folder where you saved the file.
  5. Run the program using the following command:
    go run stock_tracker.go
  6. Enter a stock symbol when prompted, and the program will display the latest stock price for that symbol.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)