以下是使用Go语言对接StockTV全球股票API的步骤及示例代码,支持马来西亚、印度等国家的实时股票数据获取:
一、准备工作
- 获取API Key:联系StockTV获取Key
- 安装依赖:
go get github.com/gorilla/websocket # WebSocket支持
二、核心代码示例
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// 通用API响应结构
type StockResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// 股票市场数据结构
type StockMarket struct {
ID int `json:"id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
Last float64 `json:"last"`
ChgPct float64 `json:"chgPct"`
High float64 `json:"high"`
Low float64 `json:"low"`
Volume float64 `json:"volume"`
CountryID int `json:"countryId"`
}
// 获取股票市场列表
func GetStockMarkets(countryID int, pageSize int) ([]StockMarket, error) {
baseURL := "https://api.stocktv.top/stock/stocks"
params := url.Values{}
params.Add("key", "YOUR_API_KEY") // 替换真实Key
params.Add("countryId", fmt.Sprintf("%d", countryID))
params.Add("pageSize", fmt.Sprintf("%d", pageSize))
resp, err := http.Get(fmt.Sprintf("%s?%s", baseURL, params.Encode()))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var response StockResponse
var markets struct {
Records []StockMarket `json:"records"`
}
response.Data = &markets
if err := json.Unmarshal(body, &response); err != nil {
return nil, err
}
return markets.Records, nil
}
// 实时WebSocket数据
func ConnectWebSocket() {
conn, _, err := websocket.DefaultDialer.Dial(
"wss://ws-api.stocktv.top/connect?key=YOUR_API_KEY",
nil,
)
if err != nil {
panic(err)
}
defer conn.Close()
// 心跳保持
go func() {
for {
time.Sleep(30 * time.Second)
conn.WriteMessage(websocket.PingMessage, nil)
}
}()
// 接收实时数据
for {
_, message, err := conn.ReadMessage()
if err != nil {
break
}
fmt.Printf("实时更新: %s\n", message)
}
}
func main() {
// 示例:获取马来西亚股票(countryId=42)
markets, err := GetStockMarkets(42, 50)
if err != nil {
panic(err)
}
fmt.Println("马来西亚股票市场数据:")
for _, m := range markets {
fmt.Printf("%s (%.2f) 涨跌: %.2f%%\n",
m.Name, m.Last, m.ChgPct)
}
// 启动WebSocket实时连接
go ConnectWebSocket()
select {} // 保持主线程运行
}
三、关键配置说明
-
国家ID对照表:
- 印度:
14 - 马来西亚:
42 - 美国:
...(其他ID需查询文档)
- 印度:
-
实时数据特性:
- WebSocket接口:
wss://ws-api.stocktv.top/connect - 推送频率:每秒更新
- 数据字段包含:最新价、买卖价、成交量、时间戳等
- WebSocket接口:
-
不限次数策略:
- 无明确速率限制(需确认服务条款)
- 建议合理控制请求频率(推荐1-5秒/次)
- WebSocket连接可长期保持
四、使用示例
// 获取印度国家指数
func GetIndiaIndices() {
url := "https://api.stocktv.top/stock/indices?countryId=14&key=YOUR_KEY"
// ... 类似股票市场请求逻辑
}
// 获取单个股票详情(通过PID)
func GetStockByID(pid int) {
url := fmt.Sprintf("https://api.stocktv.top/stock/queryStocks?id=%d&key=YOUR_KEY", pid)
// ... 请求逻辑
}
五、注意事项
- 所有返回数据为JSON格式
- 时间戳单位为秒(需要
time.Unix()转换) - 股票状态字段:
open: 是否开市(true/false)cfd: 是否差价合约
- 错误处理建议:
if response.Code != 200 {
return fmt.Errorf("API错误: %s", response.Message)
}
完整文档参考:StockTV API文档(需联系获取)
建议通过WebSocket获取实时数据,HTTP API用于初始化数据加载,两者结合可实现高效实时更新。
6532

被折叠的 条评论
为什么被折叠?



