Skip to content

Concurrency

Igor Sazonov edited this page Jul 12, 2026 · 1 revision

The coinglass-go SDK is designed to be fully thread-safe. A single *coinglass.Client instance can (and should) be shared across multiple goroutines.

You do not need to create a new client for every request or every goroutine.

Context Usage

Every service method takes a context.Context as its first argument. This allows you to enforce per-request timeouts, cancel in-flight requests, and cleanly shut down concurrent workers.

If a context is canceled while the SDK is sleeping between retry attempts (due to a 429 Rate Limit), the sleep is interrupted immediately and the context error is returned.

Example: Fetching Multiple Symbols Concurrently

Here is an example of using a single client to fetch data for multiple symbols concurrently using a sync.WaitGroup.

package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	coinglass "github.com/tigusigalpa/coinglass-go"
)

func main() {
	client := coinglass.NewClient("YOUR_API_KEY",
		coinglass.WithTimeout(15*time.Second),
		coinglass.WithRetry(3, time.Second),
	)

	ctx := context.Background()
	symbols := []string{"BTC", "ETH", "SOL"}
	
	var wg sync.WaitGroup
	var mu sync.Mutex
	results := make(map[string]int)

	for _, symbol := range symbols {
		wg.Add(1)
		go func(sym string) {
			defer wg.Done()
			
			// Safe to use client concurrently
			oi, err := client.Futures.OpenInterestHistory(ctx, &coinglass.OIHistoryParams{
				Symbol:   sym,
				Interval: "1d",
				Limit:    coinglass.IntPtr(30),
			})
			
			if err != nil {
				log.Printf("%s: error: %v\n", sym, err)
				return
			}
			
			// Protect the map write
			mu.Lock()
			results[sym] = len(oi)
			mu.Unlock()
			
		}(symbol)
	}

	// Wait for all goroutines to finish
	wg.Wait()

	for _, symbol := range symbols {
		fmt.Printf("%s: %d open-interest points fetched\n", symbol, results[symbol])
	}
}

Clone this wiki locally