1
zj
2024-08-15 171628f9a463f5af3ce55d897fa37b1b80ea4e8b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package project.contract.job;
 
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
 
import kernel.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import kernel.util.Arith;
import kernel.util.ThreadUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ObjectUtils;
import project.contract.ContractLock;
import project.contract.ContractOrder;
import project.contract.ContractOrderService;
import project.contract.ContractRedisKeys;
import project.data.DataService;
import project.data.model.Realtime;
import project.redis.RedisHandler;
import project.syspara.SysparaService;
import project.wallet.AssetService;
import project.wallet.Wallet;
import project.wallet.WalletRedisKeys;
import project.wallet.WalletService;
import project.wallet.consumer.WalletMessage;
 
public class ContractOrderCalculationServiceImpl implements ContractOrderCalculationService, ApplicationContextAware {
    private ApplicationContext applicationContext;
 
    private static final Logger logger = LoggerFactory.getLogger(ContractOrderCalculationServiceImpl.class);
    private ContractOrderService contractOrderService;
    private DataService dataService;
    private WalletService walletService;
//    private RedisHandler redisHandler;
    private AssetService assetService;
    public final static String STATE_SUBMITTED = "submitted";
    public final static String STATE_CREATED = "created";
    /**
     * 平仓线 110%(订金价值 /收益=110%)
     */
    public double order_close_line = 1.1;
    /**
     * 平仓方式 1全仓 2单个持仓
     */
    public int order_close_line_type = 1;
    private SysparaService sysparaService;
 
    public void saveCalculation(String order_no) {
 
        try {
            ContractOrder order = contractOrderService.findByOrderNo(order_no);
            if (order == null || !ContractOrder.STATE_SUBMITTED.equals(order.getState())) {
                /**
                 * 状态已改变,退出处理
                 */
                return;
            }
            List<Realtime> list = this.dataService.realtime(order.getSymbol());
            if (list.size() == 0) {
                return;
            }
            Realtime realtime = list.get(0);
 
            double close = realtime.getClose();
 
            if (ContractOrder.DIRECTION_BUY.equals(order.getDirection())) {
                /*
                 * 0 买涨
                 */
                logger.info("当前价格:"+close+"---------价格:"+Arith.add(order.getTrade_avg_price(), order.getPips()));
                if (close >= Arith.add(order.getTrade_avg_price(), order.getPips())) {
                    settle(order, "profit", close);
                }
 
                if (close <= Arith.sub(order.getTrade_avg_price(), order.getPips())) {
                    settle(order, "loss", close);
                }
 
            } else {
                /*
                 * 1 买跌
                 */
                if (close <= Arith.sub(order.getTrade_avg_price(), order.getPips())) {
                    settle(order, "profit", close);
                }
                if (close >= Arith.add(order.getTrade_avg_price(), order.getPips())) {
                    settle(order, "loss", close);
                }
            }
        } catch (Throwable e) {
            logger.error("OrderCalculationServiceImpll run fail", e);
        }
 
    }
 
    /**
     * 盈亏计算
     *
     * @param profit_loss  profit 盈 loss亏
     * @param currentPrice 当前点位
     */
    public void settle(ContractOrder order, String profit_loss, double currentPrice) {
 
        double mul = Arith.mul(order.getDeposit_open(), order.getLever_rate());//仓位
        double div = Arith.div(mul, order.getTrade_avg_price());//持有币的数量
        double amount = Arith.mul(div, Arith.sub(currentPrice, order.getTrade_avg_price()));
        logger.info("---------盈亏金额:"+amount);
        logger.info("---------盈亏:"+profit_loss);
        RedisHandler redisHandler = getRedisHandler();
        if ("profit".equals(profit_loss)) {
            /**
             * 盈 正数
             */
            order.setProfit(Arith.add(0.0D, Math.abs(amount)));
 
            Object profit = redisHandler.get("MONEY_CONTRACT_PROFIT_" + order.getPartyId().toString());
            if(!ObjectUtils.isEmpty(profit)){
                if(Double.parseDouble(profit.toString()) < 0 ){
 
                    redisHandler.setSync("MONEY_CONTRACT_PROFIT_"+order.getPartyId().toString(), 0);
 
                    Object money = redisHandler.get("PARTY_ID_MONEY_" + order.getPartyId().toString());
                    if(!ObjectUtils.isEmpty(money)){
                        Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId().toString());
                        wallet.setMoney(Double.parseDouble(money.toString()));
                        redisHandler.setSync(WalletRedisKeys.WALLET_PARTY_ID + wallet.getPartyId().toString(), wallet);
                        redisHandler.pushAsyn(WalletRedisKeys.WALLET_QUEUE_UPDATE, new WalletMessage(order.getPartyId().toString(), amount));
                    }
                }
            }
        } else if ("loss".equals(profit_loss)) {
            order.setProfit(Arith.sub(0.0D,Math.abs(amount) ));
 
            //定义一个 总浮动亏损的值
            Double contractAssetsProfit = (Double) redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString());
            double contractProfit = null == contractAssetsProfit ? 0.000D : contractAssetsProfit;
            List<ContractOrder> list = contractOrderService.findSubmitted(order.getPartyId().toString(), null, null);
            double deposit = 0;
            for (int i = 0; i < list.size(); i++) {
                ContractOrder close_line = list.get(i);
                deposit = Arith.add(deposit, close_line.getDeposit());
            }
            double profitt = Arith.add(contractProfit,deposit);
            if(profitt <= 0){
                redisHandler.setSync("MONEY_CONTRACT_PROFIT_"+order.getPartyId().toString(), profitt);
            }else{
                redisHandler.setSync("MONEY_CONTRACT_PROFIT_"+order.getPartyId().toString(), 0);
            }
            //修改余额,每次修改取平仓前余额减去浮动亏损
            Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId().toString());
            Object money = redisHandler.get("PARTY_ID_MONEY_" + order.getPartyId().toString());
            Object profit = redisHandler.get("MONEY_CONTRACT_PROFIT_" + order.getPartyId().toString());
            if(!ObjectUtils.isEmpty(money) && !ObjectUtils.isEmpty(profit)){
                double residueMoney = Arith.add(Double.parseDouble(money.toString()), Double.parseDouble(profit.toString()));
                //如果当前余额减去浮动亏损小于0,将进入强平,这里不再进行余额更新
                if(residueMoney > 0){
                    wallet.setMoney(residueMoney);
                    redisHandler.setSync(WalletRedisKeys.WALLET_PARTY_ID + wallet.getPartyId().toString(), wallet);
                }
            }
        }
 
        double changeRatio;
        changeRatio = Arith.mul(Arith.div(order.getProfit(), order.getDeposit_open()), 100);
        DecimalFormat df = new DecimalFormat("#.##");
        order.setChange_ratio(Double.valueOf(df.format(changeRatio)));
 
        /**
         * 多次平仓价格不对,后续修
         */
        order.setClose_avg_price(currentPrice);
        this.contractOrderService.update(order);
        /**
         * 止盈价
         */
        Double profit_stop = order.getStop_price_profit();
        if (profit_stop != null && profit_stop > 0 && ContractOrder.DIRECTION_BUY.equals(order.getDirection())) {
            /*
             * 买涨
             */
            if (currentPrice >= profit_stop) {
                this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
                return;
            }
        } else if (profit_stop != null && profit_stop > 0
                && ContractOrder.DIRECTION_SELL.equals(order.getDirection())) {
            /**
             * 买跌
             */
            if (currentPrice <= profit_stop) {
                this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
                return;
            }
        }
 
        /**
         * 止亏线
         */
        Double loss_stop = order.getStop_price_loss();
 
        if (loss_stop != null && loss_stop > 0 && ContractOrder.DIRECTION_BUY.equals(order.getDirection())) {
            /*
             * 买涨
             */
            if (currentPrice <= loss_stop) {
                this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
                return;
 
            }
        } else if (loss_stop != null && loss_stop > 0 && ContractOrder.DIRECTION_SELL.equals(order.getDirection())) {
            /**
             * 买跌
             */
 
            if (currentPrice >= loss_stop) {
                this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
                return;
            }
        }
        logger.info("order_close_line_type:"+order_close_line_type);
        if (order_close_line_type == 1) {
            /**
             * 收益
             */
            double profit = 0;
 
            List<ContractOrder> list = contractOrderService.findSubmitted(order.getPartyId().toString(), null, null);
            for (int i = 0; i < list.size(); i++) {
                ContractOrder close_line = list.get(i);
                profit = Arith.add(profit, Arith.add(close_line.getProfit(), close_line.getDeposit()));
            }
            Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId().toString());
            Object money = redisHandler.get("PARTY_ID_MONEY_" + order.getPartyId().toString());
            double totleMoney = 0;
            if(ObjectUtils.isEmpty(money)){
                totleMoney = wallet.getMoney();
            }else{
                totleMoney = Double.parseDouble(money.toString());
            }
            if (Arith.add(profit,totleMoney) <= 0) {
                redisHandler.setSync("MONEY_CONTRACT_PROFIT_"+order.getPartyId().toString(), 0);
                /**
                 * 触发全仓强平
                 */
                this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
                ThreadUtils.sleep(100);
                for (int i = 0; i < list.size(); i++) {
                    ContractOrder close_line = list.get(i);
                    if (!order.getOrder_no().equals(close_line.getOrder_no())) {
                        try {
 
                            while (true) {
                                if (ContractLock.add(close_line.getOrder_no())) {
                                    this.contractOrderService.saveClose(close_line.getPartyId().toString(),
                                            close_line.getOrder_no());
                                    /**
                                     * 处理完退出
                                     */
                                    break;
                                }
                                ThreadUtils.sleep(500);
 
                            }
 
                        } catch (Exception e) {
                            logger.error("error:", e);
                        } finally {
                            ContractLock.remove(close_line.getOrder_no());
                            ThreadUtils.sleep(100);
                        }
 
                    }
                }
 
            }
        } else {
            logger.info("---------进入单个持仓----------------");
            logger.info("---------order.getProfit()----------------"+order.getProfit());
            logger.info("---------order.getDeposit()----------------"+order.getDeposit());
            logger.info("---------order_close_line----------------"+order_close_line);
            if (order.getProfit() < 0 && (Arith.div(order.getDeposit(), Math.abs(order.getProfit())) <= Arith
                    .div(order_close_line, 100))) {
                logger.info("---------进入强平了----------------");
                /**
                 * 低于系统默认平仓线,进行强平
                 */
                this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
                return;
            }
        }
 
    }
    public void setDataService(DataService dataService) {
        this.dataService = dataService;
    }
 
    public void setSysparaService(SysparaService sysparaService) {
        this.sysparaService = sysparaService;
    }
 
    public void setContractOrderService(ContractOrderService contractOrderService) {
        this.contractOrderService = contractOrderService;
    }
 
    public void setWalletService(WalletService walletService) {
        this.walletService = walletService;
    }
 
    public void setOrder_close_line(double order_close_line) {
        this.order_close_line = order_close_line;
    }
 
    public void setOrder_close_line_type(int order_close_line_type) {
        this.order_close_line_type = order_close_line_type;
    }
 
    public RedisHandler getRedisHandler() {
        return applicationContext.getBean(RedisHandler.class);
    }
 
 
    public void setAssetService(AssetService assetService) {
        this.assetService = assetService;
    }
 
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
 
}