Compare commits

..

147 Commits

Author SHA1 Message Date
quangnguyen202
59e4aa9e1a Add alternal source 2024-09-19 14:33:22 +07:00
gavin
bae645e3c6 修复官方查询时名称写死的问题 2024-09-12 14:15:31 +08:00
gavin
94d9aea2c8 指定股票更换详情测试代码 2024-09-10 13:11:01 +08:00
gavin
5ae9762d45 指定股票更换详情测试代码 2024-09-09 14:59:38 +08:00
quangnguyen202
ece52491dd Merge branch 'refactor/optimization' into 'develop'
Optimize

See merge request india/india_market_java!38
2024-09-09 06:54:16 +00:00
quangnguyen202
6235d41711 Optimize 2024-09-06 11:17:41 +07:00
vpckiet
c865eccaf4 Merge branch 'refactor/optimization' into 'develop'
Optimize code

See merge request india/india_market_java!37
2024-09-06 01:53:33 +00:00
quangnguyen202
136020a497 Update 2024-09-05 16:30:46 +07:00
quangnguyen202
d7da59aca1 Optimize code 2024-09-05 15:59:13 +07:00
gavin
8427bed427 指定股票更换详情测试代码 2024-09-04 12:52:17 +08:00
gavin
269f02b79d 指定股票更换详情测试代码 2024-09-04 11:56:04 +08:00
gavin
7cc456bcd8 同步手动更新代码 2024-09-02 15:32:50 +08:00
vpckiet
be05d403af Merge branch 'bug/craw_img_news' into 'develop'
update crawl img news

See merge request india/india_market_java!33
2024-09-02 06:47:52 +00:00
Congkiet4695
4a29bf6659 update crawl img news 2024-09-02 13:46:22 +07:00
gavin
5b2eb8519a 大盘缓存数据改为6秒 2024-07-26 15:04:56 +08:00
gavin
2e4449bd64 大盘数据更换moneycontrol 数据源 2024-07-26 14:53:50 +08:00
Thanh Nguyen
b321fd9d4e Update automatic-deployment link 2024-07-23 09:39:48 +07:00
gavin
2f9e54bf4f 更改数据库连接
更新新闻时间格式为24小时制
2024-07-12 15:33:25 +08:00
3bb354bbc6 Merge remote-tracking branch 'origin/develop' into develop 2024-07-08 12:38:26 +08:00
a403cba964 fix: 时间字段错乱 2024-07-08 12:38:13 +08:00
Achilles
99bde81670 Merge remote-tracking branch 'origin/develop' into develop 2024-06-28 17:00:04 +08:00
Achilles
bae941828e 代码优化和优化 2024-06-28 16:59:58 +08:00
gs
2f86571578 价格问题处理 2024-06-25 18:00:21 +08:00
gs
d491bef735 新闻时间处理 2024-06-25 17:45:15 +08:00
gs
74c64eb7d4 Merge remote-tracking branch 'origin/develop' into develop
# Conflicts:
#	src/main/java/cn/stock/market/web/StockApiController.java
2024-06-20 16:55:50 +08:00
gs
f50b6b5519 新闻时间处理 2024-06-20 16:54:56 +08:00
2446d89b30 fix: 时间字段错乱 2024-06-20 16:33:38 +08:00
gs
33a68eb7e8 新闻处理 2024-06-20 14:50:15 +08:00
gs
7b0a08150d Merge remote-tracking branch 'origin/develop' into develop
# Conflicts:
#	src/main/java/cn/stock/market/domain/basic/service/StockService.java
2024-06-20 14:47:53 +08:00
gs
146e9d9bc0 新闻处理 2024-06-20 14:47:04 +08:00
william
59a0480be0 Merge branch 'main' into 'develop'
# Conflicts:
#   docker-entrypoint.sh
2024-05-06 12:33:09 +00:00
william
5fe3200ea1 fix bug 2024-05-06 12:31:40 +00:00
vercel
943c6c77e4 fix: 新闻抓取优化 2024-05-05 13:53:46 +08:00
william
b2e93f646c 1 2024-05-01 11:57:12 +08:00
william
9af156cd4a 1 2024-05-01 11:53:13 +08:00
william
8660354dc1 fix bug 2024-05-01 01:35:02 +08:00
william
ed924d85ae Merge branch 'main' of gitlab.main99.com:india/india_market_java 2024-05-01 01:30:32 +08:00
william
b7f0793d88 修复错误 2024-05-01 01:30:27 +08:00
Administrator
4e9810e074 Merge branch 'develop' into 'main'
Merge branch 'main' into 'develop'

See merge request india/india_market_java!25
2024-04-30 16:37:43 +00:00
Administrator
d2e186cae6 Merge branch 'main' into 'develop'
Main

See merge request india/india_market_java!24
2024-04-30 16:19:23 +00:00
william
d8862710a1 兼容路径错误问题 2024-05-01 00:17:46 +08:00
william
efae848b4f 修复环境变量 2024-04-30 21:47:07 +08:00
william
0cec277282 修改命名 2024-04-29 23:35:09 +08:00
Administrator
f6cc52bb9c 更改docker镜像的名称 2024-04-29 10:23:45 +00:00
guoshuai
45fe49a398 Merge branch 'develop' into 'main'
fix:优化money股票K线图1w和1m

See merge request india/india_market_java!23
2024-04-29 07:16:55 +00:00
xiaoliuhu
e0007aa6cc fix:优化money股票K线图1w和1m 2024-04-29 14:10:48 +08:00
william
3982de78be 1 2024-04-27 09:00:47 +08:00
william
d24ce12179 1 2024-04-27 08:58:06 +08:00
william
7524952c46 docker镜像构建 2024-04-27 08:46:05 +08:00
guoshuai
40555fcd64 Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!22
2024-04-25 11:54:10 +00:00
xiaoliuhu
30d95acdcf fix:优化money股票K线图 2024-04-25 10:09:59 +08:00
xiaoliuhu
c340bba073 fix:优化money股票K线图1H和1D只返回当天数据 2024-04-24 22:21:04 +08:00
guoshuai
4a3b75e0c6 Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!21
2024-04-24 14:14:25 +00:00
xiaoliuhu
33c83af353 fix:优化money股票K线图1H和1D只返回当天数据 2024-04-24 22:11:49 +08:00
xiaoliuhu
11130a9eda fix:优化money股票K线图1H和1D只返回当天数据 2024-04-24 21:50:28 +08:00
xiaoliuhu
5a95d6be9a 优化money股票K线图1H和1D只返回当天数据 2024-04-24 21:24:03 +08:00
xiaoliuhu
e680bee42b fix:优化money股票K线图1H和1D只返回当天数据 2024-04-24 21:18:39 +08:00
xiaoliuhu
fbc7815365 fix:修改economictimes获取指数详情bug 2024-04-20 21:32:52 +08:00
xiaoliuhu
37bb619e24 fix:修改economictimes获取指数详情bug 2024-04-20 21:28:18 +08:00
xiaoliuhu
a7e6cc0b05 fix:拓展可自定义时间缓存接口,app指数接口增加缓存1分钟 2024-04-20 19:20:05 +08:00
xiaoliuhu
ece782497f fix:app指数接口增加economictimes数据源兜底 2024-04-20 19:11:47 +08:00
zhangjian
4b25467bd2 日志打印优化 2024-04-20 17:16:43 +08:00
zhangjian
5b3cc7e156 印度--获取指定指数信息接口getIndiaIndexByToday.do: BToday添加兜底数据源Growwin 2024-04-20 17:01:59 +08:00
zhangjian
55c9865845 money股票推荐getTopGainer和 getTopLoser接口根据股票名称去重 2024-04-20 14:26:15 +08:00
zhangjian
07d3b0623e money股票推荐相关getTopActives接口根据股票名称去重 2024-04-20 10:33:50 +08:00
Achilles
03e6d9ecb9 Merge remote-tracking branch 'origin/develop' into develop 2024-04-07 15:51:23 +08:00
Achilles
cf97e84538 测试环境修改最新的数据库 2024-04-07 15:50:44 +08:00
rplees
63014508d4 Update .gitlab-ci.yml 2024-04-04 10:53:06 +00:00
guoshuai
85fe98cc29 Merge branch 'develop' into 'main'
hotfix: 脏数据情况下的一个股票处理

See merge request india/india_market_java!20
2024-03-26 11:21:53 +00:00
Achilles
7de157fc2e hotfix: 脏数据情况下的一个股票处理 2024-03-26 14:11:12 +08:00
guoshuai
9d6413bc43 Merge branch 'develop' into 'main'
hotfix:价格优化

See merge request india/india_market_java!19
2024-03-21 09:42:50 +00:00
Achilles
fb4840f8a9 hotfix:价格优化 2024-03-21 17:39:47 +08:00
guoshuai
8c472d2973 Merge branch 'develop' into 'main'
代码优化

See merge request india/india_market_java!18
2024-03-18 10:19:06 +00:00
Achilles
5a9029f950 代码优化 2024-03-18 18:12:57 +08:00
rplees
1d945f126e Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!17
2024-03-15 06:07:14 +00:00
zhangjian
11d4062859 修改获取money数据源的kline日/周数据返回条数 2024-03-13 14:14:17 +08:00
zhangjian
c1e0bbd77d update pom 2024-03-13 13:52:24 +08:00
Achilles
1314d9271c Merge remote-tracking branch 'origin/develop' into develop 2024-03-13 09:25:40 +08:00
Achilles
df22b2fd22 k线小时单位进行展示 2024-03-13 09:25:14 +08:00
rplees
f4567f94b6 Update .gitlab-ci.yml 2024-02-29 09:57:19 +00:00
rplees
19cb36b33a Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!16
2024-02-23 09:52:23 +00:00
xiaoliuhu
fba16687df fix:修改bug 2024-02-23 15:49:07 +08:00
xiaoliuhu
77c436df1d fix:增加today指数信息 2024-02-23 15:07:23 +08:00
rplees
a977f7c5fe Merge branch 'develop' into 'main'
新闻定时任务新增日志信息

See merge request india/india_market_java!15
2024-02-16 10:39:43 +00:00
dengli
4df20a07a0 新闻定时任务新增日志信息 2024-02-16 18:38:07 +08:00
rplees
f7bf2cb0eb Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!14
2024-02-16 10:13:14 +00:00
dengli
3d59acf8fd Merge remote-tracking branch 'origin/develop' into develop 2024-02-16 18:09:53 +08:00
dengli
3ec78dbe9a 新闻定时任务新增日志信息 2024-02-16 18:09:40 +08:00
guoshuai
de44d54ece Merge branch 'develop' into 'main'
代码返回参数优化

See merge request india/india_market_java!13
2024-02-15 15:47:04 +00:00
gs
4b944f9d84 代码返回参数优化 2024-02-15 23:45:13 +08:00
guoshuai
ff2896a0fd Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!12
2024-02-15 15:04:45 +00:00
gs
92a5ac5be1 Merge remote-tracking branch 'origin/develop' into develop 2024-02-15 23:02:54 +08:00
gs
3e0d209b34 调整一下抓取股票的时间 2024-02-15 23:02:45 +08:00
rplees
c515b0ff0e Update .gitlab-ci.yml 2024-02-13 06:29:28 +00:00
gs
d15535bf9b 调整一下抓取股票的时间 2024-02-13 14:10:14 +08:00
rplees
877154c1cc Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!11
2024-02-12 14:11:14 +00:00
gs
f4dd0b4542 调整一下抓取股票的时间 2024-02-12 19:28:17 +08:00
gs
4caad1b6a5 调整一下抓取股票的时间 2024-02-12 15:14:10 +08:00
rplees
96c23943ab Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!10
2024-02-08 12:35:11 +00:00
dengli
2b3f511ff6 新闻定时任务测试 2024-02-08 20:04:51 +08:00
dengli
0112687ce2 新闻定时任务测试 2024-02-08 19:59:23 +08:00
dengli
4874e3bee4 新闻定时任务测试 2024-02-08 19:39:17 +08:00
dengli
bcff09cbec Merge remote-tracking branch 'origin/develop' into develop 2024-02-08 19:34:41 +08:00
dengli
592431d70a 新闻定时任务测试 2024-02-08 19:34:18 +08:00
rplees
930e1e79cf Merge branch 'develop' into 'main'
新股修改的时间获取

See merge request india/india_market_java!9
2024-02-06 07:42:08 +00:00
Achilles
8266094509 新股修改的时间获取 2024-02-04 13:41:11 +08:00
rplees
6c429ba58f Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!8
2024-02-02 07:12:48 +00:00
Achilles
5fa22c8410 新股修改的时间获取 2024-02-02 15:06:00 +08:00
Achilles
529aa76cb3 新股修改的时间获取 2024-02-02 14:54:02 +08:00
Achilles
bbcbdcc856 新股修改的时间获取 2024-02-02 14:50:04 +08:00
Achilles
7b87dd8186 新股修改的时间获取 2024-02-02 14:46:14 +08:00
rplees
277ee7dfe4 Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!7
2024-01-24 06:27:47 +00:00
Achilles
960946692d 优化提交,计算获取总发行股票数量 2024-01-23 10:26:35 +08:00
Achilles
3e26a9db28 优化提交,计算获取总发行股票数量 2024-01-22 21:27:45 +08:00
Achilles
56232a42a7 优化代码 2024-01-16 14:17:26 +08:00
Achilles
bdded7b3fc 优化代码 2024-01-15 10:13:00 +08:00
rplees
933dadca3c Merge branch 'develop' into 'main'
Develop

See merge request india/india_market_java!6
2024-01-14 15:09:09 +00:00
li deng
a9704b62ae Merge branch 'dengli2024/1/11' into 'main'
新闻定时任务

See merge request india/india_market_java!5
2024-01-11 10:16:49 +00:00
Achilles
82ede6e680 优化代码 2024-01-11 14:25:11 +08:00
Achilles
0d23d57eae 优化代码 2024-01-11 14:12:10 +08:00
Achilles
7c807ba521 优化代码 2024-01-11 10:52:56 +08:00
Achilles
a03ee86223 优化代码 2024-01-11 09:45:11 +08:00
Achilles
825c26dba6 Merge remote-tracking branch 'origin/develop' into develop 2024-01-11 09:38:46 +08:00
Achilles
87c1504421 优化代码 2024-01-11 09:38:42 +08:00
xiaoliuhu
d221ed3d04 fix:修改指数信息 2024-01-10 16:30:37 +08:00
xiaoliuhu
8b368cfcc8 fix:修改指数信息 2024-01-10 12:04:48 +08:00
xiaoliuhu
91a557cc51 fix:修改指数信息 2024-01-10 11:55:45 +08:00
xiaoliuhu
6fa3428ca1 fix:修改指数信息 2024-01-10 11:25:13 +08:00
xiaoliuhu
37425eff84 Merge remote-tracking branch 'origin/develop' into develop 2024-01-10 11:20:53 +08:00
xiaoliuhu
27bb313f74 fix:修改指数信息 2024-01-10 11:20:26 +08:00
dengli
baca671bbf 新闻测试 2024-01-10 11:19:36 +08:00
dengli
dd34ab116f Merge remote-tracking branch 'origin/develop' into develop 2024-01-10 11:14:44 +08:00
dengli
49e7593da5 新闻测试 2024-01-10 11:14:37 +08:00
xiaoliuhu
f2c369c73d Merge remote-tracking branch 'origin/develop' into develop 2024-01-10 11:02:12 +08:00
xiaoliuhu
a968f61a05 fix:修改指数信息 2024-01-10 11:01:44 +08:00
dengli
3de67ae9ec 新闻测试 2024-01-10 10:58:18 +08:00
dengli
bc5cf91a88 新闻测试 2024-01-10 10:56:10 +08:00
dengli
bc3efbc2de 新闻测试 2024-01-10 10:41:18 +08:00
dengli
a49ad82f3f 新闻测试 2024-01-10 10:41:06 +08:00
dengli
875d4faf0e 新闻测试 2024-01-10 10:36:08 +08:00
dengli
a9fe1c39a7 新闻测试 2024-01-10 10:34:21 +08:00
dengli
c646988219 新闻测试 2024-01-10 10:20:39 +08:00
dengli
c7284e8081 新闻测试 2024-01-10 10:15:48 +08:00
dengli
e87c451b3f 新闻测试 2024-01-10 09:59:18 +08:00
dengli
2ba716d87c Merge remote-tracking branch 'origin/develop' into develop 2024-01-10 09:46:00 +08:00
dengli
a986870d4b 新闻测试 2024-01-10 09:45:45 +08:00
Achilles
43f08fc073 没两天的凌晨两点 2024-01-09 20:40:54 +08:00
32 changed files with 1682 additions and 261 deletions

View File

@@ -1,7 +1,8 @@
stages: stages:
# 构建 # 构建
- build - build
- webhook - dockerize
- deploy
build: build:
image: maven:3.6.3-openjdk-8 image: maven:3.6.3-openjdk-8
@@ -37,16 +38,42 @@ build:
- mvn clean install -Dmaven.test.skip=true - mvn clean install -Dmaven.test.skip=true
- ls - ls
- echo ">>>>>>Finish Building<<<<<<" - echo ">>>>>>Finish Building<<<<<<"
webhook: dockerize:
stage: webhook stage: dockerize
tags:
- hk2
dependencies:
- build
only:
- main
- develop
script:
- echo ">>>>>>Start Building Image<<<<<<"
- ls
- ls target
- echo $DOCKER_PASSWORD
- echo $CI_PIPELINE_ID
- docker build -t juyoutech/india_stock_market:latest .
- docker tag juyoutech/india_stock_market:latest juyoutech/india_stock_market:$CI_PIPELINE_ID
- docker tag juyoutech/india_stock_market:latest juyoutech/india_stock_market:$CI_COMMIT_BRANCH
- docker login -u juyoutech -p dckr_pat_8rg23IBA2kZMOCX4IJKApb8m5l8
- docker push juyoutech/india_stock_market:latest
- docker push juyoutech/india_stock_market:$CI_PIPELINE_ID
- docker push juyoutech/india_stock_market:$CI_COMMIT_BRANCH
deploy-dev:
stage: deploy
only: only:
- develop - develop
script: script:
- echo ">>>>>>Start Deploy<<<<<<" - echo "Deploying application..."
- ls - ls
- apt-get update - apt-get update
- apt-get install -y curl - apt-get install -y curl
- curl --max-time 30 http://124.156.133.209:11113/api/webhook/justpull?project=india_market_java\&setenv_file=alpha.sh\&publish_env=alpha\&shell=india/deploy-test.sh - |
- echo ">>>>>>Start Deploy Finish<<<<<<" curl -X POST \
-H "Content-Type: application/json" \
-d '{"namespace":"yddev", "deployment_name":"india-stock-market"}' \
https://updater-yddev.moneytj.com/restart-deployment
- echo "Application successfully deployed."

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM openjdk:8
RUN echo "deb http://archive.debian.org/debian/ stretch main contrib non-free" > /etc/apt/sources.list \
&& echo "deb-src http://archive.debian.org/debian/ stretch main contrib non-free" >> /etc/apt/sources.list \
&& echo 'Acquire::Check-Valid-Until "false";' > /etc/apt/apt.conf.d/10no-check-valid
RUN apt-get update
#RUN apt-get install -y iputils-ping dnsutils vim net-tools --allow-unauthenticated
WORKDIR /app
COPY target/india_market_java.jar /app/app.jar
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
CMD ["docker-entrypoint.sh"]

21
docker-entrypoint.sh Normal file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
export JAVA_OPTS="$JAVA_OPTS -XX:-OmitStackTraceInFastThrow \
-Dspring.redis.host=$REDIS_HOST \
-Dspring.redis.password=$REDIS_PASS \
-Dmarket.domain=$MARKET_HOST \
-Dspring.redis.port=$REDIS_PORT \
-Dspring.datasource.stock-market.url=jdbc:mysql://$MYSQL_HOST:$MYSQL_PORT/$MYSQL_DB?useUnicode=true&autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=true \
-Dspring.datasource.stock-market.username=$MYSQL_USER \
-Dspring.datasource.stock-market.password=$MYSQL_PASSWORD \
-Dspring.datasource.stock.url=jdbc:mysql://$MYSQL_HOST:$MYSQL_PORT/$MYSQL_DB?useUnicode=true&autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=true \
-Dspring.datasource.stock.username=$MYSQL_USER \
-Dspring.datasource.stock.password=$MYSQL_PASSWORD"
echo 'param:'$@
echo 'JAVA_OPTS:'$JAVA_OPTS
java $JAVA_OPTS -jar /app/app.jar $@
tail -f /dev/null

View File

@@ -264,7 +264,7 @@
<repositories> <repositories>
<repository> <repository>
<id>nexus</id> <id>nexus</id>
<url>https://nexus.duofu88.com/repository/maven-public/</url> <url>https://nexus.main99.com/repository/maven-public/</url>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
</releases> </releases>

View File

@@ -23,6 +23,10 @@ public class QBtodayStockPO extends EntityPathBase<BtodayStockPO> {
public final NumberPath<Integer> id = createNumber("id", Integer.class); public final NumberPath<Integer> id = createNumber("id", Integer.class);
public final NumberPath<Integer> isLock = createNumber("isLock", Integer.class);
public final NumberPath<Integer> isShow = createNumber("isShow", Integer.class);
public final DateTimePath<java.util.Date> lastUpdateTime = createDateTime("lastUpdateTime", java.util.Date.class); public final DateTimePath<java.util.Date> lastUpdateTime = createDateTime("lastUpdateTime", java.util.Date.class);
public final StringPath selfUrl = createString("selfUrl"); public final StringPath selfUrl = createString("selfUrl");

View File

@@ -1,22 +1,19 @@
package cn.stock.market.domain.basic.service; package cn.stock.market.domain.basic.service;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.net.ssl.X509TrustManager;
import javax.persistence.EntityExistsException; import javax.persistence.EntityExistsException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import cn.stock.market.dto.model.*; import cn.stock.market.dto.model.*;
import cn.stock.market.infrastructure.api.EttechchartsApis;
import cn.stock.market.infrastructure.api.GrowwInApis;
import cn.stock.market.infrastructure.api.TodayApis;
import cn.stock.market.infrastructure.api.investing.IndiaIndexVo; import cn.stock.market.infrastructure.api.investing.IndiaIndexVo;
import cn.stock.market.infrastructure.api.investing.IndiaStockVO; import cn.stock.market.infrastructure.api.investing.IndiaStockVO;
import cn.stock.market.infrastructure.api.investing.InvestingApis; import cn.stock.market.infrastructure.api.investing.InvestingApis;
@@ -28,9 +25,6 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Request.Builder; import okhttp3.Request.Builder;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import cn.stock.market.infrastructure.db.po.QStockPO; import cn.stock.market.infrastructure.db.po.QStockPO;
@@ -62,11 +56,6 @@ import cn.stock.market.infrastructure.api.sina.vo.MarketVO;
import cn.stock.market.infrastructure.api.sina.vo.MarketVOResult; import cn.stock.market.infrastructure.api.sina.vo.MarketVOResult;
import cn.stock.market.infrastructure.api.sina.vo.k.MinDataVO; import cn.stock.market.infrastructure.api.sina.vo.k.MinDataVO;
import cn.stock.market.infrastructure.api.sina.vo.k.echarts.EchartsDataVO; import cn.stock.market.infrastructure.api.sina.vo.k.echarts.EchartsDataVO;
import cn.stock.market.utils.GetPyByChinese;
import cn.stock.market.utils.HttpClientRequest;
import cn.stock.market.utils.PropertiesUtil;
import cn.stock.market.utils.ServerResponse;
import cn.stock.market.utils.Utils;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@@ -265,7 +254,13 @@ public class StockService {
.header("Referer", "https://www.business-standard.com/") .header("Referer", "https://www.business-standard.com/")
.header("Accept-Language", "en-US,en;q=0.9") .header("Accept-Language", "en-US,en;q=0.9")
.get(); .get();
result = doc.html().substring(doc.html().indexOf("<div class=\"short-video-img\">"),doc.html().lastIndexOf("<div class=\"short-video-img\">")+500); // result = doc.html().substring(doc.html().indexOf("<div class=\"listingstyle_shortvideoimg__0TWuX shortvideoimg\">"),doc.html().lastIndexOf("<div class=\"listingstyle_shortvideoimg__0TWuX shortvideoimg\">")+500);
Elements divElements = doc.select("div.listingstyle_cardlistlist__dfq57");
StringBuilder sb = new StringBuilder();
for (Element divElement : divElements) {
sb.append(divElement.outerHtml()).append("\n");
}
result = sb.toString();
} catch (Exception e) { } catch (Exception e) {
return e.toString(); return e.toString();
} }
@@ -945,8 +940,10 @@ public class StockService {
market.setName("BSESENSEX指数"); market.setName("BSESENSEX指数");
vo1.setIndexVo(market); vo1.setIndexVo(market);
String type = "min"; String period = "P1D";
List<JSONObject> list = InvestingApis.of().kline(StockCode.of(stockCode), type); String interval = "PT5M";
String type = "day";
List<JSONObject> list = InvestingApis.of().kIndex(stockCode,period,interval, type);
if(list == null || list.size() == 0){ if(list == null || list.size() == 0){
type = "day"; type = "day";
list = InvestingApis.of().kline(StockCode.of(stockCode), type); list = InvestingApis.of().kline(StockCode.of(stockCode), type);
@@ -958,13 +955,15 @@ public class StockService {
} }
try { try {
IndiaIndexVo vo2 = new IndiaIndexVo(); IndiaIndexVo vo2 = new IndiaIndexVo();
String stockCode = "8985"; //"17940"; String stockCode = "17940"; //"17940";8985
IndiaStockVO market = InvestingApis.of().market(StockCode.of(stockCode)); IndiaStockVO market = InvestingApis.of().market(StockCode.of(stockCode));
market.setName("NIFTY50指数"); market.setName("NIFTY50指数");
vo2.setIndexVo(market); vo2.setIndexVo(market);
String type = "min"; String period = "P1D";
List<JSONObject> list = InvestingApis.of().kline(StockCode.of(stockCode), type); String interval = "PT1M";
String type = "day";
List<JSONObject> list = InvestingApis.of().kIndex(stockCode,period,interval, type);
if(list == null || list.size() == 0){ if(list == null || list.size() == 0){
type = "day"; type = "day";
list = InvestingApis.of().kline(StockCode.of(stockCode), type); list = InvestingApis.of().kline(StockCode.of(stockCode), type);
@@ -976,4 +975,149 @@ public class StockService {
} }
return ServerResponse.createBySuccess(indexVoList); return ServerResponse.createBySuccess(indexVoList);
} }
public ServerResponse getIndexByBtoday(){
List<IndiaIndexVo> indexVoList = new ArrayList<>();
try {
String exchange = "bse";
IndiaIndexVo vo1 = new IndiaIndexVo();
String coCode = "20558";
JSONObject object = TodayApis.getStockDetail("in%3BSEN", coCode);
IndiaStockVO market = objToVo(object);
market.setName("BSESENSEX指数");
vo1.setIndexVo(market);
//获取k线图 1D 当天的数据
String format = "S";
String durationType = "D";
String duration = "1";
List kine = TodayApis.getStockKline(exchange,coCode,format,durationType,duration);
vo1.setKLine(kine);
indexVoList.add(vo1);
}catch (Exception e){
log.error("BToday获取BSESENSEX指数数据异常异常信息。。。。", e);
try {
GrowwInApis.requestSenSexData(indexVoList);
} catch (Exception e1) {
log.error("GrowwIn获取BSESENSEX指数数据异常异常信息。。。。", e1);
try{
EttechchartsApis.requestSensexData(indexVoList);
} catch (Exception e2) {
log.error("Ettechcharts获取BSESENSEX指数数据异常异常信息。。。。", e2);
}
}
}
try {
String exchange = "nse";
IndiaIndexVo vo1 = new IndiaIndexVo();
String coCode = "20559";
JSONObject object = TodayApis.getStockDetail("in%3BNSX", coCode);
IndiaStockVO market = objToVo(object);
market.setName("NIFTY50指数");
vo1.setIndexVo(market);
//获取k线图 1D 当天的数据
String format = "S";
String durationType = "D";
String duration = "1";
List kine = TodayApis.getStockKline(exchange,coCode,format,durationType,duration);
vo1.setKLine(kine);
indexVoList.add(vo1);
}catch (Exception e){
log.error("BToday获取NIFTY50指数数据异常异常信息。。。。", e);
try {
GrowwInApis.requestNifty50Data(indexVoList);
} catch (Exception e1) {
log.error("GrowwIn获取NIFTY50指数数据异常异常信息。。。。", e1);
try{
EttechchartsApis.requestNifty50Data(indexVoList);
} catch (Exception e2) {
log.error("Ettechcharts获取NIFTY50指数数据异常异常信息。。。。", e2);
}
}
}
return ServerResponse.createBySuccess(indexVoList);
}
private IndiaStockVO objToVo(JSONObject object){
IndiaStockVO market = new IndiaStockVO();
if(object.containsKey("priceprevclose")){
market.setClose(object.getString("priceprevclose"));
}
if(object.containsKey("pricecurrent")){
market.setNowPrice(object.getString("pricecurrent"));
}
if(object.containsKey("pricepercentchange")){
market.setRate(object.getString("pricepercentchange"));
}
if(object.containsKey("HIGH")){
market.setHigh(object.getString("HIGH"));
}
if(object.containsKey("LOW")){
market.setLow(object.getString("LOW"));
}
if(object.containsKey("OPEN")){
market.setOpen(object.getString("OPEN"));
}
return market;
// stockListVO.setName(jsonObject.getString("companyname"));
// stockListVO.setCode(jsonObject.getString("co_code"));
// stockListVO.setSpell(jsonObject.getString("symbol"));
// stockListVO.setGid(jsonObject.getString("co_code"));
// stockListVO.setNowPrice(jsonObject.getString("price"));
// stockListVO.setHcrate(jsonObject.getBigDecimal("perchg"));
// stockListVO.setToday_max(jsonObject.getString("high_price"));
// stockListVO.setToday_min(jsonObject.getString("low_price"));
// stockListVO.setBusiness_balance(jsonObject.getString("val_traded"));
// stockListVO.setBusiness_amount(jsonObject.getString("vol_traded"));
// stockListVO.setPreclose_px(jsonObject.getString("prev_close"));
// stockListVO.setOpen_px(jsonObject.getString("open_price"));
}
public ServerResponse getEttechcharts(){
List<IndiaIndexVo> indexVoList = new ArrayList<>();
try {
//获取详情
String indexid = "2365";
String exchange = "47";
String keyName = "sensex";
IndiaIndexVo vo1 = new IndiaIndexVo();
JSONObject object = EttechchartsApis.getStockDetail(indexid, exchange,keyName);
IndiaStockVO market = EttechchartsApis.ettechchartsObjToVo(object);
market.setName("BSESENSEX指数");
vo1.setIndexVo(market);
//获取k线图 1min 当天的数据 分钟
String scripcode = "SENSEX";
List kine = EttechchartsApis.getStockKline(scripcode,exchange);
vo1.setKLine(kine);
indexVoList.add(vo1);
}catch (Exception e){
log.info("获取BSESENSEX指数数据异常异常信息{}。。。。",e.getMessage());
}
try {
//获取详情
String indexid = "2369";
String exchangeid = "50";
String keyName = "nifty";
IndiaIndexVo vo1 = new IndiaIndexVo();
JSONObject object = EttechchartsApis.getStockDetail(indexid, exchangeid,keyName);
IndiaStockVO market = EttechchartsApis.ettechchartsObjToVo(object);
market.setName("NIFTY50指数");
vo1.setIndexVo(market);
//获取k线图 1min 当天的数据 分钟
String scripcode = "NSE+Index";
List kine = EttechchartsApis.getStockKline(scripcode,exchangeid);
vo1.setKLine(kine);
indexVoList.add(vo1);
}catch (Exception e){
log.info("获取NIFTY50指数数据异常异常信息{}。。。。",e.getMessage());
}
return ServerResponse.createBySuccess(indexVoList);
}
} }

View File

@@ -0,0 +1,18 @@
package cn.stock.market.dto;
import lombok.Data;
@Data
public class TodayStockDTO {
private String stockType;
private String stockName;
private String stockUrl;
private String highPrice;
private String lowPrice;
private String lastPrice;
private String prevClosePrice;
private String change;
private String changePercent;
private String dispId;
private String scId;
}

View File

@@ -35,6 +35,11 @@ public class StockListVO {
/*是否添加自选1、添加自选0、未添加自选*/ /*是否添加自选1、添加自选0、未添加自选*/
private String isOption; private String isOption;
private String pricechange;
private String symbol;
public void setCode(String code) { public void setCode(String code) {
this.code = code; this.code = code;
} }
@@ -255,4 +260,20 @@ public class StockListVO {
public void setIsOption(String isOption) { public void setIsOption(String isOption) {
this.isOption = isOption; this.isOption = isOption;
} }
public String getPricechange() {
return pricechange;
}
public void setPricechange(String pricechange) {
this.pricechange = pricechange;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
} }

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,233 @@
package cn.stock.market.infrastructure.api;
import cn.stock.market.dto.TodayStockDTO;
import cn.stock.market.infrastructure.api.investing.IndiaIndexVo;
import cn.stock.market.infrastructure.api.investing.IndiaStockVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 数据来源网站:<a href="https://groww.in/indices/nifty">...</a>, <a href="https://groww.in/indices/sp-bse-sensex">...</a>
*
* @auther jnerh
*/
public class GrowwInApis {
public static final String INDEX_DETAIL_URL = "https://groww.in/v1/api/stocks_data/v1/accord_points/exchange/%s/segment/CASH/latest_indices_ohlc/%s";
public static final String INDEX_KLINE_URL = "https://groww.in/v1/api/charting_service/v2/chart/delayed/exchange/%s/segment/CASH/%s/daily?intervalInMinutes=%s&minimal=true";
public static void requestSenSexData(List<IndiaIndexVo> indexVoList) {
IndiaIndexVo vo1 = new IndiaIndexVo();
JSONObject object = GrowwInApis.getSenSexDetail();
IndiaStockVO market = GrowwInApis.objToVo(object);
market.setName("BSESENSEX指数");
vo1.setIndexVo(market);
List kine = GrowwInApis.getSenSexKline();
vo1.setKLine(kine);
indexVoList.add(vo1);
}
public static void requestNifty50Data(List<IndiaIndexVo> indexVoList) {
IndiaIndexVo vo1 = new IndiaIndexVo();
JSONObject object = GrowwInApis.getNifty50Detail();
IndiaStockVO market = GrowwInApis.objToVo(object);
market.setName("NIFTY50指数");
vo1.setIndexVo(market);
List kine = GrowwInApis.getNifty50Kline();
vo1.setKLine(kine);
indexVoList.add(vo1);
}
/**
* 获取Nifty50指数详情
*/
public static JSONObject getIndexDetail(String exchange, String type) {
String url = String.format(INDEX_DETAIL_URL, exchange, type);
String str = get(url);
return JSON.parseObject(str);
}
/**
* 获取k线图
*/
public static List getIndexKline(String exchange, String type, String intervalInMinutes) {
String url = String.format(INDEX_KLINE_URL, exchange, type, intervalInMinutes);
String str = get(url);
JSONObject object = JSON.parseObject(str);
return getList(object.getString("candles"));
}
/**
* 获取Nifty50指数详情
*/
public static JSONObject getSenSexDetail() {
return getIndexDetail("BSE", "1");
}
/**
* 获取k线图
*/
public static List getSenSexKline() {
return getIndexKline("BSE", "1", "1");
}
/**
* 获取Nifty50指数详情
*/
public static JSONObject getNifty50Detail() {
return getIndexDetail("NSE", "NIFTY");
}
/**
* 获取k线图
*/
public static List getNifty50Kline() {
return getIndexKline("NSE", "NIFTY", "5");
}
static String get(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Referer", "https://groww.in/indices/nifty");
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0");
httpGet.setHeader("X-App-Id", "growwWeb");
httpGet.setHeader("X-Device-Id", "fd4815a2-49e4-570a-931a-0316d4d8a52d");
httpGet.setHeader("X-Device-Type", "desktop");
httpGet.setHeader("X-Platform", "web");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static IndiaStockVO objToVo(JSONObject object) {
IndiaStockVO market = new IndiaStockVO();
if (object.containsKey("close")) {
market.setClose(object.getString("close"));
}
if (object.containsKey("value")) {
market.setNowPrice(object.getString("value"));
}
if (object.containsKey("dayChangePerc")) {
market.setRate(object.getString("dayChangePerc"));
}
if (object.containsKey("high")) {
market.setHigh(object.getString("high"));
}
if (object.containsKey("low")) {
market.setLow(object.getString("low"));
}
if (object.containsKey("open")) {
market.setOpen(object.getString("open"));
}
return market;
}
private static List getList(String json) {
List<JSONObject> dataObject = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(json);
for (Object obj : jsonArray) {
JSONObject entity = new JSONObject();
JSONArray jsonArray1 = JSON.parseArray(obj.toString());
entity.put("upd_date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(JSON.parseArray(obj.toString()).getLong(0) * 1000)).replace(" ", "T"));
entity.put("price", jsonArray1.getBigDecimal(1));
dataObject.add(entity);
}
return dataObject;
}
private static TodayStockDTO todayStockDTO(JSONObject jsonObject) {
TodayStockDTO dto = new TodayStockDTO();
if (jsonObject.containsKey("exchange")) {
dto.setStockType(jsonObject.getString("exchange"));
} else {
dto.setStockType("");
}
if (jsonObject.containsKey("lname")) {
dto.setStockName(jsonObject.getString("lname"));
} else {
dto.setStockName("");
}
if (jsonObject.containsKey("high_price")) {
dto.setHighPrice(jsonObject.getString("highPrice"));
} else {
dto.setHighPrice("0.00");
}
if (jsonObject.containsKey("low_price")) {
dto.setLowPrice(jsonObject.getString("low_price"));
} else {
dto.setLowPrice("0.00");
}
if (jsonObject.containsKey("price")) {
dto.setLastPrice(jsonObject.getString("price"));
} else {
dto.setLastPrice("0.00");
}
if (jsonObject.containsKey("close_price")) {
dto.setPrevClosePrice(jsonObject.getString("close_price"));
} else {
dto.setPrevClosePrice("0.00");
}
if (jsonObject.containsKey("netchg")) {
dto.setChange(jsonObject.getString("netchg"));
} else {
dto.setChange("0.00");
}
if (jsonObject.containsKey("perchg")) {
dto.setChangePercent(jsonObject.getString("perchg"));
} else {
dto.setChangePercent("0.00");
}
return dto;
}
public static void main(String[] args) {
System.out.println(getNifty50Detail());
System.out.println(getNifty50Kline());
}
}

View File

@@ -1,5 +1,6 @@
package cn.stock.market.infrastructure.api; package cn.stock.market.infrastructure.api;
import cn.stock.market.dto.TodayStockDTO;
import cn.stock.market.utils.HttpClientRequest; import cn.stock.market.utils.HttpClientRequest;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
@@ -20,7 +21,7 @@ public class TodayApis {
} }
//获取Top Gainers //获取Top Gainers
public static List<JSONObject> getTopGainers(String exchange){ public static List getTopGainers(String exchange){
String url = "https://marketapi.intoday.in/widget/topgainer/view?exchange=" + exchange; String url = "https://marketapi.intoday.in/widget/topgainer/view?exchange=" + exchange;
//返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true} //返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true}
String str = get(url); String str = get(url);
@@ -32,17 +33,19 @@ public class TodayApis {
if(!bool){ if(!bool){
return null; return null;
} }
return getList(object.getString("data"),1);
//进行数据转换 //进行数据转换
List<JSONObject> dataObject = new ArrayList<>(); // List<TodayStockDTO> dataObject = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(object.getString("data")); // JSONArray jsonArray = JSON.parseArray(object.getString("data"));
for (Object obj : jsonArray){ // for (Object obj : jsonArray){
JSONObject entity = JSON.parseObject(obj.toString()); //// JSONObject entity = JSON.parseObject(obj.toString());
dataObject.add(entity); // TodayStockDTO entity = todayStockDTO(JSON.parseObject(obj.toString()));
} // dataObject.add(entity);
return dataObject; // }
// return dataObject;
} }
//获取Top Losers //获取Top Losers
public static List<JSONObject> getTopLosers(String exchange){ public static List getTopLosers(String exchange){
String url = "https://marketapi.intoday.in/widget/toploser/view?exchange=" + exchange; String url = "https://marketapi.intoday.in/widget/toploser/view?exchange=" + exchange;
//返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true} //返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true}
String str = get(url); String str = get(url);
@@ -54,17 +57,20 @@ public class TodayApis {
if(!bool){ if(!bool){
return null; return null;
} }
return getList(object.getString("data"),1);
//进行数据转换 //进行数据转换
List<JSONObject> dataObject = new ArrayList<>(); //// List<TodayStockDTO> dataObject = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(object.getString("data")); // List<JSONObject> dataObject = new ArrayList<>();
for (Object obj : jsonArray){ // JSONArray jsonArray = JSON.parseArray(object.getString("data"));
JSONObject entity = JSON.parseObject(obj.toString()); // for (Object obj : jsonArray){
dataObject.add(entity); // JSONObject entity = JSON.parseObject(obj.toString());
} //// TodayStockDTO entity = todayStockDTO(JSON.parseObject(obj.toString()));
return dataObject; // dataObject.add(entity);
// }
// return dataObject;
} }
//获取Most Active Volume //获取Most Active Volume
public static List<JSONObject> getMostActiveVolume(String exchange){ public static List getMostActiveVolume(String exchange){
String url = "https://marketapi.intoday.in/widget/mostactivetopper/view?exchange=" + exchange; String url = "https://marketapi.intoday.in/widget/mostactivetopper/view?exchange=" + exchange;
//返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true} //返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true}
String str = get(url); String str = get(url);
@@ -76,17 +82,19 @@ public class TodayApis {
if(!bool){ if(!bool){
return null; return null;
} }
return getList(object.getString("data"),1);
//进行数据转换 //进行数据转换
List<JSONObject> dataObject = new ArrayList<>(); // List<TodayStockDTO> dataObject = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(object.getString("data")); // JSONArray jsonArray = JSON.parseArray(object.getString("data"));
for (Object obj : jsonArray){ // for (Object obj : jsonArray){
JSONObject entity = JSON.parseObject(obj.toString()); //// JSONObject entity = JSON.parseObject(obj.toString());
dataObject.add(entity); // TodayStockDTO entity = todayStockDTO(JSON.parseObject(obj.toString()));
} // dataObject.add(entity);
return dataObject; // }
// return dataObject;
} }
//获取Most Active Value //获取Most Active Value
public static List<JSONObject> getMostActiveValue(String exchange){ public static List getMostActiveValue(String exchange){
String url = "https://marketapi.intoday.in/widget/mostactivetopperbyvalue/view?exchange=" + exchange; String url = "https://marketapi.intoday.in/widget/mostactivetopperbyvalue/view?exchange=" + exchange;
//返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true} //返回字符串对象格式:{"status_code":1,"success":true,"data":[{}],"message":"Successful","fromredis":true}
String str = get(url); String str = get(url);
@@ -98,14 +106,116 @@ public class TodayApis {
if(!bool){ if(!bool){
return null; return null;
} }
//进行数据转换 return getList(object.getString("data"),1);
List<JSONObject> dataObject = new ArrayList<>(); // //进行数据转换
JSONArray jsonArray = JSON.parseArray(object.getString("data")); // List<TodayStockDTO> dataObject = new ArrayList<>();
for (Object obj : jsonArray){ // JSONArray jsonArray = JSON.parseArray(object.getString("data"));
JSONObject entity = JSON.parseObject(obj.toString()); // for (Object obj : jsonArray){
dataObject.add(entity); //// JSONObject entity = JSON.parseObject(obj.toString());
// TodayStockDTO entity = todayStockDTO(JSON.parseObject(obj.toString()));
// dataObject.add(entity);
// }
// return dataObject;
}
private static List getList(String json, int type){
if(type == 1){
List<JSONObject> dataObject = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(json);
for (Object obj : jsonArray){
JSONObject entity = JSON.parseObject(obj.toString());
dataObject.add(entity);
}
return dataObject;
}else{
//进行数据转换
List<TodayStockDTO> dataObject = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(json);
for (Object obj : jsonArray){
TodayStockDTO entity = todayStockDTO(JSON.parseObject(obj.toString()));
dataObject.add(entity);
}
return dataObject;
} }
return dataObject;
}
private static TodayStockDTO todayStockDTO(JSONObject jsonObject){
TodayStockDTO dto = new TodayStockDTO();
if(jsonObject.containsKey("exchange")){
dto.setStockType(jsonObject.getString("exchange"));
}else {
dto.setStockType("");
}
if(jsonObject.containsKey("lname")){
dto.setStockName(jsonObject.getString("lname"));
}else{
dto.setStockName("");
}
if(jsonObject.containsKey("high_price")){
dto.setHighPrice(jsonObject.getString("highPrice"));
}else{
dto.setHighPrice("0.00");
}
if(jsonObject.containsKey("low_price")){
dto.setLowPrice(jsonObject.getString("low_price"));
}else {
dto.setLowPrice("0.00");
}
if(jsonObject.containsKey("price")){
dto.setLastPrice(jsonObject.getString("price"));
}else{
dto.setLastPrice("0.00");
}
if(jsonObject.containsKey("close_price")){
dto.setPrevClosePrice(jsonObject.getString("close_price"));
}else{
dto.setPrevClosePrice("0.00");
}
if(jsonObject.containsKey("netchg")){
dto.setChange(jsonObject.getString("netchg"));
}else{
dto.setChange("0.00");
}
if(jsonObject.containsKey("perchg")){
dto.setChangePercent(jsonObject.getString("perchg"));
}else{
dto.setChangePercent("0.00");
}
return dto;
}
//获取详情
public static JSONObject getStockDetail(String exchange,String coCode){
String url = String.format("https://priceapi.moneycontrol.com/pricefeed/notapplicable/inidicesindia/%s",exchange);
String str = get(url);
JSONObject object = JSON.parseObject(str);
boolean bool = false;
if(object.containsKey("code")){
bool = object.getInteger("code") == 200;
}
if(!bool){
return new JSONObject();
}
JSONObject entity = JSON.parseObject(object.getString("data"));
return entity;
}
//获取k线图
public static List getStockKline(String exchange, String coCode, String format, String durationType, String duration){
String url = String.format("https://marketapi.intoday.in/widget/pricechart_company/pullview?exchange=%s&co_code=%s&format=%s&durationtype=%s&duration=%s",
exchange, coCode, format, durationType, duration);
String str = get(url);
JSONObject object = JSON.parseObject(str);
boolean bool = false;
if(object.containsKey("success")){
bool = object.getBoolean("success");
}
if(!bool){
return new ArrayList();
}
return getList(object.getString("data"),1);
} }
public static void main(String[] args) { public static void main(String[] args) {

View File

@@ -153,7 +153,6 @@ public class InvestingApis {
"Time": "1698055197", "Time": "1698055197",
"Url": "/equities/aditya-birla", "Url": "/equities/aditya-birla",
"Volume": 3693615 "Volume": 3693615
* @param httpClient
* @param currPage * @param currPage
* @param pageSize * @param pageSize
* @return * @return
@@ -252,6 +251,34 @@ public class InvestingApis {
.collect(Collectors.toList()) .collect(Collectors.toList())
; ;
} }
public List<JSONObject> kIndex(String code,String period, String interval,String type) throws IOException {
if(code == null) {
throw new RuntimeException("找不到股票信息");
}
Date nowDate = new Date();
JSONObject json = InvestingInvokerApis.of().__IndiaIndex(code, period,interval);
return json
.getJSONArray("data")
.stream()
.map(val -> {
JSONArray _ar = (JSONArray) val;
JSONObject item = new JSONObject();
item.put("date", _ar.get(0));
item.put("open", _ar.get(1));
item.put("high", _ar.get(2));
item.put("low", _ar.get(3));
item.put("close", _ar.get(4));
item.put("volume", _ar.get(5));
return item;
}).filter(val -> {
if("day".equalsIgnoreCase(type)) {
return DateUtil.isSameDay(nowDate, new Date(val.getLong("date")));
}
return true;
})
.collect(Collectors.toList())
;
}
public static InvestingApis of() { public static InvestingApis of() {
return new InvestingApis(); return new InvestingApis();

View File

@@ -202,6 +202,15 @@ public class InvestingInvokerApis {
return JSON.parseObject(body); return JSON.parseObject(body);
} }
public JSONObject __IndiaIndex(String code,String period, String interval)throws IOException {
String tmpl = "https://api.investing.com/api/financialdata/{}/historical/chart/?period={}&interval={}&pointscount=160";
String url = StrFormatter.format(tmpl, code, period, interval);
Builder builder = builderGet(url);
String body = httpClient().newCall(builder.build()).execute().body().string();
return JSON.parseObject(body);
}
public static InvestingInvokerApis of() { public static InvestingInvokerApis of() {
return new InvestingInvokerApis(); return new InvestingInvokerApis();
} }

View File

@@ -71,4 +71,10 @@ public class BtodayStockPO {
/** /**
* 上次更新时间 */ * 上次更新时间 */
Date lastUpdateTime; Date lastUpdateTime;
/** 是否锁定 0否 1是 */
Integer isLock;
/** 是否展示 0是 1否 */
Integer isShow;
} }

View File

@@ -56,6 +56,10 @@ public class MoneyStockPO {
* 展示表示 */ * 展示表示 */
String selfDispId; String selfDispId;
/**
* NSE India的id */
String nseIndiaId;
/** /**
* 自有self_url */ * 自有self_url */
String selfUrl; String selfUrl;

View File

@@ -7,6 +7,7 @@ import cn.stock.market.domain.basic.repository.StockRepository;
import cn.stock.market.domain.basic.service.StockService; import cn.stock.market.domain.basic.service.StockService;
import cn.stock.market.infrastructure.api.investing.InvestingInvokerApis; import cn.stock.market.infrastructure.api.investing.InvestingInvokerApis;
import cn.stock.market.infrastructure.db.po.QSiteNewsPO; import cn.stock.market.infrastructure.db.po.QSiteNewsPO;
import cn.stock.market.utils.DateTimeUtil;
import cn.stock.market.utils.Utils; import cn.stock.market.utils.Utils;
import com.ag.utils.CollectionUtils; import com.ag.utils.CollectionUtils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
@@ -25,6 +26,8 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j @Slf4j
@Component @Component
@@ -107,30 +110,63 @@ public class InvestingTask {
} }
/*新闻接口*/ /*新闻接口*/
@Scheduled(cron = "0 0 1 * * ?") @Scheduled(cron = "0 0 0/3 * * ?")
public void saveStockNews() { public void saveStockNews() {
String news = stockService.getNews(); log.info("英文股票新闻数据同步开始");
List<String> newsList = Arrays.asList(news.split("<a href=")); try {
newsList = newsList.subList(1, newsList.size()); String news = stockService.getNews();
newsList.forEach( n -> { log.info("获取英文股票新闻数据----"+news);
String contentUrl = n.substring(1, n.indexOf("class=\"img-smllnews\"") - 2); List<String> newsList = Arrays.asList(news.split("<a href="));
String id = contentUrl.substring(contentUrl.lastIndexOf("-") + 1, contentUrl.lastIndexOf("_")); newsList = newsList.subList(1, newsList.size());
String imgUrl = n.substring(n.indexOf("img src=") + 9, n.indexOf("?")); newsList.forEach( n -> {
String time = n.substring(n.indexOf("Last Updated") + 23, n.indexOf("IST") - 9); String contentUrl = n.substring(1, n.indexOf("class=\"img-smllnews\"") - 2);
String id = contentUrl.substring(contentUrl.lastIndexOf("-") + 1, contentUrl.lastIndexOf("_"));
// String imgUrl = n.substring(n.indexOf("img loading=\"lazy\" src=") + 24, n.indexOf("?"));
String imgUrl = extractImgSrc(n);
// String time = n.substring(n.indexOf("Last Updated") + 23, n.indexOf("IST") - 9);
// Extract the date and time using regex
Pattern pattern = Pattern.compile("Updated On :<!-- --> <!-- -->(.*?)<!-- -->");
Matcher matcher = pattern.matcher(n);
String time = "";
if (matcher.find()) {
time = DateTimeUtil.formatDateTimeFor24H(matcher.group(1).trim(),"dd MMM yyyy | hh:mm a");
}
SiteNews siteNews = new SiteNews(); SiteNews siteNews = new SiteNews();
siteNews.setAddTime(new Date()); siteNews.setAddTime(new Date());
siteNews.setSourceId(id); siteNews.setSourceId(id);
siteNews.setDescription(time); siteNews.setDescription(time);
siteNews.setImgurl(imgUrl); siteNews.setImgurl(imgUrl);
List<String> newsInfo = stockService.getNewsInfo(contentUrl); List<String> newsInfo = stockService.getNewsInfo(contentUrl);
siteNews.setContent(newsInfo.get(0)); siteNews.setContent(newsInfo.get(0));
siteNews.setTitle(newsInfo.get(1)); siteNews.setTitle(newsInfo.get(1));
List<SiteNews> list = newsRepository.findAll(QSiteNewsPO.siteNewsPO.sourceId.eq(id)); List<SiteNews> list = newsRepository.findAll(QSiteNewsPO.siteNewsPO.sourceId.eq(id));
if (list.size() == 0) { if (list.size() == 0) {
newsRepository.save(siteNews); newsRepository.save(siteNews);
} }
}); });
log.info("英文股票新闻数据同步完成");
} catch (Exception e) {
log.info("新闻数据同步异常,异常信息{}。。。。",e.getMessage());
}
} }
public static String extractImgSrc(String htmlData) {
String searchString = "<noscript>";
int startPos = htmlData.indexOf(searchString);
if (startPos != -1) {
String startTag = "src=";
startPos = htmlData.indexOf(startTag, startPos) + startTag.length() + 1;
int endPos = htmlData.indexOf("?", startPos);
if (endPos != -1) {
return htmlData.substring(startPos, endPos);
}
}
return null;
}
} }

View File

@@ -15,6 +15,7 @@ import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -49,6 +50,7 @@ public class MoneyScraper {
private MoneyStockRepository moneyStockRepository; private MoneyStockRepository moneyStockRepository;
@GetMapping("testScraperGetMoneyControlStock") @GetMapping("testScraperGetMoneyControlStock")
//@Scheduled(cron = "0 0 2 */1 * ?")
public void schedule(){ public void schedule(){
List<String> letters = new ArrayList<>(); List<String> letters = new ArrayList<>();
for (char c = 'A'; c <= 'Z'; c++) { for (char c = 'A'; c <= 'Z'; c++) {

View File

@@ -1,5 +1,6 @@
package cn.stock.market.infrastructure.job; package cn.stock.market.infrastructure.job;
import cn.hutool.core.collection.CollectionUtil;
import cn.stock.market.domain.basic.entity.BtodayStock; import cn.stock.market.domain.basic.entity.BtodayStock;
import cn.stock.market.domain.basic.entity.StockIpo; import cn.stock.market.domain.basic.entity.StockIpo;
import cn.stock.market.domain.basic.repository.BtodayStockRepository; import cn.stock.market.domain.basic.repository.BtodayStockRepository;
@@ -8,6 +9,7 @@ import cn.stock.market.dto.StockIpoDTO;
import cn.stock.market.infrastructure.db.po.QStockIpoPO; import cn.stock.market.infrastructure.db.po.QStockIpoPO;
import cn.stock.market.infrastructure.db.po.StockIpoPO; import cn.stock.market.infrastructure.db.po.StockIpoPO;
import cn.stock.market.infrastructure.db.repo.BtodayStockRepo; import cn.stock.market.infrastructure.db.repo.BtodayStockRepo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
@@ -30,6 +32,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@@ -100,9 +103,10 @@ public class Scraper {
@Scheduled(cron = "0 0 5 * * ?") @Scheduled(cron = "0 0 18 * * ?")
@RequestMapping("/testScraperGetMoneyControllerNewIPO") @RequestMapping("/testScraperGetMoneyControllerNewIPO")
public void schedule2() { public void getMoneyControllerNewIPOSchedule() {
log.info("定时任务执行获取新股ipo的方法开始执行");
// 目标 URL // 目标 URL
String url = "https://www.moneycontrol.com/ipo/open-upcoming-ipos"; String url = "https://www.moneycontrol.com/ipo/open-upcoming-ipos";
// 创建 HttpClient 实例 // 创建 HttpClient 实例
@@ -130,7 +134,7 @@ public class Scraper {
// 将 JSON 字符串解析为 Java JSONObject // 将 JSON 字符串解析为 Java JSONObject
JSONObject jsonObject = JSONObject.parseObject(jsonDataStr); JSONObject jsonObject = JSONObject.parseObject(jsonDataStr);
log.info(jsonObject.toJSONString()); log.info("获取到新股的json信息:"+jsonObject.toJSONString());
JSONObject pageProps = jsonObject.getJSONObject("props").getJSONObject("pageProps"); JSONObject pageProps = jsonObject.getJSONObject("props").getJSONObject("pageProps");
JSONObject ipoTableData = pageProps.getJSONObject("ipoTableData"); JSONObject ipoTableData = pageProps.getJSONObject("ipoTableData");
@@ -147,11 +151,18 @@ public class Scraper {
stockIpo.setStockPrice(entry.getBigDecimal("issue_price")); stockIpo.setStockPrice(entry.getBigDecimal("issue_price"));
stockIpo.setSubscriptionDate(convertStringToTimestamp(entry.getString("open_date"))); stockIpo.setSubscriptionDate(convertStringToTimestamp(entry.getString("open_date")));
stockIpo.setListingDate(convertStringToTimestamp(entry.getString("listing_date"))); stockIpo.setListingDate(convertStringToTimestamp(entry.getString("listing_date")));
stockIpo.setTotalNumber(entry.getInteger("lot_size")); Integer totalNumber = 0;
if(null!=entry.getInteger("issue_size")&&entry.getBigDecimal("issue_price")!=null&&!entry.getBigDecimal("issue_price").equals(BigDecimal.valueOf(0))){
Integer issue_size = entry.getInteger("issue_size");
BigDecimal issueSize = new BigDecimal(issue_size);
BigDecimal totalNumberBigDecimal = issueSize.divide(entry.getBigDecimal("issue_price"), 2, BigDecimal.ROUND_HALF_UP);
totalNumber = totalNumberBigDecimal.intValue();
}
stockIpo.setTotalNumber(totalNumber);
stockIpo.setApply(entry.getString("total_subs")); stockIpo.setApply(entry.getString("total_subs"));
stockIpo.setCreateDate(new Date()); stockIpo.setCreateDate(new Date());
stockIpo.setUpdateDate(new Date()); stockIpo.setUpdateDate(new Date());
stockIpo.setSourceType("2"); stockIpo.setSourceType("3");
listStockIpoList.add(stockIpo); listStockIpoList.add(stockIpo);
} }
@@ -163,7 +174,14 @@ public class Scraper {
stockIpo.setStockPrice(entry.getBigDecimal("issue_price")); stockIpo.setStockPrice(entry.getBigDecimal("issue_price"));
stockIpo.setSubscriptionDate(convertStringToTimestamp(entry.getString("open_date"))); stockIpo.setSubscriptionDate(convertStringToTimestamp(entry.getString("open_date")));
stockIpo.setListingDate(convertStringToTimestamp(entry.getString("listing_date"))); stockIpo.setListingDate(convertStringToTimestamp(entry.getString("listing_date")));
stockIpo.setTotalNumber(entry.getInteger("lot_size")); Integer totalNumber = 0;
if(null!=entry.getInteger("issue_size")&&entry.getBigDecimal("issue_price")!=null&&!entry.getBigDecimal("issue_price").equals(BigDecimal.valueOf(0))){
Integer issue_size = entry.getInteger("issue_size");
BigDecimal issueSize = new BigDecimal(issue_size);
BigDecimal totalNumberBigDecimal = issueSize.divide(entry.getBigDecimal("issue_price"), 2, BigDecimal.ROUND_HALF_UP);
totalNumber = totalNumberBigDecimal.intValue();
}
stockIpo.setTotalNumber(totalNumber);
stockIpo.setApply(entry.getString("total_subs")); stockIpo.setApply(entry.getString("total_subs"));
stockIpo.setCreateDate(new Date()); stockIpo.setCreateDate(new Date());
stockIpo.setUpdateDate(new Date()); stockIpo.setUpdateDate(new Date());
@@ -173,17 +191,26 @@ public class Scraper {
// stockIpoRepository.saveAll(listStockIpoList); // stockIpoRepository.saveAll(listStockIpoList);
List<String> nameList = Lists.transform(listStockIpoList, StockIpo::getStockName); List<String> scIdList = Lists.transform(listStockIpoList, StockIpo::getStockCode);
List<StockIpo> existStockIpoList = stockIpoRepository.findAll(QStockIpoPO.stockIpoPO.stockName.in(nameList)); if(CollectionUtil.isNotEmpty(scIdList)){
List<String> existingStockNames = existStockIpoList.stream() List<StockIpo> existStockIpoList = stockIpoRepository.findAll(QStockIpoPO.stockIpoPO.stockCode.in(scIdList));
.map(StockIpo::getStockName) List<String> existingStockScIds = existStockIpoList.stream()
.collect(Collectors.toList()); .map(StockIpo::getStockCode)
.collect(Collectors.toList());
listStockIpoList = listStockIpoList.stream()
.filter(stockIpos -> !existingStockScIds.contains(stockIpos.getStockCode())).filter(stockIpo -> StringUtils.isNotBlank(stockIpo.getStockName()))
.collect(Collectors.toList());
//保存全部的新股
if(CollectionUtil.isNotEmpty(listStockIpoList)){
stockIpoRepository.saveAll(listStockIpoList);
log.info("定时任务执行获取新股ipo的方法开始结束,保存了数据:{}", JSON.toJSONString(listStockIpoList));
}else {
log.info("定时任务执行获取新股ipo的方法开始结束,没有数据");
}
}
listStockIpoList = listStockIpoList.stream()
.filter(stockIpos -> !existingStockNames.contains(stockIpos.getStockName()))
.collect(Collectors.toList());
//保存全部的新股
stockIpoRepository.saveAll(listStockIpoList);
// 输出整个 JSON 数据 // 输出整个 JSON 数据
} else { } else {
@@ -195,6 +222,7 @@ public class Scraper {
} catch (IOException e) { } catch (IOException e) {
log.error("获取新股接口发生异常",e); log.error("获取新股接口发生异常",e);
} }
} }
@@ -257,6 +285,8 @@ public class Scraper {
btodayStock.setSelfUrl(url); btodayStock.setSelfUrl(url);
btodayStock.setUrl(detailUrl); btodayStock.setUrl(detailUrl);
btodayStock.setLastUpdateTime(new Date()); btodayStock.setLastUpdateTime(new Date());
btodayStock.setIsLock(0);
btodayStock.setIsShow(0);
btodayStockRepo.save(btodayStock); btodayStockRepo.save(btodayStock);
/* if (webInfo != null) { /* if (webInfo != null) {

View File

@@ -5,6 +5,8 @@ import java.sql.Timestamp;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Calendar; import java.util.Calendar;
import java.util.Locale;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatter;
@@ -186,6 +188,25 @@ public class DateTimeUtil {
} }
public static String formatDateTimeFor24H(String inputDateTime,String inputFormatStr){
String outputDateTime = "";
// 1. 解析日期时间
SimpleDateFormat inputFormat = new SimpleDateFormat(inputFormatStr, Locale.ENGLISH);
Date date = null;
try {
date = inputFormat.parse(inputDateTime);
} catch (Exception e) {
e.printStackTrace();
}
if (date != null) {
// 2. 转换为24小时制
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputDateTime = outputFormat.format(date);
}
return outputDateTime;
}
public static void main(String[] args) { public static void main(String[] args) {
parseToDateByMinute(10); parseToDateByMinute(10);
} }

View File

@@ -212,6 +212,59 @@ public class HttpClientRequest {
return result; return result;
} }
public static String doEttechchartsGet(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
// httpGet.setHeader(":authority","ettechcharts.indiatimes.com");
// httpGet.setHeader(":method","GET");
// httpGet.setHeader(":scheme","https");
httpGet.setHeader("accept","*/*");
httpGet.setHeader("accept-encoding","gzip, deflate, br");
httpGet.setHeader("accept-language","zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
httpGet.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
httpGet.setHeader("Referer", "https://economictimes.indiatimes.com/");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static void main(String[] args) { public static void main(String[] args) {
String url = "https://marketapi.intoday.in/widget/topgainer/view?exchange=nse"; String url = "https://marketapi.intoday.in/widget/topgainer/view?exchange=nse";
String str = doGet(url); String str = doGet(url);

View File

@@ -0,0 +1,170 @@
package cn.stock.market.utils;
import cn.stock.market.dto.StockHistoryRequest;
import cn.stock.market.dto.StockHistoryResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;
public class NseIndiaRequest {
private static final String NSE_INDIA_URL = "https://www.nseindia.com";
private static final OkHttpClient client;
static {
client = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
private final Map<String, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
}
private static Request createRequest(String url) {
Request request = new Request.Builder()
.url(url)
.header("accept", "application/json, text/plain, */*")
.header("accept-language", "en-US,en;q=0.9")
.header("cache-control", "no-cache")
.header("pragma", "no-cache")
.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36")
.build();
return request;
}
private static void initCookie() {
Request request = createRequest(NSE_INDIA_URL);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Failed to fetch initial cookies");
}
} catch (IOException e) {
throw new RuntimeException("Failed to initialize cookies", e);
}
}
public static JSONObject stockByJYSFromHttp(String stockType, String symbol, String nseIndiaId) {
initCookie();
String url = NSE_INDIA_URL + "/api/quote-equity?symbol=" + nseIndiaId;
Request request = createRequest(url).newBuilder()
.addHeader("referer", NSE_INDIA_URL)
.addHeader("origin", NSE_INDIA_URL)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Request failed with code: " + response.code());
}
JSONObject jsonData = JSONObject.parseObject(response.body().string());
JSONObject data =jsonData.getJSONObject("priceInfo");
JSONObject json = new JSONObject();
json.put("pricepercentchange",data.getString("pChange"));
json.put("stockType",stockType);
json.put("pricechange",data.getString("change"));
json.put("pricecurrent",data.getString("lastPrice"));
json.put("priceprevclose",data.getString("previousClose"));
json.put("PREVDATE","");
json.put("VOL",jsonData.getJSONObject("preOpenMarket").getString("totalTradedVolume"));
json.put("dataSourceType","3");
json.put("symbol",symbol);
json.put("BSEID",symbol);
json.put("NSEID",symbol);
json.put("LTH",data.getString("upperCP"));
json.put("LTL",data.getString("lowerCP"));
json.put("OPN",data.getString("open"));
return json;
} catch (IOException e) {
throw new RuntimeException("Failed to fetch data", e);
}
}
public static StockHistoryResponse stockKLineFromHttp(StockHistoryRequest stockHistoryRequest) {
initCookie();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String fromDate = sdf.format(new Date(stockHistoryRequest.getFrom() * 1000));
String toDate = sdf.format(new Date(stockHistoryRequest.getTo() * 1000));
String url = String.format("%s/api/historical/cm/equity?symbol=%s&from=%s&to=%s", NSE_INDIA_URL, stockHistoryRequest.getSymbol(), fromDate, toDate);
Request request = createRequest(url).newBuilder()
.addHeader("referer", NSE_INDIA_URL)
.addHeader("origin", NSE_INDIA_URL)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Request failed with code: " + response.code());
}
JSONObject jsonData = JSONObject.parseObject(response.body().string());
JSONArray data =jsonData.getJSONArray("data");
StockHistoryResponse result = new StockHistoryResponse();
List<Long> tList = new ArrayList<>();
List<Double> oList = new ArrayList<>();
List<Double> hList = new ArrayList<>();
List<Double> lList = new ArrayList<>();
List<Double> cList = new ArrayList<>();
List<Long> vList = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
Long t, v;
Double o, h, l, c;
try {
JSONObject jsonObject = data.getJSONObject(i);
String timestampStr = jsonObject.getString("TIMESTAMP");
Instant instant = Instant.parse(timestampStr);
t = instant.toEpochMilli() / 1000;
o = jsonObject.getDouble("CH_OPENING_PRICE");
c = jsonObject.getDouble("CH_CLOSING_PRICE");
h = jsonObject.getDouble("CH_TRADE_HIGH_PRICE");
l = jsonObject.getDouble("CH_TRADE_LOW_PRICE");
v = jsonObject.getLong("CH_TOT_TRADED_VAL");
} catch (Exception e) {
continue;
}
tList.add(t);
oList.add(o);
hList.add(h);
lList.add(l);
cList.add(c);
vList.add(v);
}
result.setT(tList);
result.setO(oList);
result.setH(hList);
result.setL(lList);
result.setC(cList);
result.setV(vList);
return result;
} catch (IOException e) {
throw new RuntimeException("Failed to fetch data", e);
}
}
}

View File

@@ -66,6 +66,50 @@ public class RequestCacheUtils {
return response; return response;
} }
/**
* 根据时间创建缓存
* @param key key
* @param duration 时间(毫秒)
* @return
*/
public static Cache<String, ServerResponse<?>> cacheByMilliseconds(String key,long duration) {
if(! map.containsKey(key)) {
log.info("创建缓存: {}", key);
Cache<String, ServerResponse<?>> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(duration,TimeUnit.MILLISECONDS)
.weakValues()
.recordStats()
.build(
// new CacheLoader<String, Object>() {
// @Override
// public Object load(String key) throws Exception {
// return func.apply(key);
// }
// }
);
map.put(key, cache);
}
return map.get(key);
}
@SneakyThrows
public static <T> ServerResponse<T> cache(String module, String key,long duration, Function<String, ServerResponse<?>> func) {
Cache<String, ServerResponse<?>> cache = cacheByMilliseconds(module,duration);
AtomicBoolean bool = new AtomicBoolean(true);
ServerResponse<T> response = (ServerResponse<T>) cache.get(key, () -> {
bool.set(false);
return func.apply(key);
});
if(bool.get()) {
log.info("命中缓存 module: {}, key: {}, 时间戳: {}", module, key, System.currentTimeMillis());
}
return response;
}
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
ServerResponse<Object> response = null; ServerResponse<Object> response = null;
Function<String, ServerResponse<?>> func = (string) -> { Function<String, ServerResponse<?>> func = (string) -> {

View File

@@ -20,7 +20,7 @@ import cn.stock.market.domain.basic.service.SiteArticleService;
import cn.stock.market.utils.ServerResponse; import cn.stock.market.utils.ServerResponse;
@Controller @Controller
@RequestMapping({"/api/market/art/", "/api/hq/art/"}) @RequestMapping({"/market/api/market/art/","/market/api/market/art/","/api/market/art/", "/api/hq/art/"})
@Api(tags = "公告信息") @Api(tags = "公告信息")
public class ArticleApiController extends BaseController { public class ArticleApiController extends BaseController {

View File

@@ -2,6 +2,7 @@ package cn.stock.market.web;
import cn.stock.market.domain.basic.entity.BtodayStock; import cn.stock.market.domain.basic.entity.BtodayStock;
import cn.stock.market.domain.basic.service.BtodayStockService; import cn.stock.market.domain.basic.service.BtodayStockService;
import cn.stock.market.web.annotations.EncryptFilter;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
@@ -21,6 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -34,7 +36,7 @@ public class BTodayStockController {
@Autowired @Autowired
private BtodayStockService btodayStockService; private BtodayStockService btodayStockService;
@GetMapping("/api/bToday/kLine") @GetMapping({"/market/api/bToday/kLine","/api/bToday/kLine"})
@ApiOperation(value = "股票详情K线图",httpMethod = "GET") @ApiOperation(value = "股票详情K线图",httpMethod = "GET")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name="exchange",value = "BSE或者NSE"), @ApiImplicitParam(name="exchange",value = "BSE或者NSE"),
@@ -43,6 +45,8 @@ public class BTodayStockController {
@ApiImplicitParam(name="durationtype",value = "D(1D的时候传D),D(5D的时候传D),M(3M的时候传M),Y(1Y的时候传Y),Y(5Y的时候传Y),Y(10Y的时候传Y)"), @ApiImplicitParam(name="durationtype",value = "D(1D的时候传D),D(5D的时候传D),M(3M的时候传M),Y(1Y的时候传Y),Y(5Y的时候传Y),Y(10Y的时候传Y)"),
@ApiImplicitParam(name="duration",value = "1(1D的时候传1),5(5D的时候传5),3(3M的时候传3),1(1Y的时候传1),5(5Y的时候传5),10(10Y的时候传10)"), @ApiImplicitParam(name="duration",value = "1(1D的时候传1),5(5D的时候传5),3(3M的时候传3),1(1Y的时候传1),5(5Y的时候传5),10(10Y的时候传10)"),
}) })
@EncryptFilter(decryptRequest = false)
public JSONArray getPriceChartCompanyPullView( public JSONArray getPriceChartCompanyPullView(
@RequestParam(value = "exchange") String exchange, @RequestParam(value = "exchange") String exchange,
@RequestParam(value = "co_code") String coCode, @RequestParam(value = "co_code") String coCode,
@@ -137,7 +141,8 @@ public class BTodayStockController {
"fromredis: 标志是否来自 Redis 缓存false 表示不是", response = JSONObject.class), "fromredis: 标志是否来自 Redis 缓存false 表示不是", response = JSONObject.class),
}) })
@GetMapping("/api/bToday/stockDetail") @GetMapping({"/market/api/bToday/stockDetail","/api/bToday/stockDetail"})
@EncryptFilter(decryptRequest = false)
public com.alibaba.fastjson.JSONObject getPriceChartCompanyPullView( public com.alibaba.fastjson.JSONObject getPriceChartCompanyPullView(
@RequestParam(value = "exchange") String exchange, @RequestParam(value = "exchange") String exchange,
@RequestParam(value = "co_code") String coCode @RequestParam(value = "co_code") String coCode
@@ -155,6 +160,19 @@ public class BTodayStockController {
String forObject = restTemplate.getForObject(apiUrl, String.class); String forObject = restTemplate.getForObject(apiUrl, String.class);
JSONObject jsonObject = JSON.parseObject(forObject); JSONObject jsonObject = JSON.parseObject(forObject);
JSONArray arryData = jsonObject.getJSONArray("data");
if (arryData != null&&arryData.size()>0) {
try {
JSONObject jsonObject1 = arryData.getJSONObject(0);
String price = jsonObject1.getString("price");
double priceValue = Double.parseDouble(price);
DecimalFormat df = new DecimalFormat("0.00");
jsonObject1.put("price", df.format(priceValue));
} catch (NumberFormatException e) {
// Handle the case where price is not a valid double
e.printStackTrace();
}
}
jsonObject.put("id",btodayStock.getId()); jsonObject.put("id",btodayStock.getId());
return jsonObject; return jsonObject;
} }

View File

@@ -25,7 +25,7 @@ import springfox.documentation.annotations.ApiIgnore;
* @created Dec 4, 2018 10:22:44 PM * @created Dec 4, 2018 10:22:44 PM
*/ */
@RestController @RestController
@RequestMapping("/api/hq/") @RequestMapping({"/market/api/hq/","/api/hq/"})
@ApiIgnore @ApiIgnore
public class InfoController { public class InfoController {
@Value("${spring.application.name}") @Value("${spring.application.name}")
@@ -40,6 +40,7 @@ public class InfoController {
public Map<String, Object> test(@RequestParam(required = false) String key) { public Map<String, Object> test(@RequestParam(required = false) String key) {
Map<String, Object> map = Maps.newHashMap(); Map<String, Object> map = Maps.newHashMap();
map.put("stockMarketDbUrl", stockMarketDbUrl); map.put("stockMarketDbUrl", stockMarketDbUrl);
map.put("stockMarketDbUrl1", stockMarketDbUrl);
if(StringUtils.isNotBlank(key)) { if(StringUtils.isNotBlank(key)) {
map.put("key", PropertiesUtil.getProperty(key)); map.put("key", PropertiesUtil.getProperty(key));
} }

View File

@@ -1,13 +1,15 @@
package cn.stock.market.web; package cn.stock.market.web;
import cn.hutool.core.date.DateUtil;
import cn.stock.market.MoneyStockSuggestDTO; import cn.stock.market.MoneyStockSuggestDTO;
import cn.stock.market.domain.basic.entity.MoneyStock; import cn.stock.market.domain.basic.entity.MoneyStock;
import cn.stock.market.domain.basic.repository.MoneyStockRepository; import cn.stock.market.domain.basic.repository.MoneyStockRepository;
import cn.stock.market.dto.StockHistoryRequest; import cn.stock.market.dto.StockHistoryRequest;
import cn.stock.market.dto.StockHistoryResponse; import cn.stock.market.dto.StockHistoryResponse;
import cn.stock.market.infrastructure.db.po.QMoneyStockPO; import cn.stock.market.infrastructure.db.po.QMoneyStockPO;
import cn.stock.market.utils.RequestCacheUtils; import cn.stock.market.utils.NseIndiaRequest;
import cn.stock.market.utils.ServerResponse; import cn.stock.market.utils.ServerResponse;
import cn.stock.market.web.annotations.EncryptFilter;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache; import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
@@ -36,9 +38,7 @@ import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -60,13 +60,11 @@ public class MoneyApiController {
private static final String EXTERNAL_API_URL = "https://priceapi.moneycontrol.com/techCharts/indianMarket/stock/history"; private static final String EXTERNAL_API_URL = "https://priceapi.moneycontrol.com/techCharts/indianMarket/stock/history";
@ApiOperation(value = "股票详情信息", httpMethod = "GET")
@ApiOperation(value = "股票详情信息",httpMethod = "GET")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name="stockType",value = "BSE或者NSE"), @ApiImplicitParam(name = "stockType", value = "BSE或者NSE"),
@ApiImplicitParam(name="symbol",value = "scId值"), @ApiImplicitParam(name = "symbol", value = "scId值"),
@ApiImplicitParam(name="id",value = "id值"), @ApiImplicitParam(name = "id", value = "id值"),
}) })
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "" + @ApiResponse(code = 200, message = "" +
@@ -165,45 +163,68 @@ public class MoneyApiController {
"priceprevclose: 前一交易日的收盘价\n" + "priceprevclose: 前一交易日的收盘价\n" +
"30DayAvg: 过去30天的平均", response = JSONObject.class), "30DayAvg: 过去30天的平均", response = JSONObject.class),
}) })
@GetMapping("/api/market/money/getStockDetail") @GetMapping({"/market/api/market/money/getStockDetail", "/api/market/money/getStockDetail"})
@ResponseBody @ResponseBody
public ServerResponse getStockDetail(@RequestParam String stockType, @RequestParam String symbol ) { @EncryptFilter(decryptRequest = false)
String url = String.format("https://priceapi.moneycontrol.com/pricefeed/%s/equitycash/%s",stockType,symbol);
MoneyStock moneyStock = moneyStockRepository.findOne(QMoneyStockPO.moneyStockPO.stockType.eq(stockType).and(QMoneyStockPO.moneyStockPO.moneyScId.eq(symbol))).orElse(null); public ServerResponse getStockDetail(@RequestParam String stockType, @RequestParam String symbol) {
MoneyStock moneyStock = moneyStockRepository.findOne(QMoneyStockPO.moneyStockPO.stockType.eq(stockType)
.and(QMoneyStockPO.moneyStockPO.moneyScId.eq(symbol))
.and(QMoneyStockPO.moneyStockPO.isLock.eq(0))
.and(QMoneyStockPO.moneyStockPO.isShow.eq(0)))
.orElse(null);
/* if(moneyStock==null){ /* if(moneyStock==null){
return ServerResponse.createByErrorMsg("没有找到该股票"); return ServerResponse.createByErrorMsg("没有找到该股票");
}*/ }*/
// 设置重试次数 // 设置重试次数
if ("ANI".equals(symbol)) {
JSONObject json1 = new JSONObject();
json1.put("company", "Archit Nuwood Industries Ltd");
json1.put("pricepercentchange", "Archit Nuwood Industries Ltd");
json1.put("stockType", stockType);
json1.put("pricecurrent", "386");
json1.put("dataSourceType", "3");
json1.put("symbol", "ANI");
json1.put("BSEID", "ANI");
json1.put("NSEID", "ANI");
return ServerResponse.createBySuccess(json1);
}
String url = String.format("https://priceapi.moneycontrol.com/pricefeed/%s/equitycash/%s", stockType, symbol);
int maxRetries = 3; int maxRetries = 3;
for (int retry = 1; retry <= maxRetries; retry++) { for (int retry = 1; retry <= maxRetries; retry++) {
try { try {
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class); ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
JSONObject json1 = new JSONObject(); JSONObject json1 = new JSONObject();
if (responseEntity.getStatusCode().value() == 200 && responseEntity.getBody() != null ) { if (responseEntity.getStatusCode().value() == 200 && responseEntity.getBody() != null) {
JSONObject data = JSONObject.parseObject(responseEntity.getBody()).getJSONObject("data"); JSONObject data = JSONObject.parseObject(responseEntity.getBody()).getJSONObject("data");
if(data!=null){ if (data != null) {
json1.put("company",data.getString("company")); json1.put("company", data.getString("SC_FULLNM"));
json1.put("pricepercentchange",data.getString("pricepercentchange")); json1.put("pricepercentchange", data.getString("pricepercentchange"));
json1.put("stockType",stockType); json1.put("stockType", stockType);
json1.put("pricechange",data.getString("pricechange")); json1.put("pricechange", data.getString("pricechange"));
json1.put("pricecurrent",data.getString("pricecurrent")); json1.put("pricecurrent", data.getString("pricecurrent"));
json1.put("priceprevclose",data.getString("priceprevclose")); json1.put("priceprevclose", data.getString("priceprevclose"));
json1.put("PREVDATE",data.getString("PREVDATE")); json1.put("PREVDATE", data.getString("PREVDATE"));
json1.put("VOL",data.getString("VOL")); json1.put("VOL", data.getString("VOL"));
json1.put("dataSourceType","3"); json1.put("dataSourceType", "3");
json1.put("symbol",data.getString("symbol")); json1.put("symbol", data.getString("symbol"));
json1.put("BSEID",data.getString("BSEID")); json1.put("BSEID", data.getString("BSEID"));
json1.put("NSEID",data.getString("NSEID")); json1.put("NSEID", data.getString("NSEID"));
json1.put("LTH",data.getString("HP")); json1.put("LTH", data.getString("HP"));
json1.put("LTL",data.getString("LP")); json1.put("LTL", data.getString("LP"));
json1.put("OPN",data.getString("OPN")); json1.put("OPN", data.getString("OPN"));
if(null!=moneyStock){ if (null != moneyStock) {
json1.put("id",moneyStock.getId()); json1.put("id", moneyStock.getId());
}
if (StringUtils.equals(data.getString("pricecurrent"), "0.00")
&& (!StringUtils.equals(data.getString("priceprevclose"), "0.00"))) {
json1.put("pricecurrent", data.getString("priceprevclose"));
} }
} }
return ServerResponse.createBySuccess(json1); if (json1.size() > 0)
return ServerResponse.createBySuccess(json1);
} }
} catch (Exception e) { } catch (Exception e) {
} }
// 如果不是最后一次重试,则等待一段时间再进行下一次重试 // 如果不是最后一次重试,则等待一段时间再进行下一次重试
@@ -216,20 +237,31 @@ public class MoneyApiController {
} }
} }
} }
if (moneyStock != null && moneyStock.getNseIndiaId() != null && !moneyStock.getNseIndiaId().isEmpty()) {
try {
// Get data from nseindia
JSONObject json = NseIndiaRequest.stockByJYSFromHttp(stockType, symbol, moneyStock.getNseIndiaId());
json.put("id", moneyStock.getId());
json.put("company",moneyStock.getStockName());
return ServerResponse.createBySuccess(json);
} catch (Exception e) {
return null;
}
}
return null; return null;
} }
private static List<MoneyStockSuggestDTO> nseActives() {
private static List<MoneyStockSuggestDTO> nseActives() {
List<MoneyStockSuggestDTO> list = new ArrayList<>(); List<MoneyStockSuggestDTO> list = new ArrayList<>();
String url = "https://www.moneycontrol.com/stocks/marketstats/nse-mostactive-stocks/nifty-50-9/"; String url = "https://www.moneycontrol.com/stocks/marketstats/nse-mostactive-stocks/nifty-50-9/";
try { try {
Document doc = Jsoup.connect(url).get(); Document doc = Jsoup.connect(url).get();
int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size(); int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size();
for (int i =1;i<=size;i++){ for (int i = 1; i <= size; i++) {
MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO(); MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO();
Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child("+i+") > td.PR > span > a").first(); Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > a").first();
if (company_a != null) { if (company_a != null) {
String stockUrl = company_a.attr("href"); String stockUrl = company_a.attr("href");
String stockName = company_a.text(); String stockName = company_a.text();
@@ -237,7 +269,7 @@ public class MoneyApiController {
dto.setStockUrl(stockUrl); dto.setStockUrl(stockUrl);
} }
String highPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child("+i+") > td:nth-child(2)").first()); String highPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(2)").first());
dto.setHighPrice(highPrice); dto.setHighPrice(highPrice);
String lowPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(3)").first()); String lowPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(3)").first());
@@ -262,7 +294,7 @@ public class MoneyApiController {
return list; return list;
} }
private static List<MoneyStockSuggestDTO> bseActives() { private static List<MoneyStockSuggestDTO> bseActives() {
List<MoneyStockSuggestDTO> list = new ArrayList<>(); List<MoneyStockSuggestDTO> list = new ArrayList<>();
String url = "https://www.moneycontrol.com/stocks/marketstats/bsemact1/index.php"; String url = "https://www.moneycontrol.com/stocks/marketstats/bsemact1/index.php";
@@ -270,9 +302,9 @@ public class MoneyApiController {
Document doc = Jsoup.connect(url).get(); Document doc = Jsoup.connect(url).get();
int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size(); int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size();
System.err.println(size); System.err.println(size);
for (int i =1;i<=size;i++){ for (int i = 1; i <= size; i++) {
MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO(); MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO();
Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child("+i+") > td.PR > span > a").first(); Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > a").first();
if (company_a != null) { if (company_a != null) {
String stockUrl = company_a.attr("href"); String stockUrl = company_a.attr("href");
String stockName = company_a.text(); String stockName = company_a.text();
@@ -280,18 +312,18 @@ public class MoneyApiController {
dto.setStockUrl(stockUrl); dto.setStockUrl(stockUrl);
} }
String highPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(2)").first()); String highPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(3)").first());
dto.setHighPrice(highPrice); dto.setHighPrice(highPrice);
String lowPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(3)").first()); String lowPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(4)").first());
dto.setLowPrice(lowPrice); dto.setLowPrice(lowPrice);
String lastPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(4)").first()); String lastPrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(5)").first());
dto.setLastPrice(lastPrice); dto.setLastPrice(lastPrice);
String prevClosePrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(5)").first()); /* String prevClosePrice = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(6)").first());
dto.setPrevClosePrice(prevClosePrice); dto.setPrevClosePrice(prevClosePrice);
*/
String changePercent = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(6)").first()); String changePercent = getTextOrEmpty(doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td:nth-child(6)").first());
dto.setChangePercent(changePercent); dto.setChangePercent(changePercent);
@@ -301,19 +333,19 @@ public class MoneyApiController {
} }
} catch (IOException e) { } catch (IOException e) {
log.error("occur Exception",e); log.error("occur Exception", e);
} }
return list; return list;
} }
private static List<MoneyStockSuggestDTO> bseGainer() { private static List<MoneyStockSuggestDTO> bseGainer() {
String url = "https://www.moneycontrol.com/stocks/marketstats/bse-gainer/sensex_4/"; String url = "https://www.moneycontrol.com/stocks/marketstats/bse-gainer/sensex_4/";
List<MoneyStockSuggestDTO> list = Lists.newArrayList(); List<MoneyStockSuggestDTO> list = Lists.newArrayList();
try { try {
Document doc = Jsoup.connect(url).get(); Document doc = Jsoup.connect(url).get();
int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size(); int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size();
for (int i =1;i<=size;i++){ for (int i = 1; i <= size; i++) {
Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child("+i+") > td.PR > span > a").first(); Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > a").first();
MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO(); MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO();
if (company_a != null) { if (company_a != null) {
String stockUrl = company_a.attr("href"); String stockUrl = company_a.attr("href");
@@ -357,9 +389,9 @@ public class MoneyApiController {
try { try {
Document doc = Jsoup.connect(url).get(); Document doc = Jsoup.connect(url).get();
int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size(); int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size();
for (int i =1;i<=size;i++){ for (int i = 1; i <= size; i++) {
MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO(); MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO();
Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child("+i+") > td.PR > span > h3 > a").first(); Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > h3 > a").first();
if (company_a != null) { if (company_a != null) {
String stockUrl = company_a.attr("href"); String stockUrl = company_a.attr("href");
String stockName = company_a.text(); String stockName = company_a.text();
@@ -394,20 +426,20 @@ public class MoneyApiController {
return list; return list;
} }
private static List<MoneyStockSuggestDTO> nseTopLoser() { private static List<MoneyStockSuggestDTO> nseTopLoser() {
String url = "https://www.moneycontrol.com/stocks/marketstats/nseloser/index.php"; String url = "https://www.moneycontrol.com/stocks/marketstats/nseloser/index.php";
List<MoneyStockSuggestDTO> list = Lists.newArrayList(); List<MoneyStockSuggestDTO> list = Lists.newArrayList();
try { try {
Document doc = Jsoup.connect(url).get(); Document doc = Jsoup.connect(url).get();
int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size(); int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size();
for (int i =1;i<=size;i++){ for (int i = 1; i <= size; i++) {
MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO(); MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO();
Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child("+i+") > td.PR > span > h3 > a").first(); Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > h3 > a").first();
if (company_a != null) { if (company_a != null) {
String stockUrl = company_a.attr("href"); String stockUrl = company_a.attr("href");
String stockName = company_a.text(); String stockName = company_a.text();
dto.setStockUrl(stockUrl); dto.setStockUrl(stockUrl);
dto.setStockName(stockName); dto.setStockName(stockName);
} }
@@ -434,7 +466,7 @@ public class MoneyApiController {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return list; return list;
} }
private static List<MoneyStockSuggestDTO> bseTopLoser() { private static List<MoneyStockSuggestDTO> bseTopLoser() {
@@ -444,7 +476,7 @@ public class MoneyApiController {
try { try {
Document doc = Jsoup.connect(url).get(); Document doc = Jsoup.connect(url).get();
int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size(); int size = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr").size();
for (int i =1;i<=size;i++){ for (int i = 1; i <= size; i++) {
Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > a").first(); Element company_a = doc.select("#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div > div.bsr_table.hist_tbl_hm > table > tbody > tr:nth-child(" + i + ") > td.PR > span > a").first();
MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO(); MoneyStockSuggestDTO dto = new MoneyStockSuggestDTO();
if (company_a != null) { if (company_a != null) {
@@ -489,18 +521,18 @@ public class MoneyApiController {
} }
@ApiOperation(value = "股票推荐TopGainer", httpMethod = "GET")
@ApiOperation(value = "股票推荐TopGainer",httpMethod = "GET")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name="stockType",value = "BSE或者NSE"), @ApiImplicitParam(name = "stockType", value = "BSE或者NSE"),
}) })
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "" + @ApiResponse(code = 200, message = "" +
"股票推荐相关: top gainer", response = JSONObject.class), "股票推荐相关: top gainer", response = JSONObject.class),
}) })
@GetMapping("/api/market/money/getTopGainer") @GetMapping({"/market/api/market/money/getTopGainer", "/api/market/money/getTopGainer"})
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public List<MoneyStockSuggestDTO> getTopGainer(@RequestParam String stockType) { public List<MoneyStockSuggestDTO> getTopGainer(@RequestParam String stockType) {
List<MoneyStockSuggestDTO> moneyStockSuggestDTOS = null; List<MoneyStockSuggestDTO> moneyStockSuggestDTOS = null;
// 尝试从缓存中获取结果 // 尝试从缓存中获取结果
@@ -513,15 +545,17 @@ public class MoneyApiController {
} else if (StringUtils.equals(stockType, "bse")) { } else if (StringUtils.equals(stockType, "bse")) {
moneyStockSuggestDTOS = bseGainer(); moneyStockSuggestDTOS = bseGainer();
} }
Map<Object, Boolean> map = new HashMap<>();
moneyStockSuggestDTOS = moneyStockSuggestDTOS.stream().filter(f->StringUtils.isNotBlank(f.getStockName())).collect(Collectors.toList()); moneyStockSuggestDTOS = moneyStockSuggestDTOS.stream()
if(CollectionUtils.isNotEmpty(moneyStockSuggestDTOS)){ .filter(f -> StringUtils.isNotBlank(f.getStockName()))
.filter(i -> map.putIfAbsent(i.getStockName(), Boolean.TRUE) == null).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(moneyStockSuggestDTOS)) {
List<String> selfUlrList = moneyStockSuggestDTOS.stream().map(MoneyStockSuggestDTO::getStockName).collect(Collectors.toList()); List<String> selfUlrList = moneyStockSuggestDTOS.stream().map(MoneyStockSuggestDTO::getStockName).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(selfUlrList)){ if (CollectionUtils.isNotEmpty(selfUlrList)) {
List<MoneyStock> all = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.stockName.in(selfUlrList)); List<MoneyStock> all = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.stockName.in(selfUlrList));
if(CollectionUtils.isNotEmpty(all)){ if (CollectionUtils.isNotEmpty(all)) {
moneyStockSuggestDTOS.stream().filter(f->all.stream().anyMatch(s->s.getStockName().equals(f.getStockName()))) moneyStockSuggestDTOS.stream().filter(f -> all.stream().anyMatch(s -> s.getStockName().equals(f.getStockName())))
.forEach(f->f.setScId(all.stream().filter(s->s.getStockName().equals(f.getStockName())).findFirst().orElse(null).getMoneyScId())); .forEach(f -> f.setScId(all.stream().filter(s -> s.getStockName().equals(f.getStockName())).findFirst().orElse(null).getMoneyScId()));
} }
} }
gainerStockSuggestCache.put(stockType, moneyStockSuggestDTOS); gainerStockSuggestCache.put(stockType, moneyStockSuggestDTOS);
@@ -532,42 +566,47 @@ public class MoneyApiController {
} }
@ApiOperation(value = "股票推荐TopLoser",httpMethod = "GET") @ApiOperation(value = "股票推荐TopLoser", httpMethod = "GET")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name="stockType",value = "BSE或者NSE"), @ApiImplicitParam(name = "stockType", value = "BSE或者NSE"),
}) })
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "" + @ApiResponse(code = 200, message = "" +
"股票推荐相关: TopLoser", response = JSONObject.class), "股票推荐相关: TopLoser", response = JSONObject.class),
}) })
@GetMapping("/api/market/money/getTopLoser") @GetMapping({"/market/api/market/money/getTopLoser", "/api/market/money/getTopLoser"})
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public List<MoneyStockSuggestDTO> getTopLoser(@RequestParam String stockType) { public List<MoneyStockSuggestDTO> getTopLoser(@RequestParam String stockType) {
List<MoneyStockSuggestDTO> moneyStockSuggestDTOS = null; List<MoneyStockSuggestDTO> moneyStockSuggestDTOS = null;
moneyStockSuggestDTOS = loserStockSuggestCache.getIfPresent(stockType); moneyStockSuggestDTOS = loserStockSuggestCache.getIfPresent(stockType);
if(null==moneyStockSuggestDTOS){ if (null == moneyStockSuggestDTOS) {
if(StringUtils.equals(stockType,"nse")){ if (StringUtils.equals(stockType, "nse")) {
moneyStockSuggestDTOS = nseTopLoser(); moneyStockSuggestDTOS = nseTopLoser();
}else if(StringUtils.equals(stockType,"bse")){ } else if (StringUtils.equals(stockType, "bse")) {
moneyStockSuggestDTOS = bseTopLoser(); moneyStockSuggestDTOS = bseTopLoser();
} }
moneyStockSuggestDTOS = moneyStockSuggestDTOS.stream().filter(f->StringUtils.isNotBlank(f.getStockName())).collect(Collectors.toList()); Map<Object, Boolean> map = new HashMap<>();
if(CollectionUtils.isNotEmpty(moneyStockSuggestDTOS)){ moneyStockSuggestDTOS = moneyStockSuggestDTOS.stream()
moneyStockSuggestDTOS.stream().forEach(f->f.setDispId(extractLastSegment(f.getStockUrl()))); .filter(f -> StringUtils.isNotBlank(f.getStockName()))
.filter(i -> map.putIfAbsent(i.getStockName(), Boolean.TRUE) == null).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(moneyStockSuggestDTOS)) {
moneyStockSuggestDTOS.stream().forEach(f -> f.setDispId(extractLastSegment(f.getStockUrl())));
List<String> selfUlrList = moneyStockSuggestDTOS.stream().map(MoneyStockSuggestDTO::getStockName).collect(Collectors.toList()); List<String> selfUlrList = moneyStockSuggestDTOS.stream().map(MoneyStockSuggestDTO::getStockName).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(selfUlrList)){ if (CollectionUtils.isNotEmpty(selfUlrList)) {
List<MoneyStock> all = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.stockName.in(selfUlrList)); List<MoneyStock> all = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.stockName.in(selfUlrList));
if(CollectionUtils.isNotEmpty(all)){ if (CollectionUtils.isNotEmpty(all)) {
moneyStockSuggestDTOS.stream().filter(f->all.stream().anyMatch(s->s.getStockName().equals(f.getStockName()))) moneyStockSuggestDTOS.stream().filter(f -> all.stream().anyMatch(s -> s.getStockName().equals(f.getStockName())))
.forEach(f->f.setScId(all.stream().filter(s->s.getStockName().equals(f.getStockName())).findFirst().orElse(null).getMoneyScId())); .forEach(f -> f.setScId(all.stream().filter(s -> s.getStockName().equals(f.getStockName())).findFirst().orElse(null).getMoneyScId()));
} }
List<MoneyStockSuggestDTO> noScIdList = moneyStockSuggestDTOS.stream().filter(f->StringUtils.isBlank(f.getScId())).collect(Collectors.toList()); List<MoneyStockSuggestDTO> noScIdList = moneyStockSuggestDTOS.stream().filter(f -> StringUtils.isBlank(f.getScId())).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(noScIdList)){ if (CollectionUtils.isNotEmpty(noScIdList)) {
List<String> dispIdList = noScIdList.stream().map(MoneyStockSuggestDTO::getDispId).collect(Collectors.toList()); List<String> dispIdList = noScIdList.stream().map(MoneyStockSuggestDTO::getDispId).collect(Collectors.toList());
List<MoneyStock> all1 = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.selfDispId.in(dispIdList)); List<MoneyStock> all1 = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.selfDispId.in(dispIdList));
if(CollectionUtils.isNotEmpty(all1)){ if (CollectionUtils.isNotEmpty(all1)) {
moneyStockSuggestDTOS.stream().filter(f->all1.stream().anyMatch(s->s.getSelfDispId().equals(f.getDispId()))) moneyStockSuggestDTOS.stream().filter(f -> all1.stream().anyMatch(s -> s.getSelfDispId().equals(f.getDispId())))
.forEach(f->f.setScId(all.stream().filter(s->s.getSelfDispId().equals(f.getDispId())).findFirst().orElse(null).getMoneyScId())); .forEach(f -> f.setScId(all.stream().filter(s -> s.getSelfDispId().equals(f.getDispId())).findFirst().orElse(null).getMoneyScId()));
} }
} }
} }
@@ -578,44 +617,47 @@ public class MoneyApiController {
} }
@ApiOperation(value = "股票推荐TopActive", httpMethod = "GET")
@ApiOperation(value = "股票推荐TopActive",httpMethod = "GET")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name="stockType",value = "BSE或者NSE"), @ApiImplicitParam(name = "stockType", value = "BSE或者NSE"),
}) })
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "" + @ApiResponse(code = 200, message = "" +
"股票推荐相关: top active", response = JSONObject.class), "股票推荐相关: top active", response = JSONObject.class),
}) })
@GetMapping("/api/market/money/getTopActives") @GetMapping({"/market/api/market/money/getTopActives", "/api/market/money/getTopActives"})
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public List<MoneyStockSuggestDTO> getTopActive(@RequestParam String stockType) { public List<MoneyStockSuggestDTO> getTopActive(@RequestParam String stockType) {
List<MoneyStockSuggestDTO> moneyStockSuggestDTOS = null; List<MoneyStockSuggestDTO> moneyStockSuggestDTOS = null;
moneyStockSuggestDTOS = activesStockSuggestCache.getIfPresent(stockType); moneyStockSuggestDTOS = activesStockSuggestCache.getIfPresent(stockType);
if(moneyStockSuggestDTOS ==null){ if (moneyStockSuggestDTOS == null) {
if(StringUtils.equals(stockType,"nse")){ if (StringUtils.equals(stockType, "nse")) {
moneyStockSuggestDTOS = nseActives(); moneyStockSuggestDTOS = nseActives();
}else if(StringUtils.equals(stockType,"bse")){ } else if (StringUtils.equals(stockType, "bse")) {
moneyStockSuggestDTOS = bseActives(); moneyStockSuggestDTOS = bseActives();
} }
moneyStockSuggestDTOS = moneyStockSuggestDTOS.stream().filter(f->StringUtils.isNotBlank(f.getStockName())).collect(Collectors.toList()); Map<Object, Boolean> map = new HashMap<>();
if(CollectionUtils.isNotEmpty(moneyStockSuggestDTOS)){ moneyStockSuggestDTOS = moneyStockSuggestDTOS.stream()
moneyStockSuggestDTOS.stream().forEach(f->f.setDispId(extractLastSegment(f.getStockUrl()))); .filter(f -> StringUtils.isNotBlank(f.getStockName()))
.filter(i -> map.putIfAbsent(i.getStockName(), Boolean.TRUE) == null).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(moneyStockSuggestDTOS)) {
moneyStockSuggestDTOS.stream().forEach(f -> f.setDispId(extractLastSegment(f.getStockUrl())));
List<String> selfUlrList = moneyStockSuggestDTOS.stream().map(MoneyStockSuggestDTO::getStockName).collect(Collectors.toList()); List<String> selfUlrList = moneyStockSuggestDTOS.stream().map(MoneyStockSuggestDTO::getStockName).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(selfUlrList)){ if (CollectionUtils.isNotEmpty(selfUlrList)) {
List<MoneyStock> all = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.stockName.in(selfUlrList)); List<MoneyStock> all = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.stockName.in(selfUlrList));
if(CollectionUtils.isNotEmpty(all)){ if (CollectionUtils.isNotEmpty(all)) {
moneyStockSuggestDTOS.stream().filter(f->all.stream().anyMatch(s->s.getStockName().equals(f.getStockName()))) moneyStockSuggestDTOS.stream().filter(f -> all.stream().anyMatch(s -> s.getStockName().equals(f.getStockName())))
.forEach(f->f.setScId(all.stream().filter(s->s.getStockName().equals(f.getStockName())).findFirst().orElse(null).getMoneyScId())); .forEach(f -> f.setScId(all.stream().filter(s -> s.getStockName().equals(f.getStockName())).findFirst().orElse(null).getMoneyScId()));
} }
List<MoneyStockSuggestDTO> noScIdList = moneyStockSuggestDTOS.stream().filter(f->StringUtils.isBlank(f.getScId())).collect(Collectors.toList()); List<MoneyStockSuggestDTO> noScIdList = moneyStockSuggestDTOS.stream().filter(f -> StringUtils.isBlank(f.getScId())).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(noScIdList)){ if (CollectionUtils.isNotEmpty(noScIdList)) {
List<String> dispIdList = noScIdList.stream().map(MoneyStockSuggestDTO::getDispId).collect(Collectors.toList()); List<String> dispIdList = noScIdList.stream().map(MoneyStockSuggestDTO::getDispId).collect(Collectors.toList());
List<MoneyStock> all1 = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.selfDispId.in(dispIdList)); List<MoneyStock> all1 = moneyStockRepository.findAll(QMoneyStockPO.moneyStockPO.selfDispId.in(dispIdList));
if(CollectionUtils.isNotEmpty(all1)){ if (CollectionUtils.isNotEmpty(all1)) {
moneyStockSuggestDTOS.stream().filter(f->all1.stream().anyMatch(s->s.getSelfDispId().equals(f.getDispId()))) moneyStockSuggestDTOS.stream().filter(f -> all1.stream().anyMatch(s -> s.getSelfDispId().equals(f.getDispId())))
.forEach(f->f.setScId(all.stream().filter(s->s.getSelfDispId().equals(f.getDispId())).findFirst().orElse(null).getMoneyScId())); .forEach(f -> f.setScId(all.stream().filter(s -> s.getSelfDispId().equals(f.getDispId())).findFirst().orElse(null).getMoneyScId()));
} }
} }
} }
@@ -627,9 +669,8 @@ public class MoneyApiController {
} }
@GetMapping({"/market/api/market/money/history/kLine", "/api/market/money/history/kLine"})
@GetMapping("/api/market/money/history/kLine") @ApiOperation(value = "获取kline的money数据源", notes = "获取kline的money数据源", response = StockHistoryResponse.class)
@ApiOperation(value = "获取kline的money数据源", notes = "获取kline的money数据源",response = StockHistoryResponse.class)
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "symbol", value = "Stock symbol 对应的是NSEID 或者是BSEID", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "symbol", value = "Stock symbol 对应的是NSEID 或者是BSEID", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "resolution", value = "单位:60 1D 1W 1D 对应H,D,W,Y", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "resolution", value = "单位:60 1D 1W 1D 对应H,D,W,Y", required = true, dataType = "String", paramType = "query"),
@@ -639,35 +680,36 @@ public class MoneyApiController {
@ApiImplicitParam(name = "currencyCode", value = "INR 不变", required = true, dataType = "String", paramType = "query") @ApiImplicitParam(name = "currencyCode", value = "INR 不变", required = true, dataType = "String", paramType = "query")
}) })
@ResponseBody @ResponseBody
public ResponseEntity<StockHistoryResponse> getStockHistory( @RequestParam String symbol, @EncryptFilter(decryptRequest = false)
@RequestParam String resolution public ResponseEntity<StockHistoryResponse> getStockHistory(@RequestParam String symbol,
) { @RequestParam String resolution
) {
// 向外部API发起请求并获取响应 // 向外部API发起请求并获取响应
StockHistoryRequest request = new StockHistoryRequest(); StockHistoryRequest request = new StockHistoryRequest();
request.setSymbol(symbol); request.setSymbol(symbol);
Long to = null; Long to = null;
Long from = null; Long from = null;
int countback = 5; int countback = 5;
if(StringUtils.equals("H",resolution)){ if (StringUtils.equals("H", resolution)) {
to = (long) (System.currentTimeMillis() / 1000); to = (long) (System.currentTimeMillis() / 1000);
from = to - (1 * 60 * 60 ); from = to - (60 * 60);
countback = 60; countback = 60;
request.setResolution("1"); request.setResolution("1");
}else if(StringUtils.equals("D",resolution)){ } else if (StringUtils.equals("D", resolution)) {
to = (long) (System.currentTimeMillis() / 1000); to = (long) (System.currentTimeMillis() / 1000);
from = to - (24 * 60 * 60 ); from = to - (24 * 60 * 60);
countback = 9; countback = 390;
request.setResolution("60"); request.setResolution("1");
}else if(StringUtils.equals("W",resolution)){ } else if (StringUtils.equals("W", resolution)) {
to = (long) (System.currentTimeMillis() / 1000); to = (long) (System.currentTimeMillis() / 1000);
from = to - (10 * 24 * 60 * 60 ); from = to - (7 * 24 * 60 * 60);
countback = 7; countback = 471;
request.setResolution("1D"); request.setResolution("5");
}else if(StringUtils.equals("M",resolution)){ } else if (StringUtils.equals("M", resolution)) {
to = (long) (System.currentTimeMillis() / 1000); to = (long) (System.currentTimeMillis() / 1000);
from = to - (35 * 24 * 60 * 60 ); from = to - (35 * 24 * 60 * 60);
countback = 30; countback = 328;
request.setResolution("1D"); request.setResolution("30");
} }
request.setFrom(from); request.setFrom(from);
@@ -675,7 +717,7 @@ public class MoneyApiController {
request.setCountback(countback); request.setCountback(countback);
request.setCurrencyCode("INR"); request.setCurrencyCode("INR");
String apiUrl = buildApiUrl(request); String apiUrl = buildApiUrl(request);
log.info("request url:"+apiUrl); log.info("request url:" + apiUrl);
StockHistoryResponse response = null; StockHistoryResponse response = null;
int maxRetries = 3; int maxRetries = 3;
int retryCount = 0; int retryCount = 0;
@@ -699,9 +741,28 @@ public class MoneyApiController {
} }
if (response != null) { if (response != null) {
setResponse(response, resolution);
// API request successful, return the response // API request successful, return the response
return ResponseEntity.ok(response); return ResponseEntity.ok(response);
} else { } else {
if (!StringUtils.equals("H", resolution)) {
try {
MoneyStock moneyStock = moneyStockRepository.findOne((QMoneyStockPO.moneyStockPO.moneyScId.eq(symbol))
.and(QMoneyStockPO.moneyStockPO.isLock.eq(0))
.and(QMoneyStockPO.moneyStockPO.isShow.eq(0)))
.orElse(null);
if (moneyStock != null && moneyStock.getNseIndiaId() != null && !moneyStock.getNseIndiaId().isEmpty()) {
request.setSymbol(moneyStock.getNseIndiaId());
response = NseIndiaRequest.stockKLineFromHttp(request);
return ResponseEntity.ok(response);
}
} catch (Exception e) {
log.error("Failed to get data from nseindia.", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
// All retries failed, return an error response // All retries failed, return an error response
log.error("Failed to get a successful response after {} retries.", maxRetries); log.error("Failed to get a successful response after {} retries.", maxRetries);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
@@ -709,7 +770,49 @@ public class MoneyApiController {
// 返回响应 // 返回响应
} }
private void setResponse(StockHistoryResponse response, String resolution) {
if (!"ok".equals(response.getS())) {
return;
}
if (Objects.isNull(response.getT())) {
return;
}
if (StringUtils.equals("H", resolution) || StringUtils.equals("D", resolution)) {
List<Long> t = new ArrayList<>();
List<Double> o = new ArrayList<>();
List<Double> h = new ArrayList<>();
List<Double> l = new ArrayList<>();
List<Double> c = new ArrayList<>();
List<Long> v = new ArrayList<>();
//根据时间过滤,只留当天的数据
Date currentTime = new Date();
//判断最后一条是不是当天的数据,如果不是,把最后一条的时间作为当天的时间
long getTime = response.getT().get(response.getT().size() - 1) * 1000L;
if (!DateUtil.isSameDay(currentTime, new Date(getTime))) {
currentTime = new Date(getTime);
}
int i = 0;
for (Long time : response.getT()) {
time = time * 1000;
if (DateUtil.isSameDay(currentTime, new Date(time))) {
t.add(response.getT().get(i));
o.add(response.getO().get(i));
h.add(response.getH().get(i));
l.add(response.getL().get(i));
c.add(response.getC().get(i));
v.add(response.getV().get(i));
}
i++;
}
response.setT(t);
response.setO(o);
response.setH(h);
response.setL(l);
response.setC(c);
response.setV(v);
}
}
private String buildApiUrl(StockHistoryRequest request) { private String buildApiUrl(StockHistoryRequest request) {
@@ -717,7 +820,9 @@ public class MoneyApiController {
return String.format("%s?symbol=%s&resolution=%s&from=%d&to=%d&countback=%d&currencyCode=%s", return String.format("%s?symbol=%s&resolution=%s&from=%d&to=%d&countback=%d&currencyCode=%s",
EXTERNAL_API_URL, request.getSymbol(), request.getResolution(), request.getFrom(), EXTERNAL_API_URL, request.getSymbol(), request.getResolution(), request.getFrom(),
request.getTo(), request.getCountback(), request.getCurrencyCode()); request.getTo(), request.getCountback(), request.getCurrencyCode());
}; }
;
private static String extractLastSegment(String url) { private static String extractLastSegment(String url) {
@@ -733,28 +838,31 @@ public class MoneyApiController {
public static void main(String[] args) { public static void main(String[] args) {
nseGainer(); // nseGainer();
nseActives(); //// nseActives();
nseTopLoser(); //// nseTopLoser();
////
bseActives(); //// bseActives();
bseGainer(); //// bseGainer();
bseTopLoser(); //// bseTopLoser();
System.out.println(new Date());
System.out.println(new Date(1713949200000L));
System.out.println(DateUtil.isSameDay(new Date(), new Date(1713949200000L)));
} }
private Cache<String, List<MoneyStockSuggestDTO>> gainerStockSuggestCache = CacheBuilder.newBuilder() private Cache<String, List<MoneyStockSuggestDTO>> gainerStockSuggestCache = CacheBuilder.newBuilder()
.maximumSize(100) // 设置缓存的最大大小 .maximumSize(100) // 设置缓存的最大大小
.expireAfterWrite(1, TimeUnit.HOURS) // 设置缓存条目的过期时间 .expireAfterWrite(1, TimeUnit.MINUTES) // 设置缓存条目的过期时间
.build(); .build();
private Cache<String, List<MoneyStockSuggestDTO>> loserStockSuggestCache = CacheBuilder.newBuilder() private Cache<String, List<MoneyStockSuggestDTO>> loserStockSuggestCache = CacheBuilder.newBuilder()
.maximumSize(100) // 设置缓存的最大大小 .maximumSize(100) // 设置缓存的最大大小
.expireAfterWrite(1, TimeUnit.HOURS) // 设置缓存条目的过期时间 .expireAfterWrite(1, TimeUnit.MINUTES) // 设置缓存条目的过期时间
.build(); .build();
private Cache<String, List<MoneyStockSuggestDTO>> activesStockSuggestCache = CacheBuilder.newBuilder() private Cache<String, List<MoneyStockSuggestDTO>> activesStockSuggestCache = CacheBuilder.newBuilder()
.maximumSize(100) // 设置缓存的最大大小 .maximumSize(100) // 设置缓存的最大大小
.expireAfterWrite(30, TimeUnit.MINUTES) // 设置缓存条目的过期时间 .expireAfterWrite(1, TimeUnit.MINUTES) // 设置缓存条目的过期时间
.build(); .build();
} }

View File

@@ -0,0 +1,82 @@
package cn.stock.market.web;
import cn.stock.market.dto.model.StockListVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author gs
* @date 2024/2/15 下午9:18
*/
@Slf4j
@RestController
public class MoneyProxyApiControl {
@GetMapping({"/market/api/proxy/queryStockMoneyProxy","/api/proxy/queryStockMoneyProxy"})
public JSONObject queryStockByMoneyIdAndExchangeType(String scId,String exchangeType){
return stockByMoneyIdAndExchangeTypeFromHttp(scId,exchangeType);
}
public static JSONObject stockByMoneyIdAndExchangeTypeFromHttp(String scId, String exchangeType) {
try {
String url = "https://priceapi.moneycontrol.com/pricefeed/"+exchangeType+"/equitycash/" + scId ;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 解析JSON数据
log.info("stockByCodeAndExchangeType获取 sc_id:{}, exchangeType: {} 的实时价格的结果:{} ",scId,exchangeType,response.toString());
return JSONObject.parseObject(response.toString());
} else {
log.error("HTTP request failed with response code: " + responseCode);
}
} catch (Exception e) {
log.error("stockByMoneyIdAndExchangeTypeFromHttp",e);
}
return new JSONObject();
}
private static StockListVO mapJsonToMoneyStockListVO(JSONObject jsonObject) {
StockListVO stockListVO = new StockListVO();
if (jsonObject != null) {
JSONObject data = jsonObject.getJSONObject("data");
if(data!=null&&!data.isEmpty()){
stockListVO.setName(data.getString("company"));
stockListVO.setCode(data.getString("code"));
stockListVO.setSpell(data.getString("company"));
stockListVO.setGid(data.getString("symbol"));
stockListVO.setNowPrice(data.getString("pricecurrent"));
stockListVO.setOpen_px(data.getString("OPN"));
stockListVO.setPreclose_px(data.getString("priceprevclose"));
stockListVO.setHcrate(new BigDecimal(data.getString("pricepercentchange")));
stockListVO.setSymbol(data.getString("symbol"));
stockListVO.setPricechange(data.getString("pricechange"));
}
}
return stockListVO;
}
}

View File

@@ -18,7 +18,7 @@ import cn.stock.market.domain.basic.service.SiteNewsService;
import cn.stock.market.utils.ServerResponse; import cn.stock.market.utils.ServerResponse;
@Controller @Controller
@RequestMapping({"/api/market/news/", "/api/hq/news/"}) @RequestMapping({"/market/api/market/news/", "/market/api/hq/news/","/api/market/news/", "/api/hq/news/"})
@Api(tags="新闻资讯") @Api(tags="新闻资讯")
public class SiteNewsController { public class SiteNewsController {
private static final Logger log = LoggerFactory.getLogger(SiteNewsController.class); private static final Logger log = LoggerFactory.getLogger(SiteNewsController.class);

View File

@@ -3,6 +3,8 @@ package cn.stock.market.web;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@@ -12,6 +14,7 @@ import cn.qutaojing.common.jpa.ConditionBuilder;
import cn.stock.market.domain.basic.entity.SiteNews; import cn.stock.market.domain.basic.entity.SiteNews;
import cn.stock.market.domain.basic.repository.SiteNewsRepository; import cn.stock.market.domain.basic.repository.SiteNewsRepository;
import cn.stock.market.infrastructure.db.po.QSiteNewsPO; import cn.stock.market.infrastructure.db.po.QSiteNewsPO;
import cn.stock.market.infrastructure.job.InvestingTask;
import cn.stock.market.web.annotations.EncryptFilter; import cn.stock.market.web.annotations.EncryptFilter;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
@@ -56,7 +59,7 @@ import springfox.documentation.annotations.ApiIgnore;
@Controller @Controller
@Api(value = "/StockApiController", tags = "股票行情") @Api(value = "/StockApiController", tags = "股票行情")
@RequestMapping({"/api/market/stock/", "/api/hq/stock/"}) @RequestMapping({"/market/api/market/stock/", "/market/api/hq/stock/","/api/market/stock/", "/api/hq/stock/"})
public class StockApiController { public class StockApiController {
private static final Logger log = LoggerFactory.getLogger(StockApiController.class); private static final Logger log = LoggerFactory.getLogger(StockApiController.class);
@@ -167,6 +170,41 @@ public class StockApiController {
return ServerResponse.createBySuccess(newsRepository.findAll(ConditionBuilder.builder().build(), PageParam.of(pageNum, pageSize), QSiteNewsPO.siteNewsPO.id.desc())); return ServerResponse.createBySuccess(newsRepository.findAll(ConditionBuilder.builder().build(), PageParam.of(pageNum, pageSize), QSiteNewsPO.siteNewsPO.id.desc()));
} }
@RequestMapping({"test.do"})
@ResponseBody
public ServerResponse test(/*@RequestParam("url") String url, @RequestParam("pageNum") Integer pageNum*/) {
String news = stockService.getNews();
List<String> newsList = Arrays.asList(news.split("<a href="));
newsList = newsList.subList(1, newsList.size());
newsList.forEach( n -> {
String contentUrl = n.substring(1, n.indexOf("class=\"img-smllnews\"") - 2);
String id = contentUrl.substring(contentUrl.lastIndexOf("-") + 1, contentUrl.lastIndexOf("_"));
String imgUrl = InvestingTask.extractImgSrc(n);
// String time = n.substring(n.indexOf("Last Updated") + 23, n.indexOf("IST") - 9);
// Extract the date and time using regex
Pattern pattern = Pattern.compile("Updated On :<!-- --> <!-- -->(.*?)<!-- -->");
Matcher matcher = pattern.matcher(n);
String time = "";
if (matcher.find()) {
time = matcher.group(1).trim();
}
SiteNews siteNews = new SiteNews();
siteNews.setAddTime(new Date());
siteNews.setSourceId(id);
siteNews.setDescription(time);
siteNews.setImgurl(imgUrl);
List<String> newsInfo = stockService.getNewsInfo(contentUrl);
siteNews.setContent(newsInfo.get(0));
siteNews.setTitle(newsInfo.get(1));
List<SiteNews> list = newsRepository.findAll(QSiteNewsPO.siteNewsPO.sourceId.eq(id));
if (list.size() == 0) {
newsRepository.save(siteNews);
}
});
return ServerResponse.createBySuccess();
}
//印度股票时线-K线 //印度股票时线-K线
@RequestMapping({"getINDTimeK.do"}) @RequestMapping({"getINDTimeK.do"})
@ApiOperation(value = "印度股票K线", httpMethod = "GET") @ApiOperation(value = "印度股票K线", httpMethod = "GET")
@@ -205,6 +243,25 @@ public class StockApiController {
return this.stockService.getIndiaIndex(); return this.stockService.getIndiaIndex();
} }
@RequestMapping({"getIndiaIndexByToday.do"})
@ApiOperation(value = "印度--获取指定指数信息", httpMethod = "GET")
@ResponseBody
public ServerResponse getIndiaIndexByToday() {
String INDEX_CODE = "TODAY_INDEX";
return RequestCacheUtils.cache("getIndiaIndexByToday.do", INDEX_CODE,6000, (string) -> {
return this.stockService.getIndexByBtoday();
});
}
@RequestMapping({"getIndiaIndexByEttech.do"})
@ApiOperation(value = "印度--获取指定指数信息-Ettech", httpMethod = "GET")
@ResponseBody
public ServerResponse getIndiaIndexByEttech() {
String INDEX_CODE = "TODAY_INDEX";
return RequestCacheUtils.cache("getIndiaIndexByEttech.do", INDEX_CODE, (string) -> {
return this.stockService.getEttechcharts();
});
}
//根据股票id查询 股票指数、大盘指数信息 //根据股票id查询 股票指数、大盘指数信息
@RequestMapping({"getMarketByStockGid.do"}) @RequestMapping({"getMarketByStockGid.do"})
@ApiOperation(value = "根据股票id查询 股票指数、大盘指数信息", httpMethod = "GET") @ApiOperation(value = "根据股票id查询 股票指数、大盘指数信息", httpMethod = "GET")

View File

@@ -2,6 +2,7 @@ package cn.stock.market.web;
import cn.stock.market.infrastructure.api.TodayApis; import cn.stock.market.infrastructure.api.TodayApis;
import cn.stock.market.utils.ServerResponse; import cn.stock.market.utils.ServerResponse;
import cn.stock.market.web.annotations.EncryptFilter;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@@ -11,12 +12,13 @@ import org.springframework.web.bind.annotation.ResponseBody;
@Controller @Controller
@Api(value = "/TodayApiController", tags = "today股票行情") @Api(value = "/TodayApiController", tags = "today股票行情")
@RequestMapping({"/api/market/today/"}) @RequestMapping({"/market/api/market/today/","/api/market/today/"})
public class TodayApiController { public class TodayApiController {
@RequestMapping({"getTopGainers.do"}) @RequestMapping({"getTopGainers.do"})
@ApiOperation(value = "获取Top Gainers",notes = "exchange传nse或者bse", httpMethod = "GET") @ApiOperation(value = "获取Top Gainers",notes = "exchange传nse或者bse", httpMethod = "GET")
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public ServerResponse getTopGainers(@RequestParam("exchange") String exchange) { public ServerResponse getTopGainers(@RequestParam("exchange") String exchange) {
return ServerResponse.createBySuccess(TodayApis.getTopGainers(exchange)); return ServerResponse.createBySuccess(TodayApis.getTopGainers(exchange));
} }
@@ -24,6 +26,7 @@ public class TodayApiController {
@RequestMapping({"getTopLosers.do"}) @RequestMapping({"getTopLosers.do"})
@ApiOperation(value = "获取 Top Losers",notes = "exchange传nse或者bse", httpMethod = "GET") @ApiOperation(value = "获取 Top Losers",notes = "exchange传nse或者bse", httpMethod = "GET")
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public ServerResponse getTopLosers(@RequestParam("exchange") String exchange) { public ServerResponse getTopLosers(@RequestParam("exchange") String exchange) {
return ServerResponse.createBySuccess(TodayApis.getTopLosers(exchange)); return ServerResponse.createBySuccess(TodayApis.getTopLosers(exchange));
} }
@@ -31,6 +34,7 @@ public class TodayApiController {
@RequestMapping({"getMostActiveVolume.do"}) @RequestMapping({"getMostActiveVolume.do"})
@ApiOperation(value = "获取 Most Active Volume",notes = "exchange传nse或者bse", httpMethod = "GET") @ApiOperation(value = "获取 Most Active Volume",notes = "exchange传nse或者bse", httpMethod = "GET")
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public ServerResponse getMostActiveVolume(@RequestParam("exchange") String exchange) { public ServerResponse getMostActiveVolume(@RequestParam("exchange") String exchange) {
return ServerResponse.createBySuccess(TodayApis.getMostActiveVolume(exchange)); return ServerResponse.createBySuccess(TodayApis.getMostActiveVolume(exchange));
} }
@@ -38,6 +42,7 @@ public class TodayApiController {
@RequestMapping({"getMostActiveValue.do"}) @RequestMapping({"getMostActiveValue.do"})
@ApiOperation(value = "获取 Most Active Value",notes = "exchange传nse或者bse",httpMethod = "GET") @ApiOperation(value = "获取 Most Active Value",notes = "exchange传nse或者bse",httpMethod = "GET")
@ResponseBody @ResponseBody
@EncryptFilter(decryptRequest = false)
public ServerResponse getMostActiveValue(@RequestParam("exchange") String exchange) { public ServerResponse getMostActiveValue(@RequestParam("exchange") String exchange) {
return ServerResponse.createBySuccess(TodayApis.getMostActiveValue(exchange)); return ServerResponse.createBySuccess(TodayApis.getMostActiveValue(exchange));
} }

View File

@@ -3,9 +3,9 @@ spring:
show-sql: true show-sql: true
# Redis配置 # Redis配置
redis: redis:
host: 43.132.212.180 host: lb-b6sze686-7db6hgvsx05ef8nz.clb.sg-tencentclb.net
password: ruTZ9J3gaDhknJ password: a5v8b86P4mVzFlUqJV
port: 36379 port: 56379
database: 1 database: 1
lettuce: lettuce:
pool: pool:
@@ -17,9 +17,9 @@ spring:
datasource: datasource:
stock-market: stock-market:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://43.132.212.180:33306/india_stock?useUnicode=true&characterEncoding=utf-8 url: jdbc:mysql://lb-1ju43bvw-p0ecnv4by9ju8six.clb.ap-singapore.tencentclb.com:53306/india_stock?useUnicode=true&characterEncoding=utf-8
username: root username: root
password: 33BsUUcnXRYgwt password: uNejHIFQGJOUtYTmE
maxActive: 500 maxActive: 500
testWhileIdle: true testWhileIdle: true
validationQuery: SELECT 1 validationQuery: SELECT 1

File diff suppressed because one or more lines are too long