每天晚上在支付宝里看当天基金亏损,但是支付宝更新较晚而且当天看不到总亏损。韭菜等不及,当天就想知道自己亏了多少。网上一搜发现天天基金提供了相关接口,而且是实时的估值。就实现了查自己持仓实时盈亏的接口和网页。
逻辑和大致思路如下:
1.数据库存储 基金的代码、名称、份额。如果多个人共用,可以加个用户名。录入好信息
2. 请求 /fundUser/{userName}/today 接口时,根据user_name查出该用户所有数据,用基金代码调用天天基金的接口,获取实时的估值
String url = "http://fundgz.1234567.com.cn/js/" + 基金代码 + ".js";
JSONObject jijin = this.doGetstr(url);
返回报文大概这样
jsonpgz({"fundcode":"001186","name":"富国文体健康股票A","jzrq":"2021-12-21","dwjz":"2.4560","gsz":"2.4716","gszzl":"0.63","gztime":"2021-12-22 10:14"});
jzrq 基金开始日期
dwjz 净值
gsz 估算净值
gszzl 估算涨跌幅
gztime 时间
3. 当日该基金盈亏 = 该基金份额 *(实时估算净值-净值) 循环累加一下
4. 返回重定向到前台页面,粗糙的展现一下。涨红跌绿美化一下
以下为源码部分
数据库
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for fund_user
-- ----------------------------
DROP TABLE IF EXISTS `fund_user`;
CREATE TABLE `fund_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`fund_code` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`fund_name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`fund_quantity` decimal(20,6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
依赖
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
java代码
import FundUser;
import FundUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
/**
* (FundUser)表控制层
*
* @author EasyCode
* @since 2021-11-15 17:06:19
*/
@Slf4j
@Controller
@RequestMapping("/fundUser/{userName}")
public class FundUserController {
/**
* 服务对象
*/
@Autowired
private FundUserService fundUserService;
/**
* @Author
* @Date 18:41 2021/11/18
* @Description 用户退出
*/
@CrossOrigin //跨域的设置
@RequestMapping("/today")
public String setStatus(@PathVariable("userName") String userName,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<FundUser> fundUsers = fundUserService.queryByUserName(userName);
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
String notShowName = "";
String ShowName = "";
double money = 0;
LocalDateTime dateTime = LocalDateTime.now();
log.info("dateTime.getHour()" + dateTime.getHour());
dateTime = dateTime.minus(1, ChronoUnit.DAYS);
String today = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
DecimalFormat df = new DecimalFormat("0.0");
String gztime = "";
for (int i = 0; i < fundUsers.size(); i++) {
String url = "http://fundgz.1234567.com.cn/js/" + fundUsers.get(i).getFundCode() + ".js";
JSONObject jijin = this.doGetstr(url);
String jzrq = jijin.getString("jzrq");
double dwjz = Double.parseDouble(jijin.getString("dwjz"));
double gsz = Double.parseDouble(jijin.getString("gsz"));
String gszzl = jijin.getString("gszzl");
gztime = jijin.getString("gztime");
String fundName = jijin.getString("name");
String fundcode = jijin.getString("fundcode");
double change = fundUsers.get(i).getFundQuantity() * (gsz - dwjz);
money = money + change;
ShowName = ShowName + URLEncoder.encode(fundName, "UTF-8") + " " + df.format(change) + " " + gszzl + " " + fundcode + ";";
}
String returnUrl = "redirect:http://www/index.html?money=" + df.format(money) + "&ShowName=" + ShowName + "&time=" + gztime;
return returnUrl;
}
public JSONObject doGetstr(String url) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
CloseableHttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(response.getEntity(), "utf-8");
result = result.replace("jsonpgz(", "").replace(");", "");
log.info("doGet result:" + result);
jsonObject = JSONObject.fromObject(result);
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
}
前端代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> </title>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
</head>
<body>
<h1 id="money"></h1>
<h3 id="time"></h3>
<ol>
</ol>
<script src="js/jquery-3.3.1.min.js"></script>
</body>
</html>
<script type="text/javascript">
money = getQueryString('money');
ShowName = getQueryString('ShowName');
time = getQueryString('time');
$("#money").text(money);
$("#ShowName").text(ShowName);
$("#time").text("更新时间"+time);
var ShowNamestrArry = ShowName.split(";");
for(var i =0 ;i<ShowNamestrArry.length;i++)
{
if(ShowNamestrArry[i] != null && ShowNamestrArry[i].length > 0) //去掉空的
if(ShowNamestrArry[i].split(" ")[1]>0)
{
$("ol").prepend("<li><font color='#DC143C'>"+ShowNamestrArry[i].split(" ")[2]+"%</font> <a href='https://h5.1234567.com.cn/app/fund-details/?fCode="+ShowNamestrArry[i].split(" ")[3] + "'>"+ShowNamestrArry[i].split(" ")[0]+"</a> <font color='#DC143C'>"+ShowNamestrArry[i].split(" ")[1]+"</font> </li>");
}else{
$("ol").prepend("<li><font color='#008000'>"+ShowNamestrArry[i].split(" ")[2]+"%</font> <a href='https://h5.1234567.com.cn/app/fund-details/?fCode="+ShowNamestrArry[i].split(" ")[3] + "'>"+ShowNamestrArry[i].split(" ")[0]+"</a> <font color='#008000'>"+ShowNamestrArry[i].split(" ")[1]+"</font> </li>");
}
}
/*
* 获取URL参数
*/
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]); return null;
}
</script>