java对接美股股票api涵盖实时行情、K 线、指数等核心接口。

27 阅读3分钟

根据 StockTV 文档,美股数据同样属于「全球股票」模块。下面我用 Java 给出一套可测试、可扩展的美股对接方案,重点解决 countryId不确定的问题。

一、基础配置 & 通用工具类

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class StockTVUSClient {
    public static final String BASE_URL = "https://api.stocktv.top";
    public static final String API_KEY = "你的_API_KEY"; // 🔴 替换成你的 key
    public static final int US_COUNTRY_ID = 5; // 已确认的美国 countryId

    private static final ObjectMapper mapper = new ObjectMapper();

    // 通用 GET 请求
    public static String get(String path, Map<String, String> params) throws IOException {
        Map<String, String> fullParams = new HashMap<>(params);
        fullParams.put("key", API_KEY);

        StringBuilder url = new StringBuilder(BASE_URL + path);
        if (!fullParams.isEmpty()) {
            url.append("?");
            for (Map.Entry<String, String> e : fullParams.entrySet()) {
                url.append(e.getKey())
                   .append("=")
                   .append(URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
                   .append("&");
            }
            url.deleteCharAt(url.length() - 1); // 去掉末尾 &
        }

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet req = new HttpGet(url.toString());
            try (CloseableHttpResponse resp = client.execute(req)) {
                return EntityUtils.toString(resp.getEntity());
            }
        }
    }

    // 解析 JSON
    public static <T> T parse(String json, Class<T> clazz) throws IOException {
        return mapper.readValue(json, clazz);
    }
}

二、数据模型(共用一套,适合所有国家)

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

// 股票列表响应
class StockListResponse {
    @JsonProperty("code") int code;
    @JsonProperty("message") String message;
    @JsonProperty("data") Data data;

    static class Data {
        @JsonProperty("records") List<Stock> records;
        @JsonProperty("total") int total;
    }

    static class Stock {
        @JsonProperty("id") Long id;           // PID,用于 K 线和订阅
        @JsonProperty("name") String name;
        @JsonProperty("symbol") String symbol; // 如 AAPL
        @JsonProperty("last") Double last;
        @JsonProperty("chg") Double chg;
        @JsonProperty("chgPct") Double chgPct;
        @JsonProperty("high") Double high;
        @JsonProperty("low") Double low;
        @JsonProperty("volume") Long volume;
        @JsonProperty("open") Boolean open;    // 是否开盘
        @JsonProperty("countryId") Integer countryId;
        @JsonProperty("flag") String flag;     // US
    }
}

// K 线响应
class KlineResponse {
    @JsonProperty("code") int code;
    @JsonProperty("message") String message;
    @JsonProperty("data") List<KlineBar> data;

    static class KlineBar {
        @JsonProperty("time") Long time;       // 毫秒时间戳
        @JsonProperty("open") Double open;
        @JsonProperty("high") Double high;
        @JsonProperty("low") Double low;
        @JsonProperty("close") Double close;
        @JsonProperty("volume") Double volume;
    }
}

// 指数响应
class IndexResponse {
    @JsonProperty("code") int code;
    @JsonProperty("message") String message;
    @JsonProperty("data") List<Index> data;

    static class Index {
        @JsonProperty("id") Long id;
        @JsonProperty("name") String name;     // 如 "S&P 500"
        @JsonProperty("symbol") String symbol; // 如 SPX
        @JsonProperty("last") Double last;
        @JsonProperty("chgPct") Double chgPct;
        @JsonProperty("flag") String flag;     // US
    }
}

三、美股核心接口封装

import java.io.IOException;
import java.util.Map;

public class USStockAPI {
    private static final int US_ID = StockTVUSClient.US_COUNTRY_ID;

    // 1. 获取美股列表(支持分页)
    public static StockListResponse listStocks(int page, int pageSize) throws IOException {
        Map<String, String> params = Map.of(
            "countryId", String.valueOf(US_ID),
            "page", String.valueOf(page),
            "pageSize", String.valueOf(pageSize)
        );

        String json = StockTVUSClient.get("/stock/stocks", params);
        return StockTVUSClient.parse(json, StockListResponse.class);
    }

    // 2. 按 symbol 查询(如 "AAPL")
    public static StockListResponse queryBySymbol(String symbol) throws IOException {
        Map<String, String> params = Map.of("symbol", symbol);
        String json = StockTVUSClient.get("/stock/queryStocks", params);
        return StockTVUSClient.parse(json, StockListResponse.class);
    }

    // 3. 获取 K 线(需要 PID)
    public static KlineResponse getKline(long pid, String interval) throws IOException {
        Map<String, String> params = Map.of(
            "pid", String.valueOf(pid),
            "interval", interval
        );

        String json = StockTVUSClient.get("/stock/kline", params);
        return StockTVUSClient.parse(json, KlineResponse.class);
    }

    // 4. 获取美股大盘指数
    public static IndexResponse getIndices() throws IOException {
        Map<String, String> params = Map.of("countryId", String.valueOf(US_ID));
        String json = StockTVUSClient.get("/stock/indices", params);
        return StockTVUSClient.parse(json, IndexResponse.class);
    }
}

四、使用示例:跑一遍完整流程

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class USExample {
    public static void main(String[] args) throws IOException {
        // 1. 拉第一页美股列表
        StockListResponse listResp = USStockAPI.listStocks(1, 10);
        if (listResp.code != 200) {
            System.out.println("❌ 列表请求失败: " + listResp.message);
            return;
        }

        System.out.println("📊 美股列表(前10只):");
        for (StockListResponse.Stock s : listResp.data.records) {
            System.out.printf("- %s (%s) %.2f 涨跌: %.2f%%\n", 
                s.name, s.symbol, s.last, s.chgPct);
        }

        // 2. 查一只具体的票(比如 Apple)
        StockListResponse aaplResp = USStockAPI.queryBySymbol("AAPL");
        if (aaplResp.code == 200 && !aaplResp.data.records.isEmpty()) {
            StockListResponse.Stock aapl = aaplResp.data.records.get(0);
            System.out.println("\n🍎 Apple 信息: PID=" + aapl.id + ", 当前价=" + aapl.last);

            // 3. 拿日 K 线
            KlineResponse kline = USStockAPI.getKline(aapl.id, "P1D");
            if (kline.code == 200 && !kline.data.isEmpty()) {
                KlineResponse.KlineBar latest = kline.data.get(kline.data.size() - 1);
                String date = new SimpleDateFormat("yyyy-MM-dd")
                    .format(new Date(latest.time));
                System.out.printf("最近日K: %s O:%.2f H:%.2f L:%.2f C:%.2f\n",
                    date, latest.open, latest.high, latest.low, latest.close);
            }
        }

        // 4. 大盘指数
        IndexResponse indices = USStockAPI.getIndices();
        if (indices.code == 200) {
            System.out.println("\n📈 美股指数:");
            for (IndexResponse.Index idx : indices.data) {
                System.out.printf("- %s (%s): %.2f %.2f%%\n",
                    idx.name, idx.symbol, idx.last, idx.chgPct);
            }
        }
    }
}

五、实时数据(WebSocket 版)

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import java.net.URI;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class USWebSocketClient extends WebSocketClient {
    private static final String WS_URL = 
        "wss://ws-api.stocktv.top/connect?key=" + StockTVUSClient.API_KEY;

    public USWebSocketClient() {
        super(URI.create(WS_URL));
    }

    @Override
    public void onOpen(ServerHandshake h) {
        System.out.println("✅ 美股实时连接已打开");
    }

    @Override
    public void onMessage(String msg) {
        JSONObject data = new JSONObject(msg);
        String pid = data.getString("pid");
        String price = data.getString("last_numeric");
        String change = data.getString("pc");
        String pct = data.getString("pcp");

        System.out.printf("[实时] PID=%s 价格=%s 涨跌=%s(%s%%)\n", pid, price, change, pct);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("❌ 连接关闭: " + reason);
    }

    @Override
    public void onError(Exception e) {
        e.printStackTrace();
    }

    // 订阅美股 PID 列表
    public void subscribe(List<Long> pids) {
        if (!isOpen()) return;

        JSONObject sub = new JSONObject();
        sub.put("action", "subscribe");
        sub.put("pids", pids);

        send(sub.toString());
        System.out.println("已订阅: " + pids);
    }

    // 简单心跳(每30秒发空消息)
    public void startHeartbeat() {
        new Timer(true).scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (isOpen()) send("");
            }
        }, 0, 30000);
    }
}

六、快速上手步骤

  1. API_KEY 换成你从 StockTV 客服那里拿到的 key;
  2. 直接运行 USExample.main(),看能否正常输出美股列表、指数、K 线;
  3. 如果有真实的 PID(比如 AAPL 的 PID),再用 USWebSocketClient 订阅实时行情。

这套代码完全适配 countryId=5,你只需要关心填入正确 PIDAPI Key 即可正常使用。