Files
zszq-trs/YLErpUnitTest/Modules/MarginModule/MarginCalculation/BXMarginCalculation.cs
T
2024-05-09 14:06:26 +08:00

478 lines
28 KiB
C#

//using System;
//using System.Collections.Generic;
//using System.Linq;
//using YLErp.BLL.Calculation;
//using YLErp.BLL.Calculation.V2;
//using YLErp.Commons;
//using YLErp.DBModels;
//using YLErp.DBModels.Consts;
//using YLErp.Enums;
//using YLErp.Model;
//using YLErp.QdpModule;
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
//namespace YLErp.BLL.MarginCalculationBak
//{
// /// <summary>
// /// 伴兴保证金计算
// /// </summary>
// public class BXMarginCalculation : MarginCalculationBase
// {
// // 定义一个静态变量来保存类的实例
// public static readonly BXMarginCalculation Instance;
// static BXMarginCalculation()
// {
// Instance = new BXMarginCalculation();
// }
// // 定义私有构造函数,使外界不能创建该类实例
// protected BXMarginCalculation()
// {
// }
// public override List<trade_span> RunMarginCalculation(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易", bool forOtherSide = false)
// {
// //结果集
// List<trade_span> resultMap = new List<trade_span>();
// var ignoreCalcArray = tradeList.FindAll(O => O.InitialMargin != null && O.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc);
// if (ignoreCalcArray.Count > 0)
// {
// ignoreCalcArray.ForEach(O =>
// {
// var initMargin = O.InitialMargin * (O.Notional / O.OriginalNotional);
// trade_span ts = new trade_span()
// {
// TradeId = O.id,
// ClientId = O.ClientId,
// ValueDate = settleDate,
// UnderlyingId = O.UnderlyingId,
// UnderlyingCode = O.UnderlyingCode,
// OptId = userId,
// OptName = userName,
// OptDate = DateTime.Now,
// Spv1 = initMargin,
// Spv2 = initMargin,
// Spv3 = initMargin,
// Spv4 = initMargin,
// };
// ts.setWorstCastClientPayable4();
// resultMap.Add(ts);
// });
// }
// var useCalcArray = tradeList.FindAll(O => O.InitialMargin == null || O.CalcFlag != (int)CalcFlagEnum.IgnoreMarginCalc);
// if (useCalcArray.Count > 0)
// {
// resultMap.AddRange(marginCalculation(userId, userName, useCalcArray, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide));
// }
// return resultMap;
// }
// public List<trade_span> marginCalculation(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易", bool forOtherSide = false)
// {
// //结果集
// Dictionary<int, trade_span> resultMap = new Dictionary<int, trade_span>();
// using (YLContext db = new YLContext())
// {
// if (!(priceDict?.Count > 0))
// {
// var codes = tradeList.Select(O => O.UnderlyingCode).ToArray();
// priceDict = base.GetSettlePrice(codes, settleDate);
// }
// if (priceDict.Count == 0)
// {
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
// return resultMap.Values.ToList();
// }
// var underlyingIds = priceDict.Keys.ToList();
// //交易对应客户信息
// var clientIds = tradeList.Select(t => t.ClientId ?? 0).ToList();
// var clientList = (from client in db.client
// join clientlevel in db.clientlevel
// on client.LevelId equals clientlevel.id into tempClientlevel
// from clientlevelTT in tempClientlevel.DefaultIfEmpty()
// where clientIds.Contains(client.id)
// select new
// {
// client,
// clientlevel = clientlevelTT
// }).ToList();
// Dictionary<int, string> clientClassDict = new clientBLL().GetClients(clientIds).ToDictionary(K => K.id, V => V.ProperClientClass);
// //获取标的涨跌幅限制
// var umDatas = (from um in db.underlying_manager
// join variety in db.variety on um.CommodityCode equals variety.VarietyCode
// where underlyingIds.Contains(um.id)
// select new
// {
// um.id,
// um.VolatilityRate,
// um.UpDownLimit,
// defUpLimit = variety.UpLimit,
// defDownLimit = variety.DownLimit,
// defVolatilityRate = variety.VolatilityRate
// }).ToList();
// var UpLimitDict = new Dictionary<int, string>();
// var DownLimitDict = new Dictionary<int, string>();
// var umVolatilityRateDic = new Dictionary<int, double>();
// if (umDatas != null && umDatas.Count > 0)
// {
// umDatas.ForEach(t =>
// {
// //OTC-8856 Start
// //1.波动率变化
// if (DataConvert.TryParsePercentValue(t.VolatilityRate, out double pvalue) && (Math.Abs(pvalue) >= 1e-5))
// {
// umVolatilityRateDic[t.id] = pvalue;
// }
// else if (DataConvert.TryParsePercentValue(t.defVolatilityRate, out pvalue) && (Math.Abs(pvalue) >= 1e-5))
// {
// umVolatilityRateDic[t.id] = pvalue;
// }
// });
// }
// if (!hasOptionInfo)
// {
// tradeBLL.SetFieldsByTradeType(tradeList);
// }
// var tradeVolatilityRateDic = tradeList.ToDictionary(t => t.id, t => (umVolatilityRateDic.ContainsKey(t.UnderlyingId) ? umVolatilityRateDic[t.UnderlyingId] : 0) + (clientClassDict[t.ClientId ?? 0] != null && clientClassDict[t.ClientId ?? 0].Contains("普通投资者") ? 0.02 : 0))
// .Where(d => d.Value > 0).ToDictionary(d => d.Key, d => d.Value);
// Dictionary<string, Dictionary<int, double>> eodPriceDict = new Dictionary<string, Dictionary<int, double>>();
// var upLimitPrices = new Dictionary<int, double>();
// var downLimitPrices = new Dictionary<int, double>();
// //根据涨跌幅限制以及当日结算价计算涨停价以及跌停价
// if (priceDict != null && priceDict.Count > 0)
// {
// Dictionary<int, double[]> dict = base.GetUpDownLimitPrice(priceDict);
// foreach (var t in dict)
// {
// upLimitPrices[t.Key] = t.Value[0];
// downLimitPrices[t.Key] = t.Value[1];
// }
// eodPriceDict["up"] = upLimitPrices;
// eodPriceDict["down"] = downLimitPrices;
// }
// //波动率变化
// var addVolRateList = new List<Dictionary<int, double>> { null, tradeVolatilityRateDic };
// var userIdNew = UniqueTimeId.Get().ToString();
// try
// {
// foreach (var price in eodPriceDict)
// {
// addVolRateList.ForEach(addVolRateDic =>
// {
// var key = $"{price.Key}_{(addVolRateDic == null ? 0 : 1)}";
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(
// userIdNew, // userId + "_" + price.Key,
// settleDate,
// tradeList,
// price.Value,
// ValueCalculator.PV_ONLY,
// addVolRateDic,
// isEodSettle,
// volType,
// isUseTradeVol: PS.Config.IsTradeVol,
// PreciseTimeMode: !isEodSettle,
// isAddVolPercent: false);
// if (tradeRiskResult.Results != null && tradeRiskResult.Results.Count > 0)
// {
// foreach (var item in tradeRiskResult.Results)
// {
// var client = clientList.FirstOrDefault(c => c.client.id == item.Trade.ClientId);
// var clientRatio = client == null ? 1.0 : (client.clientlevel == null ? 1.0 : (client.clientlevel.Ratio ?? 1.0));
// double value = 0;
// if (item.Trade.TradeType == "自定义交易")
// {
// var eodTradeRiskManual = db.eod_trade_risk_manual.Where(x => x.ValueDate <= settleDate && x.TradeId == item.Trade.id).OrderByDescending(x => x.ValueDate).FirstOrDefault();
// //收盘时如果自定义交易还活着且没有维护当日风险,并且收的时系统日期当日的盘,抛出exception
// if (isEodSettle && !ConsTrade.TradeCompleteStatus.Contains(item.Trade.TradeStatus) && settleDate == valuedateBLL.SystemDate.ValueDate)
// {
// if (eodTradeRiskManual == null || eodTradeRiskManual.ValueDate != settleDate)
// {
// var error = $"TradeNumber:{item.Trade.TradeNumber}在{settleDate.ToString("yyyy-MM-dd")}需先进行交易风险维护";
// throw new Exception(error);
// }
// }
// value = eodTradeRiskManual?.Margin ?? 0;
// }
// if (resultMap.ContainsKey(item.Trade.id))
// {
// switch (key)
// {
// case "up_0":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// resultMap[item.Trade.id].Spv1 = item.Trade.InitialMargin;
// }
// else
// {
// resultMap[item.Trade.id].Spv1 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// case "up_1":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// resultMap[item.Trade.id].Spv2 = item.Trade.InitialMargin;
// }
// else
// {
// resultMap[item.Trade.id].Spv2 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// case "down_0":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// resultMap[item.Trade.id].Spv3 = item.Trade.InitialMargin;
// }
// else
// {
// resultMap[item.Trade.id].Spv3 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// case "down_1":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// resultMap[item.Trade.id].Spv4 = item.Trade.InitialMargin;
// }
// else
// {
// resultMap[item.Trade.id].Spv4 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// default:
// break;
// }
// resultMap[item.Trade.id].setWorstCastClientPayable4();
// }
// else
// {
// var trade = tradeList.FirstOrDefault(t => t.id == item.Trade.id);
// var tempTradeSpan = new trade_span
// {
// TradeId = item.Trade.id,
// ClientId = trade.ClientId,
// ValueDate = settleDate,
// UnderlyingId = trade.UnderlyingId,
// UnderlyingCode = trade.UnderlyingCode,
// OptId = userId,
// OptName = userName,
// OptDate = DateTime.Now
// };
// switch (key)
// {
// case "up_0":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// tempTradeSpan.Spv1 = item.Trade.InitialMargin;
// }
// else
// {
// tempTradeSpan.Spv1 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// case "up_1":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// tempTradeSpan.Spv2 = item.Trade.InitialMargin;
// }
// else
// {
// tempTradeSpan.Spv2 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// case "down_0":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// tempTradeSpan.Spv3 = item.Trade.InitialMargin;
// }
// else
// {
// tempTradeSpan.Spv3 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// case "down_1":
// if (item.Trade.CalcFlag == (int)CalcFlagEnum.IgnoreMarginCalc)
// {
// tempTradeSpan.Spv4 = item.Trade.InitialMargin;
// }
// else
// {
// tempTradeSpan.Spv4 = GetMargin(item.Trade, item.ValueResult, clientRatio);
// }
// break;
// default:
// break;
// }
// resultMap[item.Trade.id] = tempTradeSpan;
// }
// }
// }
// });
// }
// }
// finally
// {
// //上面的计算用到静态生成market,需要清除
// QdpMarketManager.Instance.RemovePrebuiltMarketProxy(userIdNew);
// }
// return resultMap.Values.ToList();
// }
// }
// private double GetMargin(trade trade, TradeValueResult valueResult, double clientRatio)
// {
// double value = 0.0;
// if (trade.TradeType == "结构化交易")
// {
// if (trade.StructureType != null && trade.StructureType.Contains("跨式"))
// {
// value = valueResult.MaxAbsPv;
// }
// else
// {
// value = valueResult.SellPv;
// }
// }
// else if (trade.TradeType != "自定义交易")
// {
// value = valueResult.Pv;
// }
// return (double.IsNaN(value) ? 0 : value) * clientRatio;
// }
// public override bool CalcClientMargin(int userId, string userName, DateTime settleDate, List<trade_span> tradeSpans, List<trade_span> tradeSpansOtherSide, int SpanType = 0, List<int> RefreshClientIds = null, bool OnlyBuyer = false, Dictionary<int, double> clientAdditionalMarginDic = null)
// {
// using (YLContext db = new YLContext())
// {
// //删除
// if (tradeSpans != null && tradeSpans.Count > 0)
// {
// var tradeIds = tradeSpans.Select(t => t.TradeId).ToList();
// var tradeList = db.trade.AsNoTracking().Where(t => tradeIds.Contains(t.id)).ToList();
// var clientIds = tradeSpans.Select(t => t.ClientId).Distinct().ToList();
// var clientList = db.client.Where(x => clientIds.Contains(x.id)).ToList();
// var tradeSpanInfo = (from tradeSpan in tradeSpans
// join
// trade in tradeList on tradeSpan.TradeId equals trade.id
// where tradeSpan.ValueDate == settleDate
// select new { trade, tradeSpan }).ToList();
// var clientSpanNews = new List<client_span>();
// var clientGroups = tradeSpanInfo.GroupBy(t => t.trade.ClientId);
// foreach (var clientGroup in clientGroups)
// {
// var underlyingGroup = clientGroup.GroupBy(t => t.trade.UnderlyingId).Select(t => new client_span
// {
// ClientId = clientGroup.Key,
// ValueDate = settleDate,
// Spv1 = t.Sum(g => g.tradeSpan.Spv1) * (-1),
// Spv2 = t.Sum(g => g.tradeSpan.Spv2) * (-1),
// Spv3 = t.Sum(g => g.tradeSpan.Spv3) * (-1),
// Spv4 = t.Sum(g => g.tradeSpan.Spv4) * (-1),
// OptId = userId,
// OptName = userName,
// OptDate = DateTime.Now,
// SpanType = SpanType
// }).ToList();
// foreach (var item in underlyingGroup)
// {
// if (PS.Config.ErpElement.NonInterBankMarginNetting)
// {
// item.WorstCastClientPayable = Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0);
// }
// else
// {
// item.WorstCastClientPayable = Math.Min(Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0), 0);
// }
// item.TwoSideMargin = Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0);
// }
// var clientSpan = new client_span
// {
// ClientId = clientGroup.Key,
// ValueDate = settleDate,
// Spv1 = underlyingGroup.Sum(g => g.Spv1),
// Spv2 = underlyingGroup.Sum(g => g.Spv2),
// Spv3 = underlyingGroup.Sum(g => g.Spv3),
// Spv4 = underlyingGroup.Sum(g => g.Spv4),
// //负数代表客户应缴保证金,正数代表客户应收保证金
// WorstCastClientPayable = (PS.Config.ErpElement.TwoSideMargin && clientList.FirstOrDefault(x => x.id == clientGroup.Key) != null && clientList.FirstOrDefault(x => x.id == clientGroup.Key).HasTwoSideMargin == 1) ? underlyingGroup.Sum(g => g.WorstCastClientPayable) : underlyingGroup.Sum(g => g.WorstCastClientPayable) < 0 ? underlyingGroup.Sum(g => g.WorstCastClientPayable) : 0,
// TwoSideMargin = underlyingGroup.Sum(g => g.TwoSideMargin),
// OptId = userId,
// OptName = userName,
// OptDate = DateTime.Now,
// SpanType = SpanType,
// AdditionalWorstCastClientPayable = clientAdditionalMarginDic == null ? 0 : (clientAdditionalMarginDic.ContainsKey(clientGroup.Key ?? 0) ? clientAdditionalMarginDic[clientGroup.Key ?? 0] : 0)
// };
// clientSpanNews.Add(clientSpan);
// }
// //span类型为实时删除所有实时计算的交易的保证金信息
// if (SpanType == client_span.SpanType_RealTime)
// {
// //var clientIds = clientSpanNews.Select(t => t.ClientId).Distinct().ToList();
// //var clientSpanOlds = db.client_span.Where(t => t.SpanType == SpanType);
// if (RefreshClientIds != null)
// {
// //clientSpanOlds = db.client_span.Where(t => RefreshClientIds.Contains(t.ClientId ?? 0));
// db.BulkDelete<client_span>($"{nameof(client_span.ClientId)} in @ids", new { ids = RefreshClientIds });
// }
// else
// {
// db.BulkDelete<client_span>($"{nameof(client_span.SpanType)}=@SpanType", new { SpanType });
// }
// //MySqlBulkExtensions.BulkDelete(db, clientSpanOlds);
// MySqlBulkExtensions.BulkInsert(db, clientSpanNews);
// }
// else
// {
// //var clientSpanOldsWithOutFlag = db.client_span.Where(t => t.ValueDate == settleDate && t.SpanType == SpanType && !t.ModifiedFlag).ToList();
// //MySqlBulkExtensions.BulkDelete(db, clientSpanOldsWithOutFlag);
// db.BulkDelete<client_span>($"{nameof(client_span.ValueDate)}=@settleDate and {nameof(client_span.SpanType)}=@SpanType and {nameof(client_span.ModifiedFlag)}=0", new { settleDate, SpanType });
// var clientSpanOldsWithFlag = db.client_span.Where(t => t.ValueDate == settleDate && t.SpanType == SpanType && t.ModifiedFlag).ToList();
// //筛选出可以修改的clientSpan
// clientSpanNews = clientSpanNews.Where(c => !clientSpanOldsWithFlag.Any(t => t.ValueDate == c.ValueDate && t.ClientId == c.ClientId)).ToList();
// MySqlBulkExtensions.BulkInsert(db, clientSpanNews);
// }
// db.SaveChanges();
// }
// return true;
// }
// }
// public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
// {
// if (trade.TradeType == "结构化交易" && trade.id > 0)
// {
// using (YLContext db = new YLContext())
// {
// trade.SubTrades = db.trade.Where(x => x.ParentTradeId == trade.id).ToList();
// }
// }
// var tradeMargin = RunMarginCalculation(0, "系统", new List<trade> { trade }, isInitialMargin ? (trade.TradeDate ?? valuedateBLL.ValueDate) : valuedateBLL.ValueDate, new Dictionary<int, double> { { trade.UnderlyingId, price } }, hasOptionInfo: hasOptionInfo);
// if (null != tradeMargin)
// {
// return tradeMargin.FirstOrDefault()?.WorstCastClientPayable ?? 0.0;
// }
// return 0.0;
// }
// }
//}