1
zj
2024-05-09 ddc52ca9c8a7597b410be4e802e598844bdc5d4a
src/main/java/com/nq/utils/task/stock/StockTask.java
@@ -1,13 +1,23 @@
package com.nq.utils.task.stock;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.gson.Gson;
import com.nq.common.ServerResponse;
import com.nq.dao.*;
import com.nq.enums.EStockType;
import com.nq.pojo.*;
import com.nq.service.IMandatoryLiquidationService;
import com.nq.service.IStockService;
import com.nq.utils.HttpClientRequest;
import com.nq.service.IUserAssetsServices;
import com.nq.service.IUserPositionService;
import com.nq.utils.http.HttpClientRequest;
import com.nq.utils.redis.RedisKeyUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.stock.BuyAndSellUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -19,6 +29,9 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
@Component
@@ -28,47 +41,59 @@
    @Autowired
    StockMapper stockMapper;
    @Autowired
    IUserPositionService userPositionService;
    @Autowired
    UserPositionMapper userPositionMapper;
    @Autowired
    IMandatoryLiquidationService mandatoryLiquidationService;
    @Autowired
    UserStockSubscribeMapper userStockSubscribeMapper;
    @Autowired
    StockSubscribeMapper stockSubscribeMapper;
    @Autowired
    IUserPositionService iUserPositionService;
    @Autowired
    IUserAssetsServices userAssetsServices;
    private final Lock ballotLock = new ReentrantLock();
    private final Lock subscriptionLock = new ReentrantLock();
    private final Lock stockConstraintLock = new ReentrantLock();
    private static final Logger log = LoggerFactory.getLogger(StockTask.class);
    public void time(boolean am, boolean pm) {
        am = false;
        pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
    }
    //每隔一个小时请求一次 同步印度股票
    @Scheduled(cron = "0 0 0/1 * * ?")
    /**
     * 同步系统所需要的股票
     * */
    @Scheduled(cron = "0 0 0/2  * * ?")
    public void syncINStockData() {
        loadAllStock(EStockType.IN);
//        loadAllStock(EStockType.HK);
    }
    /**
     * 同步美国股票
     * */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public  void synsUSStockData(){
        loadAllStock(EStockType.US);
    }
    /**
     * 同步美国股票
     * */
    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0 0/30 * * * ?")
    public  void loadStockCompanies(){
        loadAllCompanies();
    }
@@ -80,8 +105,7 @@
        for (int i = 0; i <list.size() ; i++) {
            Stock stock = list.get(i);
            EStockType eStockType = EStockType.getEStockTypeByCode(stock.getStockType());
            String result = HttpClientRequest.doGet(eStockType.stockUrl+"companies?pid=+"+stock.getStockCode()+"+country_id="+eStockType.getContryId()+"&size=1000&page=1&key="+eStockType.stockKey);
            log.info(" 公司信息返回{}",result);
            String result = HttpClientRequest.doGet(eStockType.stockUrl+"companies?pid=+"+stock.getStockCode()+"+country_id="+eStockType.getContryId()+"&size=1&page=1&key="+eStockType.stockKey);
            try {
                JSONObject jsonObject = JSONObject.parseObject(result);
                JSONObject companiesInfo = jsonObject.getJSONArray("data").getJSONObject(0);
@@ -93,9 +117,6 @@
        }
    }
    /**
     * 加载所有股票数据
@@ -109,7 +130,6 @@
            while (totleStock>list.size()){
                try{
                    String result = HttpClientRequest.doGet(eStockType.stockUrl+"list?country_id="+eStockType.getContryId()+"&size=1000&page="+page+"&key="+eStockType.stockKey);
                    ReponseBase reponseBase  = new Gson().fromJson(result,ReponseBase.class);
                    list.addAll(reponseBase.getData());
                    page++;
@@ -131,17 +151,27 @@
                    }else{
                        stock.setStockGid(o.getType());
                    }
                    if(eStockType.getCode().equals("US")){
                        stock.setStockSpell(o.getSymbol());
                    }else{
                        stock.setStockSpell(o.getTicker());
                    }
                    stock.setStockSpell(o.getSymbol());
                    stock.setIsLock(0);
                    stock.setIsShow(0);
                    stock.setDataBase(0);
                    stock.setAddTime(new Date());
                    stockMapper.insert1(stock);
                }else{
                    stock.setStockCode(o.getId());
                    stock.setStockName(o.getName());
                    stock.setStockType(eStockType.getCode());
                    if(o.getType() == null){
                        stock.setStockGid(eStockType.getCode());
                    }else{
                        stock.setStockGid(o.getType());
                    }
                    stock.setStockSpell(o.getSymbol());
                    stock.setIsLock(0);
                    stock.setIsShow(0);
                    stock.setDataBase(0);
                    stock.setAddTime(new Date());
                    stockMapper.updateById(stock);
                }
                RedisKeyUtil.setCaCheKeyBaseStock(eStockType,o);
            }
@@ -152,27 +182,86 @@
        }
    }
    /***
     * 每3分钟同步一次数据源到数据库
     *
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public  void  sysnInstockData(){
        List<Stock>  list =   stockMapper.findStockList();
        if(list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                try {
                    Stock stock = list.get(i);
                    StockRealTimeBean stockDetailBean = RedisKeyUtil.getCacheRealTimeStock(stock);
                    stock.setIncreaseRatio(new BigDecimal(stockDetailBean.getPcp().replace("%","")));
                    stockMapper.updateById(stock);
                }catch (Exception e){
    @Scheduled(cron = "0 0/10 * * * ?")
    public void ballot() {
        if (ballotLock.tryLock()) {
            try {
                log.info("新股上市转持仓定时任务--------->开始");
                List<StockSubscribe> stockSubscribes = stockSubscribeMapper.selectList(new LambdaQueryWrapper<StockSubscribe>()
                        .lt(StockSubscribe::getListDate, DateUtil.date()));
                if (CollectionUtils.isNotEmpty(stockSubscribes)) {
                    List<String> codeList = stockSubscribes.stream().map(StockSubscribe::getCode).collect(Collectors.toList());
                    List<UserStockSubscribe> userStockSubscribes = userStockSubscribeMapper.selectList(new LambdaQueryWrapper<UserStockSubscribe>()
                            .eq(UserStockSubscribe::getStatus, 4).in(UserStockSubscribe::getNewCode, codeList));
                    //订单转持仓
                    userStockSubscribes.forEach(f -> {
                        ServerResponse serverResponse = iUserPositionService.newStockToPosition(f.getId());//转持仓
                        if(serverResponse.isSuccess()){
                            f.setStatus(5);
                            userStockSubscribeMapper.updateById(f);
                        }else{
                            log.info("新股上市转持仓失败申购订单id:"+f.getId()+",失败原因:"+serverResponse.getMsg());
                        }
                    });
                }
                log.info("新股上市转持仓定时任务--------->结束");
            } catch (Exception e) {
                log.error("新股上市转持仓定时任务发生异常", e);
            } finally {
                ballotLock.unlock();
            }
        } else {
            log.info("新股上市转持仓定时任务--------->上次任务还未执行完成,本次任务忽略");
        }
    }
//    @Scheduled(cron = "0/5 * * * * ?")
//    public void subscription() {
//        if (subscriptionLock.tryLock()) {
//            try {
//                log.info("自动转已认缴--------->开始");
//                List<UserStockSubscribe> userStockSubscribes = userStockSubscribeMapper.selectList(new LambdaQueryWrapper<UserStockSubscribe>()
//                        .eq(UserStockSubscribe::getStatus, 3));
//                userStockSubscribes.forEach(f->{
//                    Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, f.getNewCode()));
//                    UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId(stock.getStockType(),f.getUserId());
//                    if(null != userAssets && userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) == 0){
//                        f.setStatus(4);
//                        userStockSubscribeMapper.updateById(f);
//                    }
//                });
//                log.info("自动转已认缴--------->结束");
//            } catch (Exception e) {
//                log.error("自动转已认缴定时任务发生异常", e);
//            } finally {
//                subscriptionLock.unlock();
//            }
//        } else {
//            log.info("自动转已认缴定时任务--------->上次任务还未执行完成,本次任务忽略");
//        }
//    }
    /**
     * 强制平仓
     */
    @Scheduled(cron = "0/1 * * * * ?")
    public void stockConstraint(){
        if (stockConstraintLock.tryLock()) {
            log.info("强制平仓任务:--------->开始");
            try {
                List<UserPosition> userPositions = userPositionMapper.selectList(new LambdaQueryWrapper<UserPosition>().isNull(UserPosition::getSellOrderId));
                if(CollectionUtils.isNotEmpty(userPositions)){
                    userPositionService.stockConstraint(userPositions);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("强制平仓任务错误:" + e.getMessage());
            } finally {
                stockConstraintLock.unlock();
                log.info("强制平仓任务:--------->结束");
            }
        } else {
            log.info("强制平仓任务--------->上次任务还未执行完成,本次任务忽略");
        }
    }
}