找回密码
 立即注册
首页 业界区 安全 Java 对接印度股票数据源实现 http+ws实时数据 ...

Java 对接印度股票数据源实现 http+ws实时数据

崆蛾寺 前天 16:10
以下是使用 Java 对接 StockTV 印度股票数据源的完整实现,包括实时行情、K线数据、公司信息等功能。
1. 项目依赖

首先在 pom.xml 中添加必要的依赖:
  1. <dependencies>
  2.    
  3.     <dependency>
  4.         <groupId>org.apache.httpcomponents</groupId>
  5.         httpclient</artifactId>
  6.         <version>4.5.14</version>
  7.     </dependency>
  8.    
  9.    
  10.     <dependency>
  11.         <groupId>com.fasterxml.jackson.core</groupId>
  12.         jackson-databind</artifactId>
  13.         <version>2.15.2</version>
  14.     </dependency>
  15.    
  16.    
  17.     <dependency>
  18.         <groupId>org.java-websocket</groupId>
  19.         Java-WebSocket</artifactId>
  20.         <version>1.5.3</version>
  21.     </dependency>
  22.    
  23.    
  24.     <dependency>
  25.         <groupId>org.slf4j</groupId>
  26.         slf4j-api</artifactId>
  27.         <version>2.0.7</version>
  28.     </dependency>
  29.     <dependency>
  30.         <groupId>org.slf4j</groupId>
  31.         slf4j-simple</artifactId>
  32.         <version>2.0.7</version>
  33.     </dependency>
  34. </dependencies>
复制代码
2. 配置类
  1. package com.stocktv.india.config;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.apache.http.impl.client.CloseableHttpClient;
  4. import org.apache.http.impl.client.HttpClients;
  5. public class StockTVConfig {
  6.    
  7.     // API 基础配置
  8.     public static final String BASE_URL = "https://api.stocktv.top";
  9.     public static final String WS_URL = "wss://ws-api.stocktv.top/connect";
  10.    
  11.     // 印度市场特定配置
  12.     public static final int INDIA_COUNTRY_ID = 14;
  13.     public static final int NSE_EXCHANGE_ID = 46;
  14.     public static final int BSE_EXCHANGE_ID = 74;
  15.    
  16.     // API Key - 请替换为实际的 API Key
  17.     private String apiKey;
  18.    
  19.     // HTTP 客户端
  20.     private final CloseableHttpClient httpClient;
  21.     private final ObjectMapper objectMapper;
  22.    
  23.     public StockTVConfig(String apiKey) {
  24.         this.apiKey = apiKey;
  25.         this.httpClient = HttpClients.createDefault();
  26.         this.objectMapper = new ObjectMapper();
  27.     }
  28.    
  29.     // Getters
  30.     public String getApiKey() { return apiKey; }
  31.     public CloseableHttpClient getHttpClient() { return httpClient; }
  32.     public ObjectMapper getObjectMapper() { return objectMapper; }
  33. }
复制代码
3. 数据模型类

股票基本信息
  1. package com.stocktv.india.model;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import lombok.Data;
  4. import java.math.BigDecimal;
  5. @Data
  6. public class Stock {
  7.     @JsonProperty("id")
  8.     private Long id;
  9.    
  10.     @JsonProperty("symbol")
  11.     private String symbol;
  12.    
  13.     @JsonProperty("name")
  14.     private String name;
  15.    
  16.     @JsonProperty("last")
  17.     private BigDecimal lastPrice;
  18.    
  19.     @JsonProperty("chg")
  20.     private BigDecimal change;
  21.    
  22.     @JsonProperty("chgPct")
  23.     private BigDecimal changePercent;
  24.    
  25.     @JsonProperty("high")
  26.     private BigDecimal high;
  27.    
  28.     @JsonProperty("low")
  29.     private BigDecimal low;
  30.    
  31.     @JsonProperty("volume")
  32.     private Long volume;
  33.    
  34.     @JsonProperty("open")
  35.     private Boolean isOpen;
  36.    
  37.     @JsonProperty("exchangeId")
  38.     private Integer exchangeId;
  39.    
  40.     @JsonProperty("countryId")
  41.     private Integer countryId;
  42.    
  43.     @JsonProperty("time")
  44.     private Long timestamp;
  45.    
  46.     @JsonProperty("fundamentalMarketCap")
  47.     private BigDecimal marketCap;
  48.    
  49.     @JsonProperty("fundamentalRevenue")
  50.     private String revenue;
  51.    
  52.     // 技术指标
  53.     @JsonProperty("technicalDay")
  54.     private String technicalDay;
  55.    
  56.     @JsonProperty("technicalHour")
  57.     private String technicalHour;
  58.    
  59.     @JsonProperty("technicalWeek")
  60.     private String technicalWeek;
  61.    
  62.     @JsonProperty("technicalMonth")
  63.     private String technicalMonth;
  64. }
复制代码
K线数据
  1. package com.stocktv.india.model;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import lombok.Data;
  4. import java.math.BigDecimal;
  5. @Data
  6. public class KLine {
  7.     @JsonProperty("time")
  8.     private Long timestamp;
  9.    
  10.     @JsonProperty("open")
  11.     private BigDecimal open;
  12.    
  13.     @JsonProperty("high")
  14.     private BigDecimal high;
  15.    
  16.     @JsonProperty("low")
  17.     private BigDecimal low;
  18.    
  19.     @JsonProperty("close")
  20.     private BigDecimal close;
  21.    
  22.     @JsonProperty("volume")
  23.     private Long volume;
  24.    
  25.     @JsonProperty("vo")
  26.     private BigDecimal turnover;
  27. }
复制代码
指数数据
  1. package com.stocktv.india.model;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import lombok.Data;
  4. import java.math.BigDecimal;
  5. @Data
  6. public class Index {
  7.     @JsonProperty("id")
  8.     private Long id;
  9.    
  10.     @JsonProperty("name")
  11.     private String name;
  12.    
  13.     @JsonProperty("symbol")
  14.     private String symbol;
  15.    
  16.     @JsonProperty("last")
  17.     private BigDecimal lastPrice;
  18.    
  19.     @JsonProperty("chg")
  20.     private BigDecimal change;
  21.    
  22.     @JsonProperty("chgPct")
  23.     private BigDecimal changePercent;
  24.    
  25.     @JsonProperty("high")
  26.     private BigDecimal high;
  27.    
  28.     @JsonProperty("low")
  29.     private BigDecimal low;
  30.    
  31.     @JsonProperty("isOpen")
  32.     private Boolean isOpen;
  33.    
  34.     @JsonProperty("time")
  35.     private Long timestamp;
  36. }
复制代码
API 响应包装类
  1. package com.stocktv.india.model;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import lombok.Data;
  4. import java.util.List;
  5. @Data
  6. public class ApiResponse<T> {
  7.     @JsonProperty("code")
  8.     private Integer code;
  9.    
  10.     @JsonProperty("message")
  11.     private String message;
  12.    
  13.     @JsonProperty("data")
  14.     private T data;
  15. }
  16. @Data
  17. class StockListResponse {
  18.     @JsonProperty("records")
  19.     private List<Stock> records;
  20.    
  21.     @JsonProperty("total")
  22.     private Integer total;
  23.    
  24.     @JsonProperty("current")
  25.     private Integer current;
  26.    
  27.     @JsonProperty("pages")
  28.     private Integer pages;
  29. }
复制代码
4. HTTP API 客户端
  1. package com.stocktv.india.client;
  2. import com.fasterxml.jackson.core.type.TypeReference;
  3. import com.stocktv.india.config.StockTVConfig;
  4. import com.stocktv.india.model.*;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.client.utils.URIBuilder;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.util.EntityUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import java.io.IOException;
  13. import java.net.URI;
  14. import java.net.URISyntaxException;
  15. import java.util.List;
  16. public class StockTVHttpClient {
  17.    
  18.     private static final Logger logger = LoggerFactory.getLogger(StockTVHttpClient.class);
  19.    
  20.     private final StockTVConfig config;
  21.     private final CloseableHttpClient httpClient;
  22.    
  23.     public StockTVHttpClient(StockTVConfig config) {
  24.         this.config = config;
  25.         this.httpClient = config.getHttpClient();
  26.     }
  27.    
  28.     /**
  29.      * 获取印度股票列表
  30.      */
  31.     public List<Stock> getIndiaStocks(Integer pageSize, Integer page) throws IOException, URISyntaxException {
  32.         URI uri = new URIBuilder(config.BASE_URL + "/stock/stocks")
  33.                 .addParameter("countryId", String.valueOf(config.INDIA_COUNTRY_ID))
  34.                 .addParameter("pageSize", String.valueOf(pageSize))
  35.                 .addParameter("page", String.valueOf(page))
  36.                 .addParameter("key", config.getApiKey())
  37.                 .build();
  38.         
  39.         ApiResponse<StockListResponse> response = executeGetRequest(uri,
  40.             new TypeReference>() {});
  41.         
  42.         if (response.getCode() == 200) {
  43.             return response.getData().getRecords();
  44.         } else {
  45.             throw new RuntimeException("API Error: " + response.getMessage());
  46.         }
  47.     }
  48.    
  49.     /**
  50.      * 查询单个股票
  51.      */
  52.     public List<Stock> queryStock(Long pid, String symbol, String name) throws IOException, URISyntaxException {
  53.         URIBuilder uriBuilder = new URIBuilder(config.BASE_URL + "/stock/queryStocks")
  54.                 .addParameter("key", config.getApiKey());
  55.         
  56.         if (pid != null) {
  57.             uriBuilder.addParameter("id", String.valueOf(pid));
  58.         }
  59.         if (symbol != null) {
  60.             uriBuilder.addParameter("symbol", symbol);
  61.         }
  62.         if (name != null) {
  63.             uriBuilder.addParameter("name", name);
  64.         }
  65.         
  66.         URI uri = uriBuilder.build();
  67.         
  68.         ApiResponse<List<Stock>> response = executeGetRequest(uri,
  69.             new TypeReference>>() {});
  70.         
  71.         return response.getData();
  72.     }
  73.    
  74.     /**
  75.      * 批量查询多个股票
  76.      */
  77.     public List<Stock> getStocksByPids(List<Long> pids) throws IOException, URISyntaxException {
  78.         String pidsStr = String.join(",", pids.stream().map(String::valueOf).toArray(String[]::new));
  79.         
  80.         URI uri = new URIBuilder(config.BASE_URL + "/stock/stocksByPids")
  81.                 .addParameter("key", config.getApiKey())
  82.                 .addParameter("pids", pidsStr)
  83.                 .build();
  84.         
  85.         ApiResponse<List<Stock>> response = executeGetRequest(uri,
  86.             new TypeReference>>() {});
  87.         
  88.         return response.getData();
  89.     }
  90.    
  91.     /**
  92.      * 获取印度主要指数
  93.      */
  94.     public List<Index> getIndiaIndices() throws IOException, URISyntaxException {
  95.         URI uri = new URIBuilder(config.BASE_URL + "/stock/indices")
  96.                 .addParameter("countryId", String.valueOf(config.INDIA_COUNTRY_ID))
  97.                 .addParameter("key", config.getApiKey())
  98.                 .build();
  99.         
  100.         ApiResponse<List<Index>> response = executeGetRequest(uri,
  101.             new TypeReference>>() {});
  102.         
  103.         return response.getData();
  104.     }
  105.    
  106.     /**
  107.      * 获取K线数据
  108.      */
  109.     public List<KLine> getKLineData(Long pid, String interval) throws IOException, URISyntaxException {
  110.         URI uri = new URIBuilder(config.BASE_URL + "/stock/kline")
  111.                 .addParameter("pid", String.valueOf(pid))
  112.                 .addParameter("interval", interval)
  113.                 .addParameter("key", config.getApiKey())
  114.                 .build();
  115.         
  116.         ApiResponse<List<KLine>> response = executeGetRequest(uri,
  117.             new TypeReference>>() {});
  118.         
  119.         return response.getData();
  120.     }
  121.    
  122.     /**
  123.      * 获取涨跌排行榜
  124.      */
  125.     public List<Stock> getUpDownList(Integer type) throws IOException, URISyntaxException {
  126.         URI uri = new URIBuilder(config.BASE_URL + "/stock/updownList")
  127.                 .addParameter("countryId", String.valueOf(config.INDIA_COUNTRY_ID))
  128.                 .addParameter("type", String.valueOf(type))
  129.                 .addParameter("key", config.getApiKey())
  130.                 .build();
  131.         
  132.         ApiResponse<List<Stock>> response = executeGetRequest(uri,
  133.             new TypeReference>>() {});
  134.         
  135.         return response.getData();
  136.     }
  137.    
  138.     /**
  139.      * 通用GET请求执行方法
  140.      */
  141.     private <T> T executeGetRequest(URI uri, TypeReference<T> typeReference) throws IOException {
  142.         HttpGet request = new HttpGet(uri);
  143.         
  144.         try (CloseableHttpResponse response = httpClient.execute(request)) {
  145.             String responseBody = EntityUtils.toString(response.getEntity());
  146.             logger.debug("API Response: {}", responseBody);
  147.             
  148.             return config.getObjectMapper().readValue(responseBody, typeReference);
  149.         }
  150.     }
  151. }
复制代码
5. WebSocket 实时数据客户端
  1. package com.stocktv.india.client;
  2. import com.fasterxml.jackson.databind.JsonNode;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.stocktv.india.config.StockTVConfig;
  5. import org.java_websocket.client.WebSocketClient;
  6. import org.java_websocket.handshake.ServerHandshake;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import java.net.URI;
  10. import java.util.concurrent.CountDownLatch;
  11. import java.util.concurrent.TimeUnit;
  12. public class StockTVWebSocketClient {
  13.    
  14.     private static final Logger logger = LoggerFactory.getLogger(StockTVWebSocketClient.class);
  15.    
  16.     private final StockTVConfig config;
  17.     private final ObjectMapper objectMapper;
  18.     private WebSocketClient webSocketClient;
  19.     private CountDownLatch connectionLatch;
  20.    
  21.     public StockTVWebSocketClient(StockTVConfig config) {
  22.         this.config = config;
  23.         this.objectMapper = config.getObjectMapper();
  24.     }
  25.    
  26.     /**
  27.      * 连接WebSocket服务器
  28.      */
  29.     public void connect() throws Exception {
  30.         String wsUrl = config.WS_URL + "?key=" + config.getApiKey();
  31.         URI serverUri = URI.create(wsUrl);
  32.         
  33.         connectionLatch = new CountDownLatch(1);
  34.         
  35.         webSocketClient = new WebSocketClient(serverUri) {
  36.             @Override
  37.             public void onOpen(ServerHandshake handshake) {
  38.                 logger.info("WebSocket连接已建立");
  39.                 connectionLatch.countDown();
  40.             }
  41.             
  42.             @Override
  43.             public void onMessage(String message) {
  44.                 try {
  45.                     handleMessage(message);
  46.                 } catch (Exception e) {
  47.                     logger.error("处理WebSocket消息时出错", e);
  48.                 }
  49.             }
  50.             
  51.             @Override
  52.             public void onClose(int code, String reason, boolean remote) {
  53.                 logger.info("WebSocket连接已关闭: code={}, reason={}, remote={}", code, reason, remote);
  54.             }
  55.             
  56.             @Override
  57.             public void onError(Exception ex) {
  58.                 logger.error("WebSocket连接错误", ex);
  59.             }
  60.         };
  61.         
  62.         webSocketClient.connect();
  63.         
  64.         // 等待连接建立
  65.         if (!connectionLatch.await(10, TimeUnit.SECONDS)) {
  66.             throw new RuntimeException("WebSocket连接超时");
  67.         }
  68.     }
  69.    
  70.     /**
  71.      * 处理收到的消息
  72.      */
  73.     private void handleMessage(String message) throws Exception {
  74.         JsonNode jsonNode = objectMapper.readTree(message);
  75.         
  76.         // 解析实时行情数据
  77.         if (jsonNode.has("pid")) {
  78.             RealTimeData realTimeData = objectMapper.treeToValue(jsonNode, RealTimeData.class);
  79.             onRealTimeData(realTimeData);
  80.         } else {
  81.             logger.info("收到消息: {}", message);
  82.         }
  83.     }
  84.    
  85.     /**
  86.      * 处理实时行情数据 - 需要子类重写
  87.      */
  88.     protected void onRealTimeData(RealTimeData data) {
  89.         logger.info("实时行情: {} - 最新价: {}, 涨跌幅: {}%",
  90.             data.getPid(), data.getLastNumeric(), data.getPcp());
  91.     }
  92.    
  93.     /**
  94.      * 发送消息
  95.      */
  96.     public void sendMessage(String message) {
  97.         if (webSocketClient != null && webSocketClient.isOpen()) {
  98.             webSocketClient.send(message);
  99.         }
  100.     }
  101.    
  102.     /**
  103.      * 关闭连接
  104.      */
  105.     public void close() {
  106.         if (webSocketClient != null) {
  107.             webSocketClient.close();
  108.         }
  109.     }
  110.    
  111.     /**
  112.      * 实时数据模型
  113.      */
  114.     public static class RealTimeData {
  115.         private String pid;
  116.         private String lastNumeric;
  117.         private String bid;
  118.         private String ask;
  119.         private String high;
  120.         private String low;
  121.         private String lastClose;
  122.         private String pc;
  123.         private String pcp;
  124.         private String turnoverNumeric;
  125.         private String time;
  126.         private String timestamp;
  127.         private Integer type;
  128.         
  129.         // Getters and Setters
  130.         public String getPid() { return pid; }
  131.         public void setPid(String pid) { this.pid = pid; }
  132.         public String getLastNumeric() { return lastNumeric; }
  133.         public void setLastNumeric(String lastNumeric) { this.lastNumeric = lastNumeric; }
  134.         public String getBid() { return bid; }
  135.         public void setBid(String bid) { this.bid = bid; }
  136.         public String getAsk() { return ask; }
  137.         public void setAsk(String ask) { this.ask = ask; }
  138.         public String getHigh() { return high; }
  139.         public void setHigh(String high) { this.high = high; }
  140.         public String getLow() { return low; }
  141.         public void setLow(String low) { this.low = low; }
  142.         public String getLastClose() { return lastClose; }
  143.         public void setLastClose(String lastClose) { this.lastClose = lastClose; }
  144.         public String getPc() { return pc; }
  145.         public void setPc(String pc) { this.pc = pc; }
  146.         public String getPcp() { return pcp; }
  147.         public void setPcp(String pcp) { this.pcp = pcp; }
  148.         public String getTurnoverNumeric() { return turnoverNumeric; }
  149.         public void setTurnoverNumeric(String turnoverNumeric) { this.turnoverNumeric = turnoverNumeric; }
  150.         public String getTime() { return time; }
  151.         public void setTime(String time) { this.time = time; }
  152.         public String getTimestamp() { return timestamp; }
  153.         public void setTimestamp(String timestamp) { this.timestamp = timestamp; }
  154.         public Integer getType() { return type; }
  155.         public void setType(Integer type) { this.type = type; }
  156.     }
  157. }
复制代码
6. 服务类
  1. package com.stocktv.india.service;
  2. import com.stocktv.india.client.StockTVHttpClient;
  3. import com.stocktv.india.client.StockTVWebSocketClient;
  4. import com.stocktv.india.config.StockTVConfig;
  5. import com.stocktv.india.model.Index;
  6. import com.stocktv.india.model.KLine;
  7. import com.stocktv.india.model.Stock;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import java.util.List;
  11. public class IndiaStockService {
  12.    
  13.     private static final Logger logger = LoggerFactory.getLogger(IndiaStockService.class);
  14.    
  15.     private final StockTVHttpClient httpClient;
  16.     private final StockTVWebSocketClient webSocketClient;
  17.    
  18.     public IndiaStockService(String apiKey) {
  19.         StockTVConfig config = new StockTVConfig(apiKey);
  20.         this.httpClient = new StockTVHttpClient(config);
  21.         this.webSocketClient = new StockTVWebSocketClient(config);
  22.     }
  23.    
  24.     /**
  25.      * 获取Nifty 50成分股
  26.      */
  27.     public List<Stock> getNifty50Stocks() {
  28.         try {
  29.             // 获取前50只股票(实际应该根据Nifty 50成分股列表查询)
  30.             return httpClient.getIndiaStocks(50, 1);
  31.         } catch (Exception e) {
  32.             logger.error("获取Nifty 50成分股失败", e);
  33.             throw new RuntimeException(e);
  34.         }
  35.     }
  36.    
  37.     /**
  38.      * 获取印度主要指数
  39.      */
  40.     public List<Index> getMajorIndices() {
  41.         try {
  42.             return httpClient.getIndiaIndices();
  43.         } catch (Exception e) {
  44.             logger.error("获取印度指数失败", e);
  45.             throw new RuntimeException(e);
  46.         }
  47.     }
  48.    
  49.     /**
  50.      * 查询特定股票
  51.      */
  52.     public List<Stock> getStockBySymbol(String symbol) {
  53.         try {
  54.             return httpClient.queryStock(null, symbol, null);
  55.         } catch (Exception e) {
  56.             logger.error("查询股票失败: " + symbol, e);
  57.             throw new RuntimeException(e);
  58.         }
  59.     }
  60.    
  61.     /**
  62.      * 获取股票K线数据
  63.      */
  64.     public List<KLine> getStockKLine(Long pid, String interval) {
  65.         try {
  66.             return httpClient.getKLineData(pid, interval);
  67.         } catch (Exception e) {
  68.             logger.error("获取K线数据失败: pid=" + pid, e);
  69.             throw new RuntimeException(e);
  70.         }
  71.     }
  72.    
  73.     /**
  74.      * 获取涨幅榜
  75.      */
  76.     public List<Stock> getGainers() {
  77.         try {
  78.             return httpClient.getUpDownList(1); // 1表示涨幅榜
  79.         } catch (Exception e) {
  80.             logger.error("获取涨幅榜失败", e);
  81.             throw new RuntimeException(e);
  82.         }
  83.     }
  84.    
  85.     /**
  86.      * 启动实时数据监听
  87.      */
  88.     public void startRealTimeMonitoring() {
  89.         try {
  90.             webSocketClient.connect();
  91.             logger.info("实时数据监听已启动");
  92.         } catch (Exception e) {
  93.             logger.error("启动实时数据监听失败", e);
  94.             throw new RuntimeException(e);
  95.         }
  96.     }
  97.    
  98.     /**
  99.      * 停止实时数据监听
  100.      */
  101.     public void stopRealTimeMonitoring() {
  102.         webSocketClient.close();
  103.         logger.info("实时数据监听已停止");
  104.     }
  105. }
复制代码
7. 使用示例
  1. package com.stocktv.india.demo;
  2. import com.stocktv.india.service.IndiaStockService;
  3. import com.stocktv.india.client.StockTVWebSocketClient;
  4. import com.stocktv.india.model.Index;
  5. import com.stocktv.india.model.KLine;
  6. import com.stocktv.india.model.Stock;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import java.util.List;
  10. public class IndiaStockDemo {
  11.    
  12.     private static final Logger logger = LoggerFactory.getLogger(IndiaStockDemo.class);
  13.    
  14.     public static void main(String[] args) {
  15.         // 替换为实际的 API Key
  16.         String apiKey = "您的API_KEY";
  17.         
  18.         IndiaStockService stockService = new IndiaStockService(apiKey);
  19.         
  20.         try {
  21.             // 1. 获取印度主要指数
  22.             logger.info("=== 印度主要指数 ===");
  23.             List<Index> indices = stockService.getMajorIndices();
  24.             indices.forEach(index ->
  25.                 logger.info("{}: {} ({}{}%)",
  26.                     index.getName(), index.getLastPrice(),
  27.                     index.getChange().doubleValue() > 0 ? "+" : "",
  28.                     index.getChangePercent())
  29.             );
  30.             
  31.             // 2. 获取Nifty 50成分股
  32.             logger.info("\n=== Nifty 50成分股(示例)===");
  33.             List<Stock> niftyStocks = stockService.getNifty50Stocks();
  34.             niftyStocks.stream().limit(10).forEach(stock ->
  35.                 logger.info("{} ({}) : {} INR, 涨跌幅: {}%",
  36.                     stock.getSymbol(), stock.getName(),
  37.                     stock.getLastPrice(), stock.getChangePercent())
  38.             );
  39.             
  40.             // 3. 查询特定股票
  41.             logger.info("\n=== 查询RELIANCE股票 ===");
  42.             List<Stock> relianceStock = stockService.getStockBySymbol("RELIANCE");
  43.             if (!relianceStock.isEmpty()) {
  44.                 Stock stock = relianceStock.get(0);
  45.                 logger.info("Reliance Industries: {} INR, 成交量: {}",
  46.                     stock.getLastPrice(), stock.getVolume());
  47.             }
  48.             
  49.             // 4. 获取K线数据
  50.             logger.info("\n=== RELIANCE日K线数据 ===");
  51.             if (!relianceStock.isEmpty()) {
  52.                 Long pid = relianceStock.get(0).getId();
  53.                 List<KLine> kLines = stockService.getStockKLine(pid, "P1D");
  54.                 kLines.stream().limit(5).forEach(kLine ->
  55.                     logger.info("时间: {}, 开: {}, 高: {}, 低: {}, 收: {}",
  56.                         kLine.getTimestamp(), kLine.getOpen(),
  57.                         kLine.getHigh(), kLine.getLow(), kLine.getClose())
  58.                 );
  59.             }
  60.             
  61.             // 5. 获取涨幅榜
  62.             logger.info("\n=== 今日涨幅榜 ===");
  63.             List<Stock> gainers = stockService.getGainers();
  64.             gainers.stream().limit(5).forEach(stock ->
  65.                 logger.info("{}: {} INR, 涨幅: {}%",
  66.                     stock.getSymbol(), stock.getLastPrice(), stock.getChangePercent())
  67.             );
  68.             
  69.             // 6. 启动实时数据监听(可选)
  70.             logger.info("\n=== 启动实时数据监听 ===");
  71.             // stockService.startRealTimeMonitoring();
  72.             
  73.             // 保持程序运行一段时间
  74.             Thread.sleep(30000);
  75.             
  76.             // 停止实时数据监听
  77.             // stockService.stopRealTimeMonitoring();
  78.             
  79.         } catch (Exception e) {
  80.             logger.error("演示程序执行失败", e);
  81.         }
  82.     }
  83. }
复制代码
8. 自定义实时数据处理

如果需要自定义实时数据处理逻辑,可以继承 StockTVWebSocketClient:
  1. package com.stocktv.india.custom;
  2. import com.stocktv.india.client.StockTVWebSocketClient;
  3. import com.stocktv.india.config.StockTVConfig;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. public class CustomWebSocketClient extends StockTVWebSocketClient {
  7.    
  8.     private static final Logger logger = LoggerFactory.getLogger(CustomWebSocketClient.class);
  9.    
  10.     public CustomWebSocketClient(StockTVConfig config) {
  11.         super(config);
  12.     }
  13.    
  14.     @Override
  15.     protected void onRealTimeData(RealTimeData data) {
  16.         // 自定义实时数据处理逻辑
  17.         if ("7310".equals(data.getPid())) { // RELIANCE的PID
  18.             logger.info("RELIANCE实时行情 - 价格: {}, 涨跌幅: {}%, 成交量: {}",
  19.                 data.getLastNumeric(), data.getPcp(), data.getTurnoverNumeric());
  20.         }
  21.         
  22.         // 可以在这里添加交易逻辑、报警逻辑等
  23.         if (Double.parseDouble(data.getPcp()) > 5.0) {
  24.             logger.warn("股票 {} 涨幅超过5%: {}%", data.getPid(), data.getPcp());
  25.         }
  26.     }
  27. }
复制代码
9. 配置说明

时间间隔参数


  • PT5M - 5分钟K线
  • PT15M - 15分钟K线
  • PT1H - 1小时K线
  • P1D - 日K线
  • P1W - 周K线
  • P1M - 月K线
排行榜类型


  • 1 - 涨幅榜
  • 2 - 跌幅榜
  • 3 - 涨停榜
  • 4 - 跌停榜
10. 注意事项


  • API Key管理: 建议从配置文件或环境变量读取API Key
  • 错误处理: 所有API调用都需要适当的异常处理
  • 频率限制: 注意API的调用频率限制
  • 连接管理: WebSocket连接需要处理重连逻辑
  • 数据缓存: 对于不经常变化的数据可以实施缓存
这个完整的Java实现提供了对接印度股票数据源的所有核心功能,可以根据具体需求进行扩展和优化。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

15 小时前

举报

这个好,看起来很实用
您需要登录后才可以回帖 登录 | 立即注册