stockquote.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // ============================================================================
  2. // stockquote.go — 股票行情
  3. //
  4. // 拉取腾讯行情、分时与日 K 数据;区分交易时段 / 休市刷新间隔。
  5. // ============================================================================
  6. package main
  7. import (
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "golang.org/x/text/encoding/simplifiedchinese" // 腾讯行情接口返回 GBK,需要转码
  16. "golang.org/x/text/transform"
  17. )
  18. // 行情接口地址
  19. const (
  20. quoteAPIURL = "https://qt.gtimg.cn/q=" // 实时行情
  21. minuteAPIURL = "https://web.ifzq.gtimg.cn/appstock/app/minute/query?code=" // 分时数据
  22. klineAPIURL = "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=" // 日 K 数据
  23. )
  24. // StockQuote 单只股票的行情快照,供前端「股市」页展示
  25. type StockQuote struct {
  26. Code string `json:"code"` // 带市场前缀的代码,如 sh600519
  27. Name string `json:"name"` // 股票名称
  28. Price float64 `json:"price"` // 当前价
  29. Change float64 `json:"change"` // 涨跌额
  30. ChangePercent float64 `json:"changePercent"` // 涨跌幅(%)
  31. Amount float64 `json:"amount"` // 成交额(万元)
  32. Time string `json:"time"` // 行情时间 HH:MM:SS
  33. }
  34. // MinutePoint 分时图上的一个点
  35. type MinutePoint struct {
  36. Time string `json:"time"` // HH:MM
  37. Price float64 `json:"price"` // 当前价
  38. Avg float64 `json:"avg"` // 均价
  39. }
  40. // MinuteChart 分时图数据
  41. type MinuteChart struct {
  42. Code string `json:"code"` // 股票代码
  43. PrevClose float64 `json:"prevClose"` // 昨收,作为分时基准线
  44. Points []MinutePoint `json:"points"` // 分时点序列
  45. }
  46. // KLineBar 日 K 的一根柱子
  47. type KLineBar struct {
  48. Date string `json:"date"` // 交易日
  49. Open float64 `json:"open"` // 开盘价
  50. Close float64 `json:"close"` // 收盘价
  51. High float64 `json:"high"` // 最高价
  52. Low float64 `json:"low"` // 最低价
  53. Volume float64 `json:"volume"` // 成交量(手)
  54. }
  55. // normalizeStockCode 规范化股票代码:纯数字自动补全市场前缀
  56. func normalizeStockCode(raw string) string {
  57. code := strings.ToLower(strings.TrimSpace(raw))
  58. if code == "" {
  59. return ""
  60. }
  61. if strings.HasPrefix(code, "sh") || strings.HasPrefix(code, "sz") || strings.HasPrefix(code, "bj") {
  62. return code // 已带前缀,直接使用
  63. }
  64. switch {
  65. case strings.HasPrefix(code, "6"), strings.HasPrefix(code, "5"), strings.HasPrefix(code, "9"):
  66. return "sh" + code // 沪市:60/68 等,也包含 5 开头基金、9 开头 B 股
  67. case strings.HasPrefix(code, "0"), strings.HasPrefix(code, "3"):
  68. return "sz" + code // 深市:00 主板、30 创业板
  69. case strings.HasPrefix(code, "4"), strings.HasPrefix(code, "8"):
  70. return "bj" + code // 北交所:43/83/87 等
  71. }
  72. return code
  73. }
  74. // fetchStockQuotes 从腾讯行情接口批量拉取股票行情
  75. func fetchStockQuotes(codes []string) ([]StockQuote, error) {
  76. if len(codes) == 0 {
  77. return []StockQuote{}, nil // 未配置股票时返回空列表
  78. }
  79. url := quoteAPIURL + strings.Join(codes, ",") // 批量查询,逗号分隔
  80. client := &http.Client{Timeout: 8 * time.Second}
  81. req, err := http.NewRequest(http.MethodGet, url, nil)
  82. if err != nil {
  83. return nil, err
  84. }
  85. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") // 部分接口会校验 UA
  86. req.Header.Set("Referer", "https://gu.qq.com/")
  87. resp, err := client.Do(req)
  88. if err != nil {
  89. return nil, err
  90. }
  91. defer resp.Body.Close()
  92. // 腾讯接口为 GBK 编码,先整体转成 UTF-8 再解析
  93. body, err := io.ReadAll(transform.NewReader(resp.Body, simplifiedchinese.GBK.NewDecoder()))
  94. if err != nil {
  95. return nil, err
  96. }
  97. quotes := make([]StockQuote, 0, len(codes))
  98. for _, line := range strings.Split(string(body), ";") { // 每只股票一行,以分号分隔
  99. quote, ok := parseQuoteLine(line)
  100. if ok {
  101. quotes = append(quotes, quote)
  102. }
  103. }
  104. return quotes, nil
  105. }
  106. // parseQuoteLine 解析单行行情:v_sh600519="1~贵州茅台~600519~价格~...";
  107. func parseQuoteLine(line string) (StockQuote, bool) {
  108. line = strings.TrimSpace(line)
  109. idx := strings.Index(line, "=\"")
  110. if idx < 0 {
  111. return StockQuote{}, false
  112. }
  113. payload := strings.Trim(strings.TrimSpace(line[idx+2:]), `";`) // 去掉包裹的引号与分号
  114. fields := strings.Split(payload, "~")
  115. if len(fields) < 38 {
  116. return StockQuote{}, false // 字段不足,视为无效行
  117. }
  118. return StockQuote{
  119. Code: fields[2],
  120. Name: fields[1],
  121. Price: parseQuoteFloat(fields[3]),
  122. Change: parseQuoteFloat(fields[31]),
  123. ChangePercent: parseQuoteFloat(fields[32]),
  124. Amount: parseQuoteFloat(fields[37]), // 成交额,单位:万元
  125. Time: formatQuoteTime(fields[30]),
  126. }, true
  127. }
  128. // fetchMinuteChart 拉取分时数据:time 分值 price avg
  129. func fetchMinuteChart(code string) (MinuteChart, error) {
  130. chart := MinuteChart{Code: code, Points: []MinutePoint{}}
  131. // 先取报价,用「现价 - 涨跌额」得到昨收,作为分时基准线
  132. quote, err := fetchSingleQuote(code)
  133. if err != nil {
  134. return chart, err
  135. }
  136. chart.PrevClose = quote.Price - quote.Change
  137. var payload minutePayload
  138. if err := httpGetJSON(minuteAPIURL+code, &payload); err != nil {
  139. return chart, err
  140. }
  141. item, ok := payload.Data[code]
  142. if !ok {
  143. return chart, fmt.Errorf("未获取到 %s 的分时数据", code)
  144. }
  145. var totalVolume, totalAmount float64
  146. for _, line := range item.Data.Data {
  147. fields := strings.Fields(line) // 形如:0930 1349.99 1486 200608514.00
  148. if len(fields) < 4 {
  149. continue
  150. }
  151. price := parseQuoteFloat(fields[1])
  152. volume := parseQuoteFloat(fields[2]) // 成交量(手)
  153. amount := parseQuoteFloat(fields[3]) // 成交额(元)
  154. totalVolume += volume * 100 // 手 → 股
  155. totalAmount += amount // 累计成交额
  156. avg := 0.0
  157. if totalVolume > 0 {
  158. avg = totalAmount / totalVolume // 均价 = 累计成交额 / 累计成交量
  159. }
  160. chart.Points = append(chart.Points, MinutePoint{
  161. Time: fields[0][0:2] + ":" + fields[0][2:4], // HHMM → HH:MM
  162. Price: price,
  163. Avg: avg,
  164. })
  165. }
  166. return chart, nil
  167. }
  168. // fetchKLine 拉取日 K 数据(前复权),返回最近 count 根
  169. func fetchKLine(code string, count int) ([]KLineBar, error) {
  170. if count <= 0 {
  171. count = 120 // 默认 120 个交易日
  172. }
  173. url := fmt.Sprintf("%s%s,day,,,%d,qfq", klineAPIURL, code, count)
  174. var payload klinePayload
  175. if err := httpGetJSON(url, &payload); err != nil {
  176. return nil, err
  177. }
  178. item, ok := payload.Data[code]
  179. if !ok {
  180. return nil, fmt.Errorf("未获取到 %s 的日K数据", code)
  181. }
  182. rows := item.QfqDay // 前复权数据优先,没有则退回原始日线
  183. if len(rows) == 0 {
  184. rows = item.Day
  185. }
  186. bars := make([]KLineBar, 0, len(rows))
  187. for _, row := range rows {
  188. if len(row) < 6 {
  189. continue // 数据不完整则跳过
  190. }
  191. // 前 6 项为 [日期, 开, 收, 高, 低, 量] 字符串;除权信息等附加字段忽略
  192. vals := make([]string, 6)
  193. for i := 0; i < 6; i++ {
  194. if err := json.Unmarshal(row[i], &vals[i]); err != nil {
  195. vals[i] = "" // 字段非字符串时置空,交给 parseQuoteFloat 归零
  196. }
  197. }
  198. bars = append(bars, KLineBar{
  199. Date: vals[0],
  200. Open: parseQuoteFloat(vals[1]),
  201. Close: parseQuoteFloat(vals[2]),
  202. High: parseQuoteFloat(vals[3]),
  203. Low: parseQuoteFloat(vals[4]),
  204. Volume: parseQuoteFloat(vals[5]),
  205. })
  206. }
  207. return bars, nil
  208. }
  209. // fetchSingleQuote 取单只股票报价(用于分时基准线)
  210. func fetchSingleQuote(code string) (StockQuote, error) {
  211. quotes, err := fetchStockQuotes([]string{code})
  212. if err != nil {
  213. return StockQuote{}, err
  214. }
  215. if len(quotes) == 0 {
  216. return StockQuote{}, fmt.Errorf("未获取到 %s 的报价", code)
  217. }
  218. return quotes[0], nil
  219. }
  220. // httpGetJSON 发起 GET 请求并解析 JSON(腾讯 web 接口为 UTF-8)
  221. func httpGetJSON(url string, target any) error {
  222. client := &http.Client{Timeout: 8 * time.Second}
  223. req, err := http.NewRequest(http.MethodGet, url, nil)
  224. if err != nil {
  225. return err
  226. }
  227. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
  228. req.Header.Set("Referer", "https://gu.qq.com/")
  229. resp, err := client.Do(req)
  230. if err != nil {
  231. return err
  232. }
  233. defer resp.Body.Close()
  234. body, err := io.ReadAll(resp.Body)
  235. if err != nil {
  236. return err
  237. }
  238. return json.Unmarshal(body, target)
  239. }
  240. // minutePayload 分时接口的响应结构(按股票代码动态嵌套)
  241. type minutePayload struct {
  242. Data map[string]struct {
  243. Data struct {
  244. Data []string `json:"data"` // "HHMM 价格 成交量 成交额"
  245. } `json:"data"`
  246. } `json:"data"`
  247. }
  248. // klinePayload 日 K 接口的响应结构
  249. type klinePayload struct {
  250. Data map[string]struct {
  251. // 前复权 / 原始日线。每行前 6 项固定为 [日期, 开, 收, 高, 低, 量] 字符串,
  252. // 除权除息日会追加第 7 个对象字段(除权信息),故用 RawMessage 以兼容任意类型。
  253. QfqDay [][]json.RawMessage `json:"qfqday"`
  254. Day [][]json.RawMessage `json:"day"`
  255. } `json:"data"`
  256. }
  257. // parseQuoteFloat 解析浮点字段,失败时返回 0
  258. func parseQuoteFloat(raw string) float64 {
  259. value, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
  260. if err != nil {
  261. return 0
  262. }
  263. return value
  264. }
  265. // formatQuoteTime 将 20231028160001 格式化为 16:00:01
  266. func formatQuoteTime(raw string) string {
  267. if len(raw) < 14 {
  268. return raw
  269. }
  270. return raw[8:10] + ":" + raw[10:12] + ":" + raw[12:14]
  271. }