A minimal Go SDK for real-time OHLCV market data from TradingView.
- Stream - Persistent WebSocket connections for real-time candle updates
- Fetch - One-shot requests for historical candle data
- Zero external dependencies (except
gorilla/websocket) - In-memory candle buffer with configurable history size
- Automatic reconnection with exponential backoff
- Rate limiting with token bucket algorithm
go get github.com/gopher-lab/tradingview-gopackage main
import (
"fmt"
"log"
"time"
tv "github.com/gopher-lab/tradingview-go"
)
func main() {
// Create a streamer
streamer := tv.NewStreamer(nil, tv.DefaultConfig())
defer streamer.Close()
// Subscribe to BTC 1-hour candles
err := streamer.Subscribe("BTCUSDT", "1H", func(c tv.Candle) {
fmt.Printf("BTC: $%.2f (vol: %.2f)\n", c.Close, c.Volume)
})
if err != nil {
log.Fatal(err)
}
// Let it run
time.Sleep(time.Hour)
}package main
import (
"context"
"fmt"
"log"
tv "github.com/gopher-lab/tradingview-go"
)
func main() {
// Create a fetcher
fetcher := tv.NewFetcher(nil, tv.DefaultConfig())
// Fetch 100 daily candles
data, err := fetcher.Fetch(context.Background(), "BTCUSDT", "1D", 100)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Got %d candles for %s\n", len(data.Candles), data.Symbol)
for _, c := range data.Candles {
fmt.Printf(" %d: O=%.2f H=%.2f L=%.2f C=%.2f V=%.2f\n",
c.Timestamp, c.Open, c.High, c.Low, c.Close, c.Volume)
}
}// Candle represents a single OHLCV candlestick
type Candle struct {
Timestamp int64 // Unix timestamp
Open float64
High float64
Low float64
Close float64
Volume float64
}
// ChartData contains candles for a symbol/resolution
type ChartData struct {
Symbol string
Resolution string
Candles []Candle
Timestamp int64
}
// Config holds all configuration
type Config struct {
MaxConnections int // Max WebSocket connections
ConnectionLifetime time.Duration // How long to keep connections
ReconnectDelay time.Duration // Delay before reconnecting
HeartbeatTimeout time.Duration // Max time without heartbeat
CandleHistory int // Number of candles to keep
RateLimit float64 // Requests per second
BurstCapacity float64 // Max burst capacity
RequestTimeout time.Duration // Fetch timeout
MaxRetries int // Max retry attempts
}// Create a streamer
streamer := tv.NewStreamer(logger, config)
// Subscribe to real-time updates
streamer.Subscribe("BTCUSDT", "1H", func(c tv.Candle) {
// Called for each new/updated candle
})
// Get cached candles
candles := streamer.GetCandles("BTCUSDT", "1H")
// Get latest candle
latest := streamer.GetLatestCandle("BTCUSDT", "1H")
// Get connection stats
stats := streamer.Stats()
// Unsubscribe
streamer.Unsubscribe("BTCUSDT", "1H")
// Close all connections
streamer.Close()// Create a fetcher
fetcher := tv.NewFetcher(logger, config)
// Fetch candles (one-shot)
data, err := fetcher.Fetch(ctx, "BTCUSDT", "1D", 100)Implement the Logger interface to inject your own logger:
type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
// Pass nil to use the built-in NoopLogger
streamer := tv.NewStreamer(nil, config)Supported timeframe resolutions:
| Friendly | TradingView |
|---|---|
1M |
1 |
5M |
5 |
15M |
15 |
30M |
30 |
1H |
60 |
2H |
120 |
4H |
240 |
1D |
D |
1W |
W |
1MN |
M |
You can use either format: "1H" or "60".
Symbols are automatically formatted for TradingView:
// These are equivalent:
streamer.Subscribe("BTCUSDT", "1H", nil)
streamer.Subscribe("BINANCE:BTCUSDT", "1H", nil)Common exchanges: BINANCE, BYBIT, COINBASE, FTX, KRAKEN
┌─────────────────────────────────────────────────┐
│ tradingview-go │
├─────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Streamer │ │ Fetcher │ │
│ │ │ │ │ │
│ │ - Subscribe │ │ - Fetch │ │
│ │ - GetCandles│ │ │ │
│ │ - Stats │ └──────┬──────┘ │
│ └──────┬──────┘ │ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────────────────────────────┐ │
│ │ WebSocket Client │ │
│ │ │ │
│ │ - Connection management │ │
│ │ - Protocol encoding/decoding │ │
│ │ - Heartbeat handling │ │
│ └──────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────┐ │
│ │ TradingView Servers │ │
│ └──────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────┘
tradingview-go/
├── tradingview.go # Package documentation
├── types.go # Candle, ChartData, etc.
├── config.go # Configuration
├── logger.go # Logger interface
├── protocol.go # TradingView protocol encoding
├── client.go # WebSocket connection
├── backoff.go # Exponential backoff
├── ratelimiter.go # Token bucket rate limiter
├── fetch.go # Fetcher (one-shot)
├── stream.go # Streamer (persistent)
├── go.mod
└── README.md
MIT