From 604341da0cfe8f40cdf549fe9ad145f0d443a718 Mon Sep 17 00:00:00 2001
From: zj <1772600164@qq.com>
Date: Tue, 27 Aug 2024 22:38:06 +0800
Subject: [PATCH] Merge remote-tracking branch 'origin/jys7-15' into jys7-15
---
src/main/java/project/contract/internal/AdminContractOrderServiceImpl.java | 4
.idea/inspectionProfiles/Project_Default.xml | 43 +++
src/main/java/project/futures/internal/AdminFuturesOrderServiceImpl.java | 2
src/main/java/project/project/web/api/ContractOrderController.java | 52 ++++
src/main/java/project/contract/internal/ContractOrderServiceImpl.java | 226 ++++++++++++++----
src/main/java/project/web/api/UserController.java | 50 ++--
src/main/java/project/wallet/internal/WalletGatherServiceImpl.java | 39 ++-
src/main/resources/spring/applicationContext-email.xml | 2
src/main/java/project/project/web/admin/AdminContractOrderController.java | 143 +++++++++--
src/main/java/project/contract/job/ContractOrderCalculationServiceImpl.java | 94 +++++++
src/main/java/project/wallet/internal/WalletServiceImpl.java | 8
11 files changed, 534 insertions(+), 129 deletions(-)
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
index cc50e6b..56d11c3 100644
--- a/.idea/inspectionProfiles/Project_Default.xml
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -1,17 +1,60 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
+ <inspection_tool class="AliAccessStaticViaInstance" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAbstractClassShouldStartWithAbstractNaming" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAbstractMethodOrInterfaceMethodMustUseJavadoc" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidApacheBeanUtilsCopy" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidCallStaticSimpleDateFormat" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidCommentBehindStatement" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidComplexCondition" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidConcurrentCompetitionRandom" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidDoubleOrFloatEqualCompare" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidManuallyCreateThread" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidMissUseOfMathRandom" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidNegationOperator" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidNewDateGetTime" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidPatternCompileInMethod" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidReturnInFinally" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaAvoidStartWithDollarAndUnderLineNaming" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaAvoidUseTimer" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaBigDecimalAvoidDoubleConstructor" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaBooleanPropertyShouldNotStartWithIs" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaClassCastExceptionWithSubListToArrayList" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaClassCastExceptionWithToArray" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaClassMustHaveAuthor" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaClassNamingShouldBeCamel" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaCollectionInitShouldAssignCapacity" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaCommentsMustBeJavadocFormat" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaConcurrentExceptionWithModifyOriginSubList" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaConstantFieldShouldBeUpperCase" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaCountDownShouldInFinally" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaDontModifyInForeachCircle" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaEnumConstantsMustHaveComment" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaExceptionClassShouldEndWithException" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaIbatisMethodQueryForList" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaLockShouldWithTryFinally" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaLowerCamelCaseVariableNaming" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaMethodReturnWrapperType" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaMethodTooLong" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaPackageNaming" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaPojoMustOverrideToString" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaPojoMustUsePrimitiveField" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaPojoNoDefaultValue" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaRemoveCommentedCode" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaServiceOrDaoClassShouldEndWithImpl" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaSneakyThrowsWithoutExceptionType" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaStringConcat" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaSwitchExpression" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaSwitchStatement" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaTestClassShouldEndWithTestNaming" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaThreadLocalShouldRemove" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaThreadPoolCreation" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaThreadShouldSetName" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaTransactionMustHaveRollback" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaUndefineMagicConstant" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaUnsupportedExceptionWithModifyAsList" enabled="true" level="WARNING" enabled_by_default="true" />
+ <inspection_tool class="AlibabaUseQuietReferenceNotation" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="AlibabaUseRightCaseForDateFormat" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
diff --git a/src/main/java/project/contract/internal/AdminContractOrderServiceImpl.java b/src/main/java/project/contract/internal/AdminContractOrderServiceImpl.java
index 2362b60..d596320 100644
--- a/src/main/java/project/contract/internal/AdminContractOrderServiceImpl.java
+++ b/src/main/java/project/contract/internal/AdminContractOrderServiceImpl.java
@@ -18,13 +18,13 @@
StringBuffer queryString = new StringBuffer(
"SELECT orders.UUID id,orders.SYMBOL symbol,orders.AMOUNT_CLOSE amount_close,orders.CLOSE_AVG_PRICE close_avg_price,"
+ "orders.STOP_PRICE_PROFIT stop_price_profit,orders.STOP_PRICE_LOSS stop_price_loss,"
- + "orders.ORDER_NO order_no,orders.TRADE_AVG_PRICE trade_avg_price,"
+ + "orders.ORDER_NO order_no,orders.PARTY_ID party_id,orders.TRADE_AVG_PRICE trade_avg_price,"
+ "orders.DIRECTION direction,orders.UNIT_AMOUNT unit_amount,"
+ "orders.STATE state,orders.FEE fee,orders.PROFIT profit,orders.CREATE_TIME createTime,"
+ "orders.DEPOSIT deposit,orders.DEPOSIT_OPEN deposit_open,orders.CLOSE_TIME closeTime,"
+ "orders.VOLUME_OPEN volume_open,orders.VOLUME volume,orders.LEVER_RATE as lever_rate,item.NAME itemname,");
queryString.append(" wallet.MONEY money, ");
- queryString.append(" party.USERNAME username,party.USERCODE usercode,party.ROLENAME rolename ");
+ queryString.append(" party.USERNAME username,party.USERCODE usercode,party.ROLENAME rolename,party.REMARKS remarks ");
queryString.append(
" FROM T_CONTRACT_ORDER orders LEFT JOIN PAT_PARTY party ON orders.PARTY_ID = party.UUID LEFT JOIN T_WALLET wallet ON wallet.PARTY_ID = party.UUID LEFT JOIN T_ITEM item ON orders.SYMBOL=item.SYMBOL WHERE 1 = 1 ");
diff --git a/src/main/java/project/contract/internal/ContractOrderServiceImpl.java b/src/main/java/project/contract/internal/ContractOrderServiceImpl.java
index a7330c2..6e52861 100644
--- a/src/main/java/project/contract/internal/ContractOrderServiceImpl.java
+++ b/src/main/java/project/contract/internal/ContractOrderServiceImpl.java
@@ -7,13 +7,14 @@
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.ObjectUtils;
import kernel.util.Arith;
import kernel.util.DateUtils;
import kernel.util.StringUtils;
import kernel.web.ApplicationUtil;
import kernel.web.Page;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.ObjectUtils;
import project.Constants;
import project.contract.ContractApplyOrder;
import project.contract.ContractApplyOrderService;
@@ -75,25 +76,25 @@
ApplicationUtil.executeInsert(order);
redisHandler.setSync(ContractRedisKeys.CONTRACT_ORDERNO + order.getOrder_no(), order);
-
+
Map<String, ContractOrder> map = (Map<String, ContractOrder>) redisHandler.get(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId().toString());
if (map == null) map = new ConcurrentHashMap<String, ContractOrder>();
map.put(order.getOrder_no(), order);
redisHandler.setSync(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId().toString(), map);
// 获取单个订单的合约总资产、总保证金、总未实现盈利
Map<String, Double> contractAssetsOrder = this.assetService.getMoneyContractByOrder(order);
-
+
Double contractAssets = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString());
Double contractAssetsDeposit = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString());
Double contractAssetsProfit = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString());
-
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
+
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
Arith.add(null == contractAssets ? 0.000D : contractAssets, contractAssetsOrder.get("money_contract")));
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
- Arith.add(null == contractAssetsDeposit ? 0.000D : contractAssetsDeposit, contractAssetsOrder.get("money_contract_deposit")));
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
+ Arith.add(null == contractAssetsDeposit ? 0.000D : contractAssetsDeposit, contractAssetsOrder.get("money_contract_deposit")));
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
Arith.add(null == contractAssetsProfit ? 0.000D : contractAssetsProfit, contractAssetsOrder.get("money_contract_profit")));
-
+
/**
* 进入市场
*/
@@ -101,7 +102,7 @@
applyOrder.setState(ContractApplyOrder.STATE_CREATED);
this.contractApplyOrderService.update(applyOrder);
-
+
Party party = this.partyService.cachePartyBy(order.getPartyId(), false);
if (Constants.SECURITY_ROLE_MEMBER.equals(party.getRolename())) {
tipService.saveTip(order.getId().toString(), TipConstants.CONTRACT_ORDER);
@@ -128,8 +129,19 @@
double profit = this.settle(order, volume);
update(order);
// if (profit > 0) {
+
Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId());
double amount_before = wallet.getMoney();
+ Object money = redisHandler.get("PARTY_ID_MONEY_" + order.getPartyId().toString());
+ if(ObjectUtils.isEmpty(money)){
+ wallet.setMoney(wallet.getMoney());
+ }else{
+ wallet.setMoney(Double.parseDouble(money.toString()));
+ }
+
+ if (Arith.add(wallet.getMoney(), profit) < 0) {
+ profit = Arith.sub(0, wallet.getMoney());
+ }
// wallet.setMoney(Arith.add(wallet.getMoney(), profit));/
if (Arith.add(wallet.getMoney(), profit) < 0) {
@@ -163,7 +175,7 @@
/**
* 根据用户批量赎回订单
- *
+ *
* @param partyId
*/
public void saveCloseRemoveAllByPartyId(String partyId) {
@@ -175,9 +187,9 @@
saveClose(order.getPartyId().toString(), order.getOrder_no());
}
redisHandler.remove(ContractRedisKeys.CONTRACT_ORDERNO + order.getOrder_no());
- }
+ }
redisHandler.remove(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + partyId);
-
+
this.redisHandler.remove(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + partyId);
this.redisHandler.remove(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + partyId);
this.redisHandler.remove(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + partyId);
@@ -192,7 +204,7 @@
if (order == null || !ContractOrder.STATE_SUBMITTED.equals(order.getState()) || !partyId.equals(order.getPartyId().toString()) || order.getVolume() <= 0) {
return null; //状态已改变,退出处理
}
-
+
/**
* 收益
*/
@@ -201,7 +213,12 @@
Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId());
double amount_before = wallet.getMoney();
-
+ Object money = redisHandler.get("PARTY_ID_MONEY_" + order.getPartyId().toString());
+ if(ObjectUtils.isEmpty(money)){
+ wallet.setMoney(wallet.getMoney());
+ }else{
+ wallet.setMoney(Double.parseDouble(money.toString()));
+ }
if (Arith.add(wallet.getMoney(), profit) < 0) {
profit = Arith.sub(0, wallet.getMoney());
@@ -244,30 +261,30 @@
String id = null == order.getId() ? ApplicationUtil.getCurrentTimeUUID() : order.getId().toString();
ApplicationUtil.executeInsertOrUpdate(order, "WHERE UUID=?", new Object[] {id});
redisHandler.setSync(ContractRedisKeys.CONTRACT_ORDERNO + order.getOrder_no(), order);
-
+
if (ContractOrder.STATE_SUBMITTED.equals(order.getState())) {
Map<String, ContractOrder> map = (Map<String, ContractOrder>) redisHandler.get(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId().toString());
if (null == map) map = new ConcurrentHashMap<String, ContractOrder>();
ContractOrder orderOld = map.get(order.getOrder_no());
-
+
map.put(order.getOrder_no(), order);
redisHandler.setSync(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId().toString(), map);
-
+
// 获取单个订单的合约总资产、总保证金、总未实现盈利
Map<String, Double> contractAssetsOrder = this.assetService.getMoneyContractByOrder(order);
Map<String, Double> contractAssetsOrderOld = this.assetService.getMoneyContractByOrder(orderOld);
-
+
Double contractAssets = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString());
Double contractAssetsDeposit = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString());
Double contractAssetsProfit = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString());
-
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
+
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
Arith.add(null == contractAssets ? 0.000D : contractAssets, contractAssetsOrder.get("money_contract") - contractAssetsOrderOld.get("money_contract")));
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
- Arith.add(null == contractAssetsDeposit ? 0.000D : contractAssetsDeposit, contractAssetsOrder.get("money_contract_deposit") - contractAssetsOrderOld.get("money_contract_deposit")));
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
+ Arith.add(null == contractAssetsDeposit ? 0.000D : contractAssetsDeposit, contractAssetsOrder.get("money_contract_deposit") - contractAssetsOrderOld.get("money_contract_deposit")));
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
Arith.add(null == contractAssetsProfit ? 0.000D : contractAssetsProfit, contractAssetsOrder.get("money_contract_profit") - contractAssetsOrderOld.get("money_contract_profit")));
-
+
} else if (ContractOrder.STATE_CREATED.equals(order.getState())) { // 平仓后,移除持仓列表
Map<String, ContractOrder> map = (Map<String, ContractOrder>) redisHandler.get(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId().toString());
ContractOrder orderOld = null;
@@ -276,21 +293,21 @@
map.remove(order.getOrder_no());
}
redisHandler.setSync(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId().toString(), map);
-
+
// 获取单个订单的合约总资产、总保证金、总未实现盈利
Map<String, Double> contractAssetsOrderOld = this.assetService.getMoneyContractByOrder(orderOld);
-
+
Double contractAssets = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString());
Double contractAssetsDeposit = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString());
Double contractAssetsProfit = (Double) this.redisHandler.get(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString());
-
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
+
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
Arith.add(null == contractAssets ? 0.000D : contractAssets, 0.000D - contractAssetsOrderOld.get("money_contract")));
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
- Arith.add(null == contractAssetsDeposit ? 0.000D : contractAssetsDeposit, 0.000D - contractAssetsOrderOld.get("money_contract_deposit")));
- this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
+ Arith.add(null == contractAssetsDeposit ? 0.000D : contractAssetsDeposit, 0.000D - contractAssetsOrderOld.get("money_contract_deposit")));
+ this.redisHandler.setSync(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
Arith.add(null == contractAssetsProfit ? 0.000D : contractAssetsProfit, 0.000D - contractAssetsOrderOld.get("money_contract_profit")));
-
+
// 平仓则纪录数据(委托平仓,订单直接平仓)
this.userDataService.saveClose(order);
Party party = this.partyService.cachePartyBy(order.getPartyId(), false);
@@ -302,7 +319,7 @@
/**
* 收益结算,平仓时计算
- *
+ *
* @param closevolume 平仓的张数
*/
public double settle(ContractOrder order, double volume) {
@@ -312,7 +329,11 @@
*/
double rate = Arith.div(volume, order.getVolume_open());
- //profit = Arith.mul(Arith.add(order.getDeposit(), order.getProfit()), rate);
+ //平仓收益
+ 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(order.getClose_avg_price(), order.getTrade_avg_price()));
+
profit = Arith.add(Arith.mul(order.getDeposit_open(),rate),Arith.mul(order.getProfit(),rate));
order.setAmount_close(Arith.add(order.getAmount_close(), profit));
order.setVolume(Arith.sub(order.getVolume(), volume));
@@ -330,7 +351,7 @@
public ContractOrder findByOrderNo(String order_no) {
ContractOrder order = (ContractOrder) this.redisHandler.get(ContractRedisKeys.CONTRACT_ORDERNO + order_no);
if (null != order) return order;
-
+
List<ContractOrder> list = ApplicationUtil.executeSelect(ContractOrder.class,"WHERE ORDER_NO=?",new Object[] {order_no});
return list.size()<=0?null:list.get(0);
}
@@ -355,11 +376,11 @@
}
return list;
}
-
+
Page page = new Page(1,Integer.MAX_VALUE,Integer.MAX_VALUE);
StringBuilder whereSql=new StringBuilder("WHERE 1=1 ");
ArrayList<Object> params=new ArrayList<Object>();
-
+
if (!StringUtils.isNullOrEmpty(partyId)) {
whereSql.append("AND PARTY_ID=? ");
params.add(partyId);
@@ -369,7 +390,7 @@
whereSql.append("AND SYMBOL=? ");
params.add(symbol);
}
-
+
if (!StringUtils.isNullOrEmpty(direction)) {
whereSql.append("AND DIRECTION=? ");
params.add(direction);
@@ -379,18 +400,18 @@
params.add("submitted");
params.add(page.getFirstElementNumber());
params.add(page.getPageSize());
-
+
return ApplicationUtil.executeSelect(ContractOrder.class,whereSql.toString(),params.toArray(new Object[params.size()]));
}
public List<Map<String, Object>> getPaged(int pageNo, int pageSize, String partyId, String symbol, String type,String startTime, String endTime) {
if (pageNo <= 0) pageNo = 1;
Page page = new Page(pageNo, pageSize, Integer.MAX_VALUE);
-
+
StringBuilder whereSql=new StringBuilder("WHERE PARTY_ID=? ");
ArrayList<Object> params=new ArrayList<Object>();
params.add(partyId);
-
+
if (!StringUtils.isNullOrEmpty(symbol)) {
whereSql.append("AND SYMBOL=? ");
params.add(symbol);
@@ -403,19 +424,19 @@
whereSql.append("AND STATE=? ");
params.add("created");
}
-
+
if (!StringUtils.isNullOrEmpty(startTime)) {
whereSql.append("AND DATE(CREATE_TIME)>=DATE('"+startTime+" 00:00:00') ");
}
-
+
if (!StringUtils.isNullOrEmpty(endTime)) {
whereSql.append("AND DATE(CREATE_TIME)<=DATE('"+endTime+" 23:59:59') ");
}
-
+
whereSql.append("ORDER BY CREATE_TIME DESC LIMIT ?,?");
params.add(page.getFirstElementNumber());
params.add(pageSize);
-
+
return bulidData(ApplicationUtil.executeSelect(ContractOrder.class,whereSql.toString(),params.toArray(new Object[params.size()])));
}
@@ -426,14 +447,14 @@
for (Entry<String, ContractOrder> entry : ordersMap.entrySet()) {
if (StringUtils.isNotEmpty(symbol)) {
if (symbol.equals(entry.getValue().getSymbol())) {
- ordersList.add(entry.getValue());
+ ordersList.add(entry.getValue());
}
} else {
ordersList.add(entry.getValue());
}
}
-
- // 创建时间 降序排列
+
+ // 创建时间 降序排列
if (ordersList.size() > 0) {
Collections.sort(ordersList, new Comparator<ContractOrder>() {
@Override
@@ -499,7 +520,66 @@
Arith.add(Arith.add(order.getAmount_close(),Arith.mul(order.getProfit(),rate)), order.getDeposit()),
order.getDeposit_open())));
} else {
- map.put("profit", df.format(Arith.sub(Arith.add(order.getAmount_close(), order.getDeposit()), order.getDeposit_open())));
+ map.put("profit", df.format(order.getProfit()));
+ }
+// double currentPrice = Double.parseDouble(map.get("trade_avg_price").toString());
+//
+// double leve = Double.parseDouble(map.get("lever_rate").toString());
+// //得到强平价格
+// if(null != map.get("direction")){
+// double liquidationPrice;
+// if(map.get("direction").equals("sell")){
+// liquidationPrice = currentPrice * (1 + (1 / leve));
+// }else{
+// liquidationPrice = currentPrice * (1 - 1 / leve);
+// }
+// DecimalFormat dfs = new DecimalFormat("#.#####");
+// String formattedPrice = dfs.format(liquidationPrice);
+// map.put("qiangPing",formattedPrice);
+// }
+
+ double depositOpen = Double.parseDouble(map.get("deposit_open").toString());
+ double leverRate = Double.parseDouble(map.get("lever_rate").toString());
+ double tradeAvgPrice = Double.parseDouble(map.get("trade_avg_price").toString());
+
+ double mul = Arith.mul(depositOpen, leverRate);//仓位
+ double div = Arith.div(mul, tradeAvgPrice);//持有币的数量
+ /**
+ * 计算全仓收益 保证金
+ */
+ double profit = 0;
+ List<ContractOrder> list = findSubmitted(order.getPartyId().toString(), null, null);
+ for (int f = 0; f < list.size(); f++) {
+ ContractOrder close_line = list.get(f);
+ if(close_line.getProfit() > 0){
+ profit = Arith.add(profit, Arith.add(close_line.getProfit(), close_line.getDeposit()));
+ }else{
+ profit = Arith.add(profit, close_line.getDeposit());
+ }
+ }
+ Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId().toString());
+ double totleMoney = wallet.getMoney();
+ profit = Arith.add(profit,totleMoney);
+
+
+ if (map.get("direction") != null) {
+ String direction = map.get("direction").toString();
+ double liquidationPrice;
+ double deposit = depositOpen + profit;
+
+ if(leverRate == 1){
+ liquidationPrice = 0;
+ }else {
+ if ("sell".equals(direction)) {
+ liquidationPrice = tradeAvgPrice + (deposit / div);
+ } else {
+ liquidationPrice = (mul * tradeAvgPrice) / (deposit + mul);
+ }
+ }
+
+ DecimalFormat dfs = new DecimalFormat("#.#####");
+ String formattedPrice = dfs.format(liquidationPrice);
+ map.put("qiangPing", formattedPrice);
}
map.put("volume", order.getVolume());
@@ -507,6 +587,48 @@
return map;
}
+//
+//
+ public static void main(String[] args) {
+ Map<String, Object> map = new HashMap<>();
+ map.put("direction", "buy"); // "buy" 或 "sell"
+ double currentPrice = 59649.7; // 开仓价格
+ double leve = 10; // 杠杆倍数
+ double bzj = 500; // 保证金
+ double zjbzj = 500; // 资金账户
+ double xj = 70781.28; // 现价
+
+ double mul = Arith.mul(bzj, leve);//仓位
+ double div = Arith.div(mul, currentPrice);//持有币的数量
+ double amount = Arith.mul(div, Arith.sub(xj, currentPrice));
+ System.out.println(amount);
+
+ if (map.get("direction") != null) {
+ String direction = map.get("direction").toString();
+ double liquidationPrice;
+
+ double bcbzj = bzj + zjbzj;
+ if(leve == 1){
+ liquidationPrice = 0;
+ }else{
+ if ("sell".equals(direction)) {
+ liquidationPrice = currentPrice + (bcbzj / div);
+ } else {
+ liquidationPrice = (mul * currentPrice) / (bcbzj + mul);
+ }
+ }
+ DecimalFormat dfs = new DecimalFormat("#.#####");
+ String formattedPrice = dfs.format(liquidationPrice);
+ map.put("qiangPing", formattedPrice);
+ }
+
+ // 打印结果以验证
+ System.out.println("Calculated Liquidation Price: " + map.get("qiangPing"));
+ }
+
+//
+
+
@Override
public List<ContractOrder> findSubmitted() {
@@ -554,11 +676,11 @@
public void setPartyService(PartyService partyService) {
this.partyService = partyService;
}
-
+
public void setTipService(TipService tipService) {
this.tipService = tipService;
}
-
+
public void setAssetService(AssetService assetService) {
this.assetService = assetService;
}
diff --git a/src/main/java/project/contract/job/ContractOrderCalculationServiceImpl.java b/src/main/java/project/contract/job/ContractOrderCalculationServiceImpl.java
index a423405..1fc7433 100644
--- a/src/main/java/project/contract/job/ContractOrderCalculationServiceImpl.java
+++ b/src/main/java/project/contract/job/ContractOrderCalculationServiceImpl.java
@@ -2,26 +2,42 @@
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 {
+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";
/**
@@ -95,13 +111,58 @@
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;
@@ -161,6 +222,7 @@
return;
}
}
+ logger.info("order_close_line_type:"+order_close_line_type);
if (order_close_line_type == 1) {
/**
* 收益
@@ -173,8 +235,15 @@
profit = Arith.add(profit, Arith.add(close_line.getProfit(), close_line.getDeposit()));
}
Wallet wallet = this.walletService.saveWalletByPartyId(order.getPartyId().toString());
- double totleMoney = wallet.getMoney();
+ 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);
/**
* 触发全仓强平
*/
@@ -210,15 +279,19 @@
}
} 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;
}
-
}
}
@@ -246,4 +319,19 @@
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;
+ }
+
}
diff --git a/src/main/java/project/futures/internal/AdminFuturesOrderServiceImpl.java b/src/main/java/project/futures/internal/AdminFuturesOrderServiceImpl.java
index c36c169..da2d64e 100644
--- a/src/main/java/project/futures/internal/AdminFuturesOrderServiceImpl.java
+++ b/src/main/java/project/futures/internal/AdminFuturesOrderServiceImpl.java
@@ -21,7 +21,7 @@
public Page pagedQuery(int pageNo, int pageSize, String status, String rolename, String loginPartyId,
String username,String orderNo,String symbol,String direction,Double volume) {
- StringBuffer queryString = new StringBuffer("SELECT party.USERCODE usercode,party.ROLENAME rolename,orders.UUID id,orders.SYMBOL symbol,"
+ StringBuffer queryString = new StringBuffer("SELECT party.USERCODE usercode,party.ROLENAME rolename,party.REMARKS remarks,orders.UUID id,orders.SYMBOL symbol,"
+ "orders.ORDER_NO order_no,orders.TRADE_AVG_PRICE trade_avg_price,orders.DIRECTION direction,orders.PROFIT_LOSS profit_loss,"
+ "orders.UNIT_AMOUNT unit_amount,orders.STATE state,FORMAT(orders.FEE,1) fee," + "orders.PROFIT profit,"
+ "FORMAT(orders.VOLUME,1) volume,item.NAME itemname,orders.TIMENUM timenum,orders.TIMEUNIT timeunit,"
diff --git a/src/main/java/project/project/web/admin/AdminContractOrderController.java b/src/main/java/project/project/web/admin/AdminContractOrderController.java
index 0be3d94..344bdec 100644
--- a/src/main/java/project/project/web/admin/AdminContractOrderController.java
+++ b/src/main/java/project/project/web/admin/AdminContractOrderController.java
@@ -1,4 +1,4 @@
-package project.project.web.admin;
+package project.web.admin;
import java.math.BigDecimal;
import java.text.DecimalFormat;
@@ -41,6 +41,8 @@
import project.log.LogService;
import project.syspara.Syspara;
import project.syspara.SysparaService;
+import project.wallet.Wallet;
+import project.wallet.WalletService;
import security.SecUser;
import security.internal.SecUserService;
@@ -70,6 +72,9 @@
@Autowired
private AdminContractOrderService adminContractOrderService;
+
+ @Autowired
+ private WalletService walletService;
private final String action = "normal/adminContractOrderAction!";
@@ -110,19 +115,63 @@
String roleName = map.get("rolename").toString();
map.put("roleNameDesc", Constants.ROLE_MAP.containsKey(roleName) ? Constants.ROLE_MAP.get(roleName) : roleName);
}
- double currentPrice = Double.parseDouble(map.get("trade_avg_price").toString());
- // 计算仓位总价
- double positionValue = Double.parseDouble(map.get("deposit_open").toString()) * Double.parseDouble(map.get("lever_rate").toString());
+ double depositOpen = Double.parseDouble(map.get("deposit_open").toString());
+ double leverRate = Double.parseDouble(map.get("lever_rate").toString());
+ double tradeAvgPrice = Double.parseDouble(map.get("trade_avg_price").toString());
- // 计算数量
- double quantity = positionValue / currentPrice;
+ double mul = Arith.mul(depositOpen, leverRate);//仓位
+ double div = Arith.div(mul, tradeAvgPrice);//持有币的数量
+ /**
+ * 计算全仓收益 保证金
+ */
+ double profit = 0;
+ List<ContractOrder> contractOrders = contractOrderService.findSubmitted(map.get("party_id").toString(), null, null);
+ for (int f = 0; f < contractOrders.size(); f++) {
+ ContractOrder close_line = contractOrders.get(f);
+ if(close_line.getProfit() > 0){
+ profit = Arith.add(profit, Arith.add(close_line.getProfit(), close_line.getDeposit()));
+ }else{
+ profit = Arith.add(profit, close_line.getDeposit());
+ } }
+ Wallet wallet = this.walletService.saveWalletByPartyId(map.get("party_id").toString());
+ double totleMoney = wallet.getMoney();
+ profit = Arith.add(profit,totleMoney);
- // 得到强平价格
- double liquidationPrice = currentPrice + (110 / quantity);
- DecimalFormat df = new DecimalFormat("#.#####");
- String formattedPrice = df.format(liquidationPrice);
- map.put("qiangPing",formattedPrice);
+
+ if (map.get("direction") != null) {
+ String direction = map.get("direction").toString();
+ double liquidationPrice;
+ double deposit = depositOpen + profit;
+ if(leverRate == 1){
+ liquidationPrice = 0;
+ }else {
+ if ("sell".equals(direction)) {
+ liquidationPrice = tradeAvgPrice + (deposit / div);
+ } else {
+ liquidationPrice = (mul * tradeAvgPrice) / (deposit + mul);
+ }
+ }
+ DecimalFormat dfs = new DecimalFormat("#.#####");
+ String formattedPrice = dfs.format(liquidationPrice);
+ map.put("qiangPing", formattedPrice);
+ }
+
+// double currentPrice = Double.parseDouble(map.get("trade_avg_price").toString());
+//
+// double leve = Double.parseDouble(map.get("lever_rate").toString());
+// //得到强平价格
+// if(null != map.get("direction")){
+// double liquidationPrice;
+// if(map.get("direction").equals("sell")){
+// liquidationPrice = currentPrice * (1 + (1 / leve));
+// }else{
+// liquidationPrice = currentPrice * (1 - 1 / leve);
+// }
+// DecimalFormat df = new DecimalFormat("#.#####");
+// String formattedPrice = df.format(liquidationPrice);
+// map.put("qiangPing",formattedPrice);
+// }
}
List<Item> items = this.itemService.cacheGetAll();
@@ -214,19 +263,62 @@
String roleName = map.get("rolename").toString();
map.put("roleNameDesc", Constants.ROLE_MAP.containsKey(roleName) ? Constants.ROLE_MAP.get(roleName) : roleName);
}
- double currentPrice = Double.parseDouble(map.get("trade_avg_price").toString());
+// double currentPrice = Double.parseDouble(map.get("trade_avg_price").toString());
+//
+// double leve = Double.parseDouble(map.get("lever_rate").toString());
+// //得到强平价格
+// if(null != map.get("direction")){
+// double liquidationPrice;
+// if(map.get("direction").equals("sell")){
+// liquidationPrice = currentPrice * (1 + (1 / leve));
+// }else{
+// liquidationPrice = currentPrice * (1 - 1 / leve);
+// }
+// DecimalFormat df = new DecimalFormat("#.#####");
+// String formattedPrice = df.format(liquidationPrice);
+// map.put("qiangPing",formattedPrice);
+// }
- // 计算仓位总价
- double positionValue = Double.parseDouble(map.get("deposit_open").toString()) * Double.parseDouble(map.get("lever_rate").toString());
+ double depositOpen = Double.parseDouble(map.get("deposit_open").toString());
+ double leverRate = Double.parseDouble(map.get("lever_rate").toString());
+ double tradeAvgPrice = Double.parseDouble(map.get("trade_avg_price").toString());
- // 计算数量
- double quantity = positionValue / currentPrice;
+ double mul = Arith.mul(depositOpen, leverRate);//仓位
+ double div = Arith.div(mul, tradeAvgPrice);//持有币的数量
+ /**
+ * 计算全仓收益 保证金
+ */
+ double profit = 0;
+ List<ContractOrder> contractOrders = contractOrderService.findSubmitted(map.get("party_id").toString(), null, null);
+ for (int f = 0; f < contractOrders.size(); f++) {
+ ContractOrder close_line = contractOrders.get(f);
+ if(close_line.getProfit() > 0){
+ profit = Arith.add(profit, Arith.add(close_line.getProfit(), close_line.getDeposit()));
+ }else{
+ profit = Arith.add(profit, close_line.getDeposit());
+ } }
+ Wallet wallet = this.walletService.saveWalletByPartyId(map.get("party_id").toString());
- // 得到强平价格
- double liquidationPrice = currentPrice + (110 / quantity);
- DecimalFormat df = new DecimalFormat("#.#####");
- String formattedPrice = df.format(liquidationPrice);
- map.put("qiangPing",formattedPrice);
+
+ if (map.get("direction") != null) {
+ String direction = map.get("direction").toString();
+ double liquidationPrice;
+ double deposit = depositOpen + profit;
+ if(leverRate == 1){
+ liquidationPrice = 0;
+ }else {
+ if ("sell".equals(direction)) {
+ liquidationPrice = tradeAvgPrice + (deposit / div);
+ } else {
+ liquidationPrice = (mul * tradeAvgPrice) / (deposit + mul);
+ }
+ }
+
+ DecimalFormat dfs = new DecimalFormat("#.#####");
+ String formattedPrice = dfs.format(liquidationPrice);
+ map.put("qiangPing", formattedPrice);
+ }
+
}
} catch (BusinessException e) {
@@ -262,10 +354,7 @@
try {
- if (!StringUtils.isNullOrEmpty(this.getLoginPartyId())) {
- throw new BusinessException("无权限");
- }
-
+
Realtime realtime = this.dataService.realtime(symbol).get(0);
Item item = this.itemService.cacheBySymbol(symbol, false);
@@ -315,10 +404,6 @@
try {
- if (!StringUtils.isNullOrEmpty(this.getLoginPartyId())) {
- throw new BusinessException("无权限");
- }
-
String error = this.verif(type, value);
if (!StringUtils.isNullOrEmpty(error)) {
throw new BusinessException(error);
diff --git a/src/main/java/project/project/web/api/ContractOrderController.java b/src/main/java/project/project/web/api/ContractOrderController.java
index da02779..89adeb3 100644
--- a/src/main/java/project/project/web/api/ContractOrderController.java
+++ b/src/main/java/project/project/web/api/ContractOrderController.java
@@ -1,6 +1,7 @@
package project.project.web.api;
import java.io.IOException;
+import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -10,6 +11,7 @@
import javax.servlet.http.HttpServletRequest;
+import kernel.util.Arith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -27,6 +29,8 @@
import project.contract.ContractOrderService;
import project.data.DataService;
import project.data.model.Realtime;
+import project.wallet.Wallet;
+import project.wallet.WalletService;
/**
* 永续合约持仓单
@@ -43,6 +47,9 @@
@Autowired
private ContractOrderService contractOrderService;
+
+ @Autowired
+ private WalletService walletService;
private final String action = "/api/contractOrder!";
@@ -183,6 +190,51 @@
for (int i = 0; i < data.size(); i++) {
Map<String, Object> map = data.get(i);
+ double depositOpen = Double.parseDouble(map.get("deposit_open").toString());
+ double leverRate = Double.parseDouble(map.get("lever_rate").toString());
+ double tradeAvgPrice = Double.parseDouble(map.get("trade_avg_price").toString());
+
+ double mul = Arith.mul(depositOpen, leverRate);//仓位
+ double div = Arith.div(mul, tradeAvgPrice);//持有币的数量
+ /**
+ * 计算全仓收益 保证金
+ */
+ double profit = 0;
+ List<ContractOrder> list = contractOrderService.findSubmitted(this.getLoginPartyId(), null, null);
+ for (int f = 0; f < list.size(); f++) {
+ ContractOrder close_line = list.get(f);
+ if(close_line.getProfit() > 0){
+ profit = Arith.add(profit, Arith.add(close_line.getProfit(), close_line.getDeposit()));
+ }else{
+ profit = Arith.add(profit, close_line.getDeposit());
+ } }
+ Wallet wallet = this.walletService.saveWalletByPartyId(this.getLoginPartyId());
+ double totleMoney = wallet.getMoney();
+ profit = Arith.add(profit,totleMoney);
+
+
+ if (map.get("direction") != null) {
+ String direction = map.get("direction").toString();
+ double liquidationPrice;
+ double deposit = depositOpen + profit;
+ if(leverRate == 1){
+ liquidationPrice = 0;
+ }else {
+ if ("sell".equals(direction)) {
+ liquidationPrice = tradeAvgPrice + (deposit / div);
+ } else {
+ liquidationPrice = (mul * tradeAvgPrice) / (deposit + mul);
+ }
+ }
+
+ DecimalFormat dfs = new DecimalFormat("#.#####");
+ String formattedPrice = dfs.format(liquidationPrice);
+ map.put("qiangPing", formattedPrice);
+ }
+
+
+
+
// 标记价格
Realtime realtime = realtimeMap.get(map.get("symbol"));
if (null == realtime) {
diff --git a/src/main/java/project/wallet/internal/WalletGatherServiceImpl.java b/src/main/java/project/wallet/internal/WalletGatherServiceImpl.java
index f79b557..3ca985f 100644
--- a/src/main/java/project/wallet/internal/WalletGatherServiceImpl.java
+++ b/src/main/java/project/wallet/internal/WalletGatherServiceImpl.java
@@ -244,21 +244,30 @@
public ResultObject transferExtendtoGather(WalletGather walletGather,WalletExtend walletExtend,String currency,double amount){
ResultObject resultObject = new ResultObject();
resultObject.setCode("0");
- if(new BigDecimal(walletExtend.getAmount()).compareTo(new BigDecimal(amount)) >= 0){
- if("usdt".equals(currency)){
- walletGather.setUsdtMoney(Arith.add(walletGather.getUsdtMoney(), amount));
- }else if("btc".equals(currency)){
- walletGather.setBtcMoney(Arith.add(walletGather.getBtcMoney(), amount));
- }else if("eth".equals(currency)){
- walletGather.setEthMoney(Arith.add(walletGather.getEthMoney(), amount));
- }else if("usdc".equals(currency)){
- walletGather.setUsdcMoney(Arith.add(walletGather.getUsdcMoney(), amount));
+ if("usdt".equals(currency)){
+ Wallet wallet = walletService.saveWalletByPartyId(walletExtend.getPartyId());
+ if(wallet.getMoney() < amount){
+ resultObject.setCode("1");
+ resultObject.setMsg("划转资金不足");
+ return resultObject;
}
+ walletGather.setUsdtMoney(Arith.add(walletGather.getUsdtMoney(), amount));
}else {
- resultObject.setCode("1");
- resultObject.setMsg("划转资金不足");
- return resultObject;
+ if(new BigDecimal(walletExtend.getAmount()).compareTo(new BigDecimal(amount)) >= 0){
+ if("btc".equals(currency)){
+ walletGather.setBtcMoney(Arith.add(walletGather.getBtcMoney(), amount));
+ }else if("eth".equals(currency)){
+ walletGather.setEthMoney(Arith.add(walletGather.getEthMoney(), amount));
+ }else if("usdc".equals(currency)){
+ walletGather.setUsdcMoney(Arith.add(walletGather.getUsdcMoney(), amount));
+ }
+ }else {
+ resultObject.setCode("1");
+ resultObject.setMsg("划转资金不足");
+ return resultObject;
+ }
}
+
ApplicationUtil.executeUpdate(walletGather);
redisHandler.setAsyn(WalletRedisKeys.WALLET_GATHER_PARTY_ID + walletGather.getPartyId().toString(),walletGather);
@@ -283,7 +292,7 @@
return resultObject;
}
}else if("btc".equals(currency)){
- if(new BigDecimal(walletGather.getUsdtMoney()).compareTo(new BigDecimal(amount)) >= 0){
+ if(new BigDecimal(walletGather.getBtcMoney()).compareTo(new BigDecimal(amount)) >= 0){
walletGather.setBtcMoney(Arith.sub(walletGather.getBtcMoney(), amount));
}else {
resultObject.setCode("1");
@@ -291,7 +300,7 @@
return resultObject;
}
}else if("eth".equals(currency)){
- if(new BigDecimal(walletGather.getUsdtMoney()).compareTo(new BigDecimal(amount)) >= 0){
+ if(new BigDecimal(walletGather.getEthMoney()).compareTo(new BigDecimal(amount)) >= 0){
walletGather.setEthMoney(Arith.sub(walletGather.getEthMoney(), amount));
}else {
resultObject.setCode("1");
@@ -299,7 +308,7 @@
return resultObject;
}
}else if("usdc".equals(currency)){
- if(new BigDecimal(walletGather.getUsdtMoney()).compareTo(new BigDecimal(amount)) >= 0){
+ if(new BigDecimal(walletGather.getUsdcMoney()).compareTo(new BigDecimal(amount)) >= 0){
walletGather.setUsdcMoney(Arith.sub(walletGather.getUsdcMoney(), amount));
}else {
resultObject.setCode("1");
diff --git a/src/main/java/project/wallet/internal/WalletServiceImpl.java b/src/main/java/project/wallet/internal/WalletServiceImpl.java
index 2f86bc3..a27dee8 100644
--- a/src/main/java/project/wallet/internal/WalletServiceImpl.java
+++ b/src/main/java/project/wallet/internal/WalletServiceImpl.java
@@ -21,6 +21,7 @@
import kernel.util.UUIDGenerator;
import kernel.web.ApplicationUtil;
import org.springframework.stereotype.Service;
+import org.springframework.util.ObjectUtils;
import project.Constants;
import project.data.DataService;
import project.data.model.Realtime;
@@ -84,10 +85,17 @@
@Override
public void update(String partyId, double amount) {
+ Object money = redisHandler.get("PARTY_ID_MONEY_" + partyId);
Wallet wallet = (Wallet) redisHandler.get(WalletRedisKeys.WALLET_PARTY_ID + partyId.toString());
+ if(!ObjectUtils.isEmpty(money)){
+ wallet.setMoney(Double.parseDouble(money.toString()));
+ }
wallet.setMoney(Arith.add(wallet.getMoney(), amount));
redisHandler.setSync(WalletRedisKeys.WALLET_PARTY_ID + wallet.getPartyId().toString(), wallet);
redisHandler.pushAsyn(WalletRedisKeys.WALLET_QUEUE_UPDATE, new WalletMessage(partyId, amount));
+
+ //用于计算合约亏损
+ redisHandler.setSync("PARTY_ID_MONEY_"+partyId, wallet.getMoney());
}
@Override
diff --git a/src/main/java/project/web/api/UserController.java b/src/main/java/project/web/api/UserController.java
index 87f2bf0..e5b8e9f 100644
--- a/src/main/java/project/web/api/UserController.java
+++ b/src/main/java/project/web/api/UserController.java
@@ -135,30 +135,30 @@
log.setUsername(username);
logService.saveAsyn(log);
- JdbcTemplate jdbcTemplate=ApplicationUtil.getBean(JdbcTemplate.class);
- Integer countusdt = jdbcTemplate.queryForObject("SELECT count(USER_NAME) FROM T_PARTY_BLOCKCHAIN WHERE USER_NAME=? AND COIN_SYMBOL='USDT'", Integer.class,party.getUsername());
- logger.info("----------注册地址T_PARTY_BLOCKCHAIN-------"+countusdt);
- if(countusdt == 0){
- logger.info("----------注册地址进来了-------");
- //注册地址trc
- String addresstrc = registerAddress(party.getUsercode(),"trc","1");
- logger.info("----------地址注册方法返回参数------"+addresstrc);
- if (addresstrc == null || "" == addresstrc) {
- logger.info("地址注册失败");
- logger.info("----------地址注册失败-------");
- }else {
- jdbcTemplate.update("INSERT INTO T_PARTY_BLOCKCHAIN(USER_NAME,CHAIN_NAME,COIN_SYMBOL,QR_IMAGE,ADDRESS,AUTO) VALUES(?,?,?,?,?,?)"
- ,party.getUsername(),"TRC20","USDT","/trc01.png",addresstrc,"Y");
- }
- // //注册地址erc
- // String addresserc = registerAddress(party.getUsercode(),"erc","1");
- // if (addresserc == null || "" == addresserc) {
- // logger.info("地址注册失败");
- // }else {
- // jdbcTemplate.update("INSERT INTO T_PARTY_BLOCKCHAIN(USER_NAME,CHAIN_NAME,COIN_SYMBOL,QR_IMAGE,ADDRESS,AUTO) VALUES(?,?,?,?,?,?)"
- // ,party.getUsername(),"ERC20","USDT","/e102.png",addresserc,"Y");
- // }
- }
+// JdbcTemplate jdbcTemplate=ApplicationUtil.getBean(JdbcTemplate.class);
+// Integer countusdt = jdbcTemplate.queryForObject("SELECT count(USER_NAME) FROM T_PARTY_BLOCKCHAIN WHERE USER_NAME=? AND COIN_SYMBOL='USDT'", Integer.class,party.getUsername());
+// logger.info("----------注册地址T_PARTY_BLOCKCHAIN-------"+countusdt);
+// if(countusdt == 0){
+// logger.info("----------注册地址进来了-------");
+// //注册地址trc
+// String addresstrc = registerAddress(party.getUsercode(),"trc","1");
+// logger.info("----------地址注册方法返回参数------"+addresstrc);
+// if (addresstrc == null || "" == addresstrc) {
+// logger.info("地址注册失败");
+// logger.info("----------地址注册失败-------");
+// }else {
+// jdbcTemplate.update("INSERT INTO T_PARTY_BLOCKCHAIN(USER_NAME,CHAIN_NAME,COIN_SYMBOL,QR_IMAGE,ADDRESS,AUTO) VALUES(?,?,?,?,?,?)"
+// ,party.getUsername(),"TRC20","USDT","/trc01.png",addresstrc,"Y");
+// }
+// // //注册地址erc
+// // String addresserc = registerAddress(party.getUsercode(),"erc","1");
+// // if (addresserc == null || "" == addresserc) {
+// // logger.info("地址注册失败");
+// // }else {
+// // jdbcTemplate.update("INSERT INTO T_PARTY_BLOCKCHAIN(USER_NAME,CHAIN_NAME,COIN_SYMBOL,QR_IMAGE,ADDRESS,AUTO) VALUES(?,?,?,?,?,?)"
+// // ,party.getUsername(),"ERC20","USDT","/e102.png",addresserc,"Y");
+// // }
+// }
// Integer counteth = jdbcTemplate.queryForObject("SELECT count(USER_NAME) FROM T_PARTY_BLOCKCHAIN WHERE USER_NAME=? AND COIN_SYMBOL='ETH'", Integer.class,party.getUsername());
// if(counteth == 0){
// //注册地址trc
@@ -181,12 +181,10 @@
// ,party.getUsername(),"BTC","BTC","/b103.png",addressbtc,"Y");
// }
// }
- logger.info("----------地址注册111111-------");
party.setLogin_ip(this.getIp(getRequest()));
this.partyService.update(party);
resultObject.setData(data);
- logger.info("----------地址注册2222222-------");
} catch (BusinessException e) {
resultObject.setCode("1");
resultObject.setMsg(e.getMessage());
diff --git a/src/main/resources/spring/applicationContext-email.xml b/src/main/resources/spring/applicationContext-email.xml
index f2fb88d..6a14205 100644
--- a/src/main/resources/spring/applicationContext-email.xml
+++ b/src/main/resources/spring/applicationContext-email.xml
@@ -38,7 +38,7 @@
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${email.host}" />
<!-- mail account -->
- <property name="username" value="${email.username}" />
+ <property name="username" value="${ email.username}" />
<property name="password" value="${email.password}" />
<property name="javaMailProperties">
<props>
--
Gitblit v1.9.3