找回密码
 立即注册
首页 业界区 安全 使用Java对接印度股票市场API 实时数据、IPO和K线(Klin ...

使用Java对接印度股票市场API 实时数据、IPO和K线(Kline)的PHP对接方案

湄圳啸 昨天 20:57
我将为您提供使用Java对接印度股票API的详细方案。根据文档内容,StockTV API支持印度股票数据,印度的countryId为14。
Java对接StockTV印度股票API

一、环境准备与基础配置

1. 添加依赖

在pom.xml中添加必要的依赖:
  1. <dependencies>
  2.    
  3.     <dependency>
  4.         <groupId>org.apache.httpcomponents</groupId>
  5.         httpclient</artifactId>
  6.         <version>4.5.13</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. </dependencies>
复制代码
2. 基础配置类
  1. package com.stocktv.india;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.util.EntityUtils;
  9. import java.io.IOException;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. public class StockTVIndiaAPI {
  13.     private static final String BASE_URL = "https://api.stocktv.top";
  14.     private static final String API_KEY = "您的API_KEY"; // 请替换为实际的Key
  15.     private static final ObjectMapper objectMapper = new ObjectMapper();
  16.     private static final int INDIA_COUNTRY_ID = 14; // 印度的countryId
  17.    
  18.     /**
  19.      * 发送HTTP GET请求
  20.      */
  21.     private static String sendGetRequest(String endpoint, Map<String, String> params) throws IOException {
  22.         StringBuilder urlBuilder = new StringBuilder(BASE_URL + endpoint);
  23.         params.put("key", API_KEY);
  24.         
  25.         if (!params.isEmpty()) {
  26.             urlBuilder.append("?");
  27.             for (Map.Entry<String, String> entry : params.entrySet()) {
  28.                 urlBuilder.append(entry.getKey())
  29.                           .append("=")
  30.                           .append(java.net.URLEncoder.encode(entry.getValue(), "UTF-8"))
  31.                           .append("&");
  32.             }
  33.             urlBuilder.deleteCharAt(urlBuilder.length() - 1); // 移除最后一个&
  34.         }
  35.         
  36.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  37.             HttpGet httpGet = new HttpGet(urlBuilder.toString());
  38.             try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
  39.                 HttpEntity entity = response.getEntity();
  40.                 if (entity != null) {
  41.                     return EntityUtils.toString(entity);
  42.                 }
  43.             }
  44.         }
  45.         return null;
  46.     }
  47.    
  48.     /**
  49.      * 解析JSON响应
  50.      */
  51.     private static <T> T parseResponse(String json, Class<T> clazz) throws IOException {
  52.         return objectMapper.readValue(json, clazz);
  53.     }
  54. }
复制代码
二、核心API接口实现

1. 获取印度股票市场列表
  1. package com.stocktv.india;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import java.util.List;
  4. import java.util.Map;
  5. public class MarketListResponse {
  6.     @JsonProperty("code")
  7.     private int code;
  8.    
  9.     @JsonProperty("message")
  10.     private String message;
  11.    
  12.     @JsonProperty("data")
  13.     private MarketData data;
  14.    
  15.     // 数据类
  16.     public static class MarketData {
  17.         @JsonProperty("records")
  18.         private List<StockRecord> records;
  19.         
  20.         @JsonProperty("total")
  21.         private int total;
  22.         
  23.         @JsonProperty("size")
  24.         private int size;
  25.         
  26.         @JsonProperty("current")
  27.         private int current;
  28.         
  29.         @JsonProperty("pages")
  30.         private int pages;
  31.         
  32.         // Getters
  33.         public List<StockRecord> getRecords() { return records; }
  34.         public int getTotal() { return total; }
  35.         public int getSize() { return size; }
  36.         public int getCurrent() { return current; }
  37.         public int getPages() { return pages; }
  38.     }
  39.    
  40.     // 股票记录类
  41.     public static class StockRecord {
  42.         @JsonProperty("id")
  43.         private Long id; // pid
  44.         
  45.         @JsonProperty("name")
  46.         private String name; // 股票名称
  47.         
  48.         @JsonProperty("symbol")
  49.         private String symbol; // 股票代码
  50.         
  51.         @JsonProperty("last")
  52.         private Double last; // 最新价
  53.         
  54.         @JsonProperty("chg")
  55.         private Double chg; // 涨跌额
  56.         
  57.         @JsonProperty("chgPct")
  58.         private Double chgPct; // 涨跌百分比
  59.         
  60.         @JsonProperty("high")
  61.         private Double high; // 最高价
  62.         
  63.         @JsonProperty("low")
  64.         private Double low; // 最低价
  65.         
  66.         @JsonProperty("volume")
  67.         private Long volume; // 成交量
  68.         
  69.         @JsonProperty("open")
  70.         private Boolean open; // 是否开市
  71.         
  72.         @JsonProperty("countryId")
  73.         private Integer countryId; // 国家ID
  74.         
  75.         @JsonProperty("countryNameTranslated")
  76.         private String countryNameTranslated; // 国家名称
  77.         
  78.         @JsonProperty("flag")
  79.         private String flag; // 国家简称
  80.         
  81.         @JsonProperty("exchangeId")
  82.         private Integer exchangeId; // 交易所ID
  83.         
  84.         @JsonProperty("lastClose")
  85.         private Double lastClose; // 前收盘价
  86.         
  87.         // Getters
  88.         public Long getId() { return id; }
  89.         public String getName() { return name; }
  90.         public String getSymbol() { return symbol; }
  91.         public Double getLast() { return last; }
  92.         public Double getChg() { return chg; }
  93.         public Double getChgPct() { return chgPct; }
  94.         public Double getHigh() { return high; }
  95.         public Double getLow() { return low; }
  96.         public Long getVolume() { return volume; }
  97.         public Boolean getOpen() { return open; }
  98.         public Integer getCountryId() { return countryId; }
  99.         public String getCountryNameTranslated() { return countryNameTranslated; }
  100.         public String getFlag() { return flag; }
  101.         public Integer getExchangeId() { return exchangeId; }
  102.         public Double getLastClose() { return lastClose; }
  103.     }
  104.    
  105.     // Getters
  106.     public int getCode() { return code; }
  107.     public String getMessage() { return message; }
  108.     public MarketData getData() { return data; }
  109. }
复制代码
  1. package com.stocktv.india;
  2. import java.io.IOException;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class IndiaStockService {
  6.     private static final int INDIA_COUNTRY_ID = 14;
  7.    
  8.     /**
  9.      * 获取印度股票市场列表
  10.      */
  11.     public static MarketListResponse getIndiaStockList(int page, int pageSize) throws IOException {
  12.         Map<String, String> params = new HashMap<>();
  13.         params.put("countryId", String.valueOf(INDIA_COUNTRY_ID));
  14.         params.put("page", String.valueOf(page));
  15.         params.put("pageSize", String.valueOf(pageSize));
  16.         
  17.         String response = StockTVIndiaAPI.sendGetRequest("/stock/stocks", params);
  18.         return StockTVIndiaAPI.parseResponse(response, MarketListResponse.class);
  19.     }
  20.    
  21.     /**
  22.      * 示例:获取印度股票列表并打印
  23.      */
  24.     public static void main(String[] args) {
  25.         try {
  26.             MarketListResponse response = getIndiaStockList(1, 10);
  27.             
  28.             if (response.getCode() == 200 && response.getData() != null) {
  29.                 System.out.println("印度股票列表 (共" + response.getData().getTotal() + "只股票):");
  30.                 System.out.println("==================================================");
  31.                
  32.                 for (MarketListResponse.StockRecord stock : response.getData().getRecords()) {
  33.                     System.out.printf("股票: %-30s 代码: %-10s 最新价: %8.2f 涨跌: %6.2f%%\n",
  34.                             stock.getName(),
  35.                             stock.getSymbol(),
  36.                             stock.getLast(),
  37.                             stock.getChgPct());
  38.                 }
  39.             } else {
  40.                 System.out.println("请求失败: " + response.getMessage());
  41.             }
  42.         } catch (IOException e) {
  43.             e.printStackTrace();
  44.         }
  45.     }
  46. }
复制代码
2. 查询特定印度股票
  1. public class QueryStockResponse {
  2.     @JsonProperty("code")
  3.     private int code;
  4.    
  5.     @JsonProperty("message")
  6.     private String message;
  7.    
  8.     @JsonProperty("data")
  9.     private List<MarketListResponse.StockRecord> data;
  10.    
  11.     // Getters
  12.     public int getCode() { return code; }
  13.     public String getMessage() { return message; }
  14.     public List<MarketListResponse.StockRecord> getData() { return data; }
  15. }
  16. public class IndiaStockQueryService {
  17.     /**
  18.      * 查询印度股票(通过PID、名称或代码)
  19.      */
  20.     public static QueryStockResponse queryIndiaStock(Long pid, String symbol, String name) throws IOException {
  21.         Map<String, String> params = new HashMap<>();
  22.         
  23.         if (pid != null) {
  24.             params.put("id", pid.toString());
  25.         }
  26.         if (symbol != null && !symbol.isEmpty()) {
  27.             params.put("symbol", symbol);
  28.         }
  29.         if (name != null && !name.isEmpty()) {
  30.             params.put("name", name);
  31.         }
  32.         
  33.         String response = StockTVIndiaAPI.sendGetRequest("/stock/queryStocks", params);
  34.         QueryStockResponse result = StockTVIndiaAPI.parseResponse(response, QueryStockResponse.class);
  35.         
  36.         // 筛选印度股票(根据countryId=14或flag='IN')
  37.         if (result.getCode() == 200 && result.getData() != null) {
  38.             List<MarketListResponse.StockRecord> filteredList = result.getData().stream()
  39.                     .filter(stock -> stock.getCountryId() != null && stock.getCountryId() == INDIA_COUNTRY_ID)
  40.                     .collect(Collectors.toList());
  41.             
  42.             // 创建新的响应对象
  43.             QueryStockResponse filteredResponse = new QueryStockResponse();
  44.             filteredResponse.setCode(result.getCode());
  45.             filteredResponse.setMessage(result.getMessage());
  46.             filteredResponse.setData(filteredList);
  47.             
  48.             return filteredResponse;
  49.         }
  50.         
  51.         return result;
  52.     }
  53. }
复制代码
3. 获取印度K线数据
  1. public class KlineData {
  2.     @JsonProperty("time")
  3.     private Long time; // 时间戳
  4.    
  5.     @JsonProperty("open")
  6.     private Double open; // 开盘价
  7.    
  8.     @JsonProperty("high")
  9.     private Double high; // 最高价
  10.    
  11.     @JsonProperty("low")
  12.     private Double low; // 最低价
  13.    
  14.     @JsonProperty("close")
  15.     private Double close; // 收盘价
  16.    
  17.     @JsonProperty("volume")
  18.     private Double volume; // 成交量
  19.    
  20.     @JsonProperty("vo")
  21.     private Double vo; // 成交额
  22.    
  23.     // Getters
  24.     public Long getTime() { return time; }
  25.     public Double getOpen() { return open; }
  26.     public Double getHigh() { return high; }
  27.     public Double getLow() { return low; }
  28.     public Double getClose() { return close; }
  29.     public Double getVolume() { return volume; }
  30.     public Double getVo() { return vo; }
  31. }
  32. public class KlineResponse {
  33.     @JsonProperty("code")
  34.     private int code;
  35.    
  36.     @JsonProperty("message")
  37.     private String message;
  38.    
  39.     @JsonProperty("data")
  40.     private List<KlineData> data;
  41.    
  42.     // Getters
  43.     public int getCode() { return code; }
  44.     public String getMessage() { return message; }
  45.     public List<KlineData> getData() { return data; }
  46. }
  47. public class IndiaKlineService {
  48.     /**
  49.      * 获取印度股票K线数据
  50.      * @param pid 股票PID
  51.      * @param interval 时间间隔: PT5M, PT15M, PT1H, PT5H, P1D, P1W, P1M
  52.      */
  53.     public static KlineResponse getIndiaStockKline(Long pid, String interval) throws IOException {
  54.         Map<String, String> params = new HashMap<>();
  55.         params.put("pid", pid.toString());
  56.         params.put("interval", interval);
  57.         
  58.         String response = StockTVIndiaAPI.sendGetRequest("/stock/kline", params);
  59.         return StockTVIndiaAPI.parseResponse(response, KlineResponse.class);
  60.     }
  61.    
  62.     /**
  63.      * 示例:获取日K线数据
  64.      */
  65.     public static void printDailyKline(Long pid) {
  66.         try {
  67.             KlineResponse response = getIndiaStockKline(pid, "P1D");
  68.             
  69.             if (response.getCode() == 200 && response.getData() != null && !response.getData().isEmpty()) {
  70.                 System.out.println("K线数据 (日线):");
  71.                 System.out.println("==================================================");
  72.                
  73.                 // 显示最近5天的数据
  74.                 int count = Math.min(response.getData().size(), 5);
  75.                 for (int i = response.getData().size() - count; i < response.getData().size(); i++) {
  76.                     KlineData kline = response.getData().get(i);
  77.                     Date date = new Date(kline.getTime());
  78.                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  79.                     
  80.                     System.out.printf("日期: %s 开:%.2f 高:%.2f 低:%.2f 收:%.2f 量:%.0f\n",
  81.                             sdf.format(date),
  82.                             kline.getOpen(),
  83.                             kline.getHigh(),
  84.                             kline.getLow(),
  85.                             kline.getClose(),
  86.                             kline.getVolume());
  87.                 }
  88.             }
  89.         } catch (IOException e) {
  90.             e.printStackTrace();
  91.         }
  92.     }
  93. }
复制代码
4. 获取印度市场指数
  1. public class IndicesResponse {
  2.     @JsonProperty("code")
  3.     private int code;
  4.    
  5.     @JsonProperty("message")
  6.     private String message;
  7.    
  8.     @JsonProperty("data")
  9.     private List<IndexData> data;
  10.    
  11.     public static class IndexData {
  12.         @JsonProperty("id")
  13.         private Long id;
  14.         
  15.         @JsonProperty("name")
  16.         private String name;
  17.         
  18.         @JsonProperty("symbol")
  19.         private String symbol;
  20.         
  21.         @JsonProperty("last")
  22.         private Double last;
  23.         
  24.         @JsonProperty("chg")
  25.         private Double chg;
  26.         
  27.         @JsonProperty("chgPct")
  28.         private Double chgPct;
  29.         
  30.         @JsonProperty("flag")
  31.         private String flag;
  32.         
  33.         @JsonProperty("isOpen")
  34.         private Boolean isOpen;
  35.         
  36.         // Getters
  37.         public Long getId() { return id; }
  38.         public String getName() { return name; }
  39.         public String getSymbol() { return symbol; }
  40.         public Double getLast() { return last; }
  41.         public Double getChg() { return chg; }
  42.         public Double getChgPct() { return chgPct; }
  43.         public String getFlag() { return flag; }
  44.         public Boolean getIsOpen() { return isOpen; }
  45.     }
  46.    
  47.     // Getters
  48.     public int getCode() { return code; }
  49.     public String getMessage() { return message; }
  50.     public List<IndexData> getData() { return data; }
  51. }
  52. public class IndiaIndicesService {
  53.     /**
  54.      * 获取印度市场指数
  55.      */
  56.     public static IndicesResponse getIndiaIndices() throws IOException {
  57.         Map<String, String> params = new HashMap<>();
  58.         params.put("countryId", String.valueOf(INDIA_COUNTRY_ID));
  59.         
  60.         String response = StockTVIndiaAPI.sendGetRequest("/stock/indices", params);
  61.         return StockTVIndiaAPI.parseResponse(response, IndicesResponse.class);
  62.     }
  63. }
复制代码
5. 获取印度IPO新股日历
  1. public class IpoResponse {
  2.     @JsonProperty("code")
  3.     private int code;
  4.    
  5.     @JsonProperty("message")
  6.     private String message;
  7.    
  8.     @JsonProperty("data")
  9.     private List<IpoData> data;
  10.    
  11.     public static class IpoData {
  12.         @JsonProperty("id")
  13.         private Long id;
  14.         
  15.         @JsonProperty("ipoListing")
  16.         private Long ipoListing; // 上市时间戳
  17.         
  18.         @JsonProperty("country")
  19.         private String country;
  20.         
  21.         @JsonProperty("company")
  22.         private String company;
  23.         
  24.         @JsonProperty("exchange")
  25.         private String exchange;
  26.         
  27.         @JsonProperty("ipoPrice")
  28.         private String ipoPrice;
  29.         
  30.         @JsonProperty("last")
  31.         private String last;
  32.         
  33.         @JsonProperty("symbol")
  34.         private String symbol;
  35.         
  36.         @JsonProperty("date")
  37.         private String date;
  38.         
  39.         @JsonProperty("pid")
  40.         private Long pid;
  41.         
  42.         // Getters
  43.         public Long getId() { return id; }
  44.         public Long getIpoListing() { return ipoListing; }
  45.         public String getCountry() { return country; }
  46.         public String getCompany() { return company; }
  47.         public String getExchange() { return exchange; }
  48.         public String getIpoPrice() { return ipoPrice; }
  49.         public String getLast() { return last; }
  50.         public String getSymbol() { return symbol; }
  51.         public String getDate() { return date; }
  52.         public Long getPid() { return pid; }
  53.     }
  54.    
  55.     // Getters
  56.     public int getCode() { return code; }
  57.     public String getMessage() { return message; }
  58.     public List<IpoData> getData() { return data; }
  59. }
  60. public class IndiaIpoService {
  61.     /**
  62.      * 获取印度IPO信息
  63.      * @param type 1=未上市, 2=已上市
  64.      */
  65.     public static IpoResponse getIndiaIpo(Integer type) throws IOException {
  66.         Map<String, String> params = new HashMap<>();
  67.         params.put("countryId", String.valueOf(INDIA_COUNTRY_ID));
  68.         
  69.         if (type != null && (type == 1 || type == 2)) {
  70.             params.put("type", type.toString());
  71.         }
  72.         
  73.         String response = StockTVIndiaAPI.sendGetRequest("/stock/getIpo", params);
  74.         return StockTVIndiaAPI.parseResponse(response, IpoResponse.class);
  75.     }
  76. }
复制代码
6. 获取印度涨跌排行榜
  1. public class UpDownListResponse {
  2.     @JsonProperty("code")
  3.     private int code;
  4.    
  5.     @JsonProperty("message")
  6.     private String message;
  7.    
  8.     @JsonProperty("data")
  9.     private List<MarketListResponse.StockRecord> data;
  10.    
  11.     // Getters
  12.     public int getCode() { return code; }
  13.     public String getMessage() { return message; }
  14.     public List<MarketListResponse.StockRecord> getData() { return data; }
  15. }
  16. public class IndiaRankService {
  17.     /**
  18.      * 获取印度股票排行榜
  19.      * @param type 1涨幅榜 2跌幅榜 3涨停榜 4跌停榜
  20.      */
  21.     public static UpDownListResponse getIndiaStockRank(int type) throws IOException {
  22.         Map<String, String> params = new HashMap<>();
  23.         params.put("countryId", String.valueOf(INDIA_COUNTRY_ID));
  24.         params.put("type", String.valueOf(type));
  25.         
  26.         String response = StockTVIndiaAPI.sendGetRequest("/stock/updownList", params);
  27.         return StockTVIndiaAPI.parseResponse(response, UpDownListResponse.class);
  28.     }
  29.    
  30.     /**
  31.      * 示例:打印涨幅榜TOP 10
  32.      */
  33.     public static void printTopGainers() {
  34.         try {
  35.             UpDownListResponse response = getIndiaStockRank(1);
  36.             
  37.             if (response.getCode() == 200 && response.getData() != null) {
  38.                 System.out.println("印度股票涨幅榜 TOP 10:");
  39.                 System.out.println("==================================================");
  40.                
  41.                 int count = Math.min(response.getData().size(), 10);
  42.                 for (int i = 0; i < count; i++) {
  43.                     MarketListResponse.StockRecord stock = response.getData().get(i);
  44.                     System.out.printf("%2d. %-30s %-10s %7.2f%%\n",
  45.                             i + 1,
  46.                             stock.getName(),
  47.                             stock.getSymbol(),
  48.                             stock.getChgPct());
  49.                 }
  50.             }
  51.         } catch (IOException e) {
  52.             e.printStackTrace();
  53.         }
  54.     }
  55. }
复制代码
三、WebSocket实时数据(核心)
  1. package com.stocktv.india.websocket;
  2. import org.java_websocket.client.WebSocketClient;
  3. import org.java_websocket.handshake.ServerHandshake;
  4. import org.json.JSONObject;
  5. import java.net.URI;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Timer;
  9. import java.util.TimerTask;
  10. public class IndiaStockWebSocketClient extends WebSocketClient {
  11.     private static final String WS_URL = "wss://ws-api.stocktv.top/connect?key=您的API_KEY";
  12.     private List<Long> subscribedPids = new ArrayList<>();
  13.    
  14.     public IndiaStockWebSocketClient() {
  15.         super(URI.create(WS_URL));
  16.     }
  17.    
  18.     @Override
  19.     public void onOpen(ServerHandshake handshakedata) {
  20.         System.out.println("WebSocket连接已建立");
  21.         
  22.         // 连接成功后发送订阅消息
  23.         if (!subscribedPids.isEmpty()) {
  24.             subscribeToPids(subscribedPids);
  25.         }
  26.         
  27.         // 启动心跳定时器
  28.         startHeartbeat();
  29.     }
  30.    
  31.     @Override
  32.     public void onMessage(String message) {
  33.         // 解析实时数据
  34.         JSONObject data = new JSONObject(message);
  35.         String pid = data.optString("pid");
  36.         String lastPrice = data.optString("last_numeric");
  37.         String change = data.optString("pc");
  38.         String changePercent = data.optString("pcp");
  39.         String volume = data.optString("turnover_numeric");
  40.         
  41.         System.out.printf("实时数据 - PID: %s, 最新价: %s, 涨跌额: %s, 涨跌幅: %s%%, 成交量: %s\n",
  42.                 pid, lastPrice, change, changePercent, volume);
  43.     }
  44.    
  45.     @Override
  46.     public void onClose(int code, String reason, boolean remote) {
  47.         System.out.println("WebSocket连接关闭: " + reason);
  48.     }
  49.    
  50.     @Override
  51.     public void onError(Exception ex) {
  52.         System.err.println("WebSocket错误: " + ex.getMessage());
  53.     }
  54.    
  55.     /**
  56.      * 订阅股票PID
  57.      */
  58.     public void subscribeToPids(List<Long> pids) {
  59.         this.subscribedPids = pids;
  60.         
  61.         if (isOpen()) {
  62.             JSONObject subscribeMsg = new JSONObject();
  63.             subscribeMsg.put("action", "subscribe");
  64.             
  65.             List<String> pidStrings = new ArrayList<>();
  66.             for (Long pid : pids) {
  67.                 pidStrings.add(pid.toString());
  68.             }
  69.             subscribeMsg.put("pids", pidStrings);
  70.             
  71.             send(subscribeMsg.toString());
  72.             System.out.println("已发送订阅请求: " + subscribeMsg.toString());
  73.         }
  74.     }
  75.    
  76.     /**
  77.      * 启动心跳定时器
  78.      */
  79.     private void startHeartbeat() {
  80.         Timer timer = new Timer(true);
  81.         timer.scheduleAtFixedRate(new TimerTask() {
  82.             @Override
  83.             public void run() {
  84.                 if (isOpen()) {
  85.                     send(""); // 发送空消息作为心跳
  86.                     System.out.println("发送心跳...");
  87.                 }
  88.             }
  89.         }, 0, 30000); // 每30秒发送一次心跳
  90.     }
  91.    
  92.     /**
  93.      * 使用示例
  94.      */
  95.     public static void main(String[] args) throws Exception {
  96.         IndiaStockWebSocketClient client = new IndiaStockWebSocketClient();
  97.         
  98.         // 连接到WebSocket服务器
  99.         client.connectBlocking(); // 阻塞连接
  100.         
  101.         // 等待连接建立
  102.         Thread.sleep(1000);
  103.         
  104.         // 订阅印度股票(示例PID)
  105.         List<Long> pids = new ArrayList<>();
  106.         pids.add(7310L);  // 示例PID
  107.         pids.add(17976L); // 示例PID
  108.         
  109.         client.subscribeToPids(pids);
  110.         
  111.         // 保持连接
  112.         Thread.sleep(60000); // 保持连接60秒
  113.         
  114.         client.close();
  115.     }
  116. }
复制代码
四、完整使用示例
  1. package com.stocktv.india;
  2. import java.io.IOException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. public class IndiaStockAPIDemo {
  6.     public static void main(String[] args) {
  7.         try {
  8.             // 1. 获取印度股票列表
  9.             System.out.println("=== 印度股票列表 ===");
  10.             MarketListResponse stockList = IndiaStockService.getIndiaStockList(1, 10);
  11.             if (stockList.getCode() == 200) {
  12.                 for (MarketListResponse.StockRecord stock : stockList.getData().getRecords()) {
  13.                     System.out.printf("%s (%s): %.2f 涨跌: %.2f%%\n",
  14.                             stock.getName(),
  15.                             stock.getSymbol(),
  16.                             stock.getLast(),
  17.                             stock.getChgPct());
  18.                 }
  19.             }
  20.             
  21.             // 2. 获取印度市场指数
  22.             System.out.println("\n=== 印度市场指数 ===");
  23.             IndicesResponse indices = IndiaIndicesService.getIndiaIndices();
  24.             if (indices.getCode() == 200) {
  25.                 for (IndicesResponse.IndexData index : indices.getData()) {
  26.                     System.out.printf("%s (%s): %.2f 涨跌: %.2f%%\n",
  27.                             index.getName(),
  28.                             index.getSymbol(),
  29.                             index.getLast(),
  30.                             index.getChgPct());
  31.                 }
  32.             }
  33.             
  34.             // 3. 获取印度IPO信息
  35.             System.out.println("\n=== 印度IPO新股 ===");
  36.             IpoResponse ipoList = IndiaIpoService.getIndiaIpo(1); // 未上市IPO
  37.             if (ipoList.getCode() == 200 && ipoList.getData() != null) {
  38.                 for (IpoResponse.IpoData ipo : ipoList.getData()) {
  39.                     Date listingDate = new Date(ipo.getIpoListing() * 1000);
  40.                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  41.                     System.out.printf("公司: %s, 发行价: %s, 上市日期: %s\n",
  42.                             ipo.getCompany(),
  43.                             ipo.getIpoPrice(),
  44.                             sdf.format(listingDate));
  45.                 }
  46.             }
  47.             
  48.             // 4. 获取涨跌排行榜
  49.             System.out.println("\n=== 印度股票涨幅榜 ===");
  50.             IndiaRankService.printTopGainers();
  51.             
  52.             // 5. 获取K线数据(假设有股票PID)
  53.             System.out.println("\n=== 印度股票K线数据 ===");
  54.             IndiaKlineService.printDailyKline(7310L); // 示例PID
  55.             
  56.         } catch (IOException e) {
  57.             System.err.println("API调用失败: " + e.getMessage());
  58.             e.printStackTrace();
  59.         }
  60.     }
  61. }
复制代码
五、重要注意事项


  • API Key:所有请求都需要在URL参数中添加key=您的API_KEY
  • 国家ID:印度固定为countryId=14
  • 实时数据:使用WebSocket接口获取实时行情
  • 错误处理:始终检查响应中的code字段,200表示成功
  • 并发限制:合理控制请求频率,避免过度调用
六、数据结构说明

从文档中的示例数据可以看到,印度股票数据包含以下关键字段:

  • 基础信息:id(PID), name, symbol, countryId(14), flag("IN")
  • 行情数据:last, chg, chgPct, high, low, volume
  • 时间信息:time, open(是否开市)
  • 技术指标:technicalDay, technicalHour等
  • 基本面数据:fundamentalMarketCap, fundamentalRevenue等
七、最佳实践建议


  • 连接池管理:使用HTTP连接池提高性能
  • 异常处理:添加重试机制和熔断机制
  • 数据缓存:对频繁访问的数据进行缓存
  • 日志记录:记录API调用和错误信息
  • 配置管理:将API Key等配置信息放在配置文件中
这个Java实现方案涵盖了印度股票数据的实时行情、K线、指数、IPO和排行榜等核心功能。您可以根据具体需求选择使用HTTP接口或WebSocket接口获取数据。

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

相关推荐

您需要登录后才可以回帖 登录 | 立即注册