golang股票外汇加密货币市场数据获取插件库go-finnhub的使用

golang股票外汇加密货币市场数据获取插件库go-finnhub的使用

简介

go-finnhub是一个简单易用的Go语言客户端库,用于从finnhub.io获取股票、外汇和加密货币数据。它可以访问来自60多个股票交易所、10家外汇经纪商和15+加密货币交易所的实时市场数据。

安装

go get github.com/m1/go-finnhub

使用示例

首先在finnhub.io注册获取API令牌。

基础示例代码

package main

import (
	"fmt"
	"log"
	
	"github.com/m1/go-finnhub"
)

func main() {
	// 初始化客户端,替换"your_token_here"为你的API令牌
	c := finnhub.NewClient("your_token_here")

	// 股票数据示例
	// 获取苹果公司(AAPL)的简介
	company, err := c.Stock.GetProfile("AAPL")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("苹果公司简介: %+v\n", company)

	// 获取苹果公司的CEO信息
	ceo, err := c.Stock.GetCEO("AAPL")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("苹果公司CEO: %s\n", ceo)

	// 获取苹果公司的股票推荐信息
	recommendation, err := c.Stock.GetRecommendations("AAPL")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("苹果公司股票推荐: %+v\n", recommendation)

	// 获取苹果公司的日K线数据
	candle, err := c.Stock.GetCandle("AAPL", finnhub.CandleResolutionDay, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("苹果公司日K线数据: %+v\n", candle)

	// 加密货币数据示例
	// 获取Binance交易所的BEAM/USDT交易对的月K线数据
	cryptoCandle, err := c.Crypto.GetCandle("BINANCE:BEAMUSDT", finnhub.CandleResolutionMonth, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("BEAM/USDT月K线数据: %+v\n", cryptoCandle)

	// 外汇数据示例
	// 获取OANDA的黄金兑英镑(XAU_GBP)的月K线数据
	forexCandle, err := c.Forex.GetCandle("OANDA:XAU_GBP", finnhub.CandleResolutionMonth, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("XAU/GBP月K线数据: %+v\n", forexCandle)

	// 新闻数据示例
	// 获取加密货币类新闻
	news, err := c.News.Get(&finnhub.NewsParams{Category: finnhub.NewsCategoryCrypto})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("加密货币新闻: %+v\n", news)
}

功能说明

股票功能

  • GetProfile(symbol string) - 获取公司简介
  • GetCEO(symbol string) - 获取公司CEO信息
  • GetRecommendations(symbol string) - 获取股票推荐
  • GetPriceTarget(symbol string) - 获取价格目标
  • GetOptionChain(symbol string) - 获取期权链
  • GetPeers(symbol string) - 获取同行公司
  • GetEarnings(symbol string) - 获取收益数据
  • GetCandle(symbol string, resolution CandleResolution, params *CandleParams) - 获取K线数据
  • GetExchanges() - 获取交易所列表
  • GetSymbols(exchange string) - 获取交易所的股票代码
  • GetGradings(params *GradingParams) - 获取评级数据

加密货币功能

  • GetExchanges() - 获取加密货币交易所
  • GetSymbols(exchange string) - 获取交易所的交易对
  • GetCandle(symbol string, resolution CandleResolution, params *CandleParams) - 获取K线数据

外汇功能

  • GetExchanges() - 获取外汇交易所
  • GetSymbols(exchange string) - 获取交易所的货币对
  • GetCandle(symbol string, resolution CandleResolution, params *CandleParams) - 获取K线数据

新闻功能

  • Get(params *NewsParams) - 获取新闻
  • GetCompany(symbol string) - 获取公司相关新闻
  • GetSentiment(symbol string) - 获取情绪分析

这个库提供了访问finnhub.io API的完整功能,可以方便地集成到Go应用程序中获取金融市场数据。


更多关于golang股票外汇加密货币市场数据获取插件库go-finnhub的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang股票外汇加密货币市场数据获取插件库go-finnhub的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


go-finnhub 使用指南

go-finnhub 是一个用于访问 Finnhub API 的 Golang 客户端库,可以获取股票、外汇、加密货币等市场数据。Finnhub 提供实时市场数据、财务数据、新闻等金融信息。

安装

go get github.com/Finnhub-Stock-API/finnhub-go

初始化客户端

首先需要获取 Finnhub API 密钥,可以在 Finnhub 官网 注册获取。

package main

import (
	"context"
	"fmt"
	"os"

	finnhub "github.com/Finnhub-Stock-API/finnhub-go"
)

func main() {
	// 从环境变量获取API密钥
	apiKey := os.Getenv("FINNHUB_API_KEY")
	if apiKey == "" {
		panic("FINNHUB_API_KEY environment variable not set")
	}

	// 创建配置
	cfg := finnhub.NewConfiguration()
	cfg.AddDefaultHeader("X-Finnhub-Token", apiKey)
	
	// 创建客户端
	finnhubClient := finnhub.NewAPIClient(cfg).DefaultApi
	ctx := context.Background()
	
	// 在这里调用各种API方法
}

常用功能示例

1. 获取股票实时报价

func getQuote(finnhubClient *finnhub.DefaultApiService, ctx context.Context, symbol string) {
	quote, _, err := finnhubClient.Quote(ctx, symbol)
	if err != nil {
		fmt.Printf("Error getting quote: %v\n", err)
		return
	}
	
	fmt.Printf("Current price of %s: %.2f\n", symbol, *quote.C)
	fmt.Printf("High price today: %.2f\n", *quote.H)
	fmt.Printf("Low price today: %.2f\n", *quote.L)
	fmt.Printf("Open price: %.2f\n", *quote.O)
	fmt.Printf("Previous close: %.2f\n", *quote.Pc)
}

2. 获取公司基本信息

func getCompanyProfile(finnhubClient *finnhub.DefaultApiService, ctx context.Context, symbol string) {
	profile, _, err := finnhubClient.CompanyProfile2(ctx, &finnhub.CompanyProfile2Opts{
		Symbol: optional.NewString(symbol),
	})
	if err != nil {
		fmt.Printf("Error getting company profile: %v\n", err)
		return
	}
	
	fmt.Printf("Company Name: %s\n", *profile.Name)
	fmt.Printf("Ticker: %s\n", *profile.Ticker)
	fmt.Printf("Exchange: %s\n", *profile.Exchange)
	fmt.Printf("IPO Date: %s\n", *profile.Ipo)
	fmt.Printf("Market Cap: %.2f\n", *profile.MarketCapitalization)
	fmt.Printf("Share Outstanding: %.2f\n", *profile.ShareOutstanding)
	fmt.Printf("Website: %s\n", *profile.Weburl)
}

3. 获取加密货币汇率

func getCryptoExchangeRate(finnhubClient *finnhub.DefaultApiService, ctx context.Context, base string, target string) {
	rate, _, err := finnhubClient.CryptoExchanges(ctx)
	if err != nil {
		fmt.Printf("Error getting crypto exchanges: %v\n", err)
		return
	}
	
	fmt.Println("Available crypto exchanges:")
	for _, exchange := range rate {
		fmt.Println(exchange)
	}
	
	// 获取特定加密货币对汇率
	candle, _, err := finnhubClient.CryptoCandles(ctx, "BINANCE:BTCUSDT", "D", 1590988249, 1591852249)
	if err != nil {
		fmt.Printf("Error getting crypto candles: %v\n", err)
		return
	}
	
	fmt.Println("BTC/USDT candles:")
	for i := 0; i < len(candle.O); i++ {
		fmt.Printf("Time: %d, Open: %.2f, High: %.2f, Low: %.2f, Close: %.2f\n", 
			candle.T[i], candle.O[i], candle.H[i], candle.L[i], candle.C[i])
	}
}

4. 获取外汇汇率

func getForexRates(finnhubClient *finnhub.DefaultApiService, ctx context.Context, base string, target string) {
	// 获取支持的货币对
	symbols, _, err := finnhubClient.ForexSymbols(ctx, "OANDA")
	if err != nil {
		fmt.Printf("Error getting forex symbols: %v\n", err)
		return
	}
	
	fmt.Println("Available forex pairs:")
	for _, symbol := range symbols {
		fmt.Printf("%s - %s\n", *symbol.DisplaySymbol, *symbol.Description)
	}
	
	// 获取特定货币对汇率
	quote, _, err := finnhubClient.ForexRates(ctx, &finnhub.ForexRatesOpts{
		Base: optional.NewString(base),
	})
	if err != nil {
		fmt.Printf("Error getting forex rates: %v\n", err)
		return
	}
	
	fmt.Printf("Base currency: %s\n", *quote.Base)
	for code, rate := range quote.Quote {
		if code == target {
			fmt.Printf("%s/%s: %.4f\n", *quote.Base, code, rate)
		}
	}
}

5. 获取市场新闻

func getMarketNews(finnhubClient *finnhub.DefaultApiService, ctx context.Context, category string) {
	news, _, err := finnhubClient.MarketNews(ctx, category, nil)
	if err != nil {
		fmt.Printf("Error getting market news: %v\n", err)
		return
	}
	
	fmt.Printf("Latest %s news:\n", category)
	for i, item := range news {
		if i >= 5 { // 只显示前5条
			break
		}
		fmt.Printf("[%s] %s - %s\n", *item.Source, *item.Headline, *item.Url)
	}
}

使用建议

  1. 缓存数据:Finnhub API 有调用频率限制,建议对不常变化的数据进行缓存
  2. 错误处理:API 调用可能会失败,务必添加适当的错误处理
  3. 上下文控制:使用 context 控制请求超时和取消
  4. 环境变量:将 API 密钥存储在环境变量中而非代码中
  5. 速率限制:免费版 Finnhub 有每分钟 30 次调用的限制,注意不要超过

完整示例

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	finnhub "github.com/Finnhub-Stock-API/finnhub-go"
	"golang.org/x/time/rate"
)

func main() {
	apiKey := os.Getenv("FINNHUB_API_KEY")
	if apiKey == "" {
		panic("FINNHUB_API_KEY environment variable not set")
	}

	cfg := finnhub.NewConfiguration()
	cfg.AddDefaultHeader("X-Finnhub-Token", apiKey)
	finnhubClient := finnhub.NewAPIClient(cfg).DefaultApi
	ctx := context.Background()
	
	// 使用限流器避免超过API限制
	limiter := rate.NewLimiter(rate.Every(time.Second), 1) // 每秒1次请求
	
	// 获取股票报价
	if err := limiter.Wait(ctx); err == nil {
		getQuote(finnhubClient, ctx, "AAPL")
	}
	
	// 获取公司信息
	if err := limiter.Wait(ctx); err == nil {
		getCompanyProfile(finnhubClient, ctx, "AAPL")
	}
	
	// 获取加密货币数据
	if err := limiter.Wait(ctx); err == nil {
		getCryptoExchangeRate(finnhubClient, ctx, "BTC", "USDT")
	}
	
	// 获取外汇数据
	if err := limiter.Wait(ctx); err == nil {
		getForexRates(finnhubClient, ctx, "USD", "CNY")
	}
	
	// 获取市场新闻
	if err := limiter.Wait(ctx); err == nil {
		getMarketNews(finnhubClient, ctx, "general")
	}
}

// 前面定义的各种函数...

go-finnhub 提供了丰富的金融市场数据接口,适合开发金融分析工具、交易系统或市场监控应用。根据你的具体需求,可以选择合适的 API 端点获取数据。

回到顶部