//using System; //using System.Collections.Generic; //using System.Linq; //using YLErp.BLL.Calculation.V2; //using YLErp.DBModels; //using YLErp.DBModels.Consts; //using YLErp.Model; //using YLErp.Modules.MarginModule; //using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld; //namespace YLErp.BLL.MarginCalculationBak //{ // /// // /// 申银万国 // /// // public class SYWGMarginCalculation : MarginCalculationBase // { // // 定义一个静态变量来保存类的实例 // public static readonly SYWGMarginCalculation Instance; // static SYWGMarginCalculation() // { // Instance = new SYWGMarginCalculation(); // } // // 定义私有构造函数,使外界不能创建该类实例 // private SYWGMarginCalculation() // { // } // public override List RunMarginCalculation(int userId, string userName, List tradeList, DateTime settleDate, Dictionary priceDict, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易", bool forOtherSide = false) // { // List tradeSpans = new List(); // if (tradeList != null && tradeList.Count > 0) // { // var tempStockTradeList = tradeList.Where(t => t.UnderlyingInstrumentType == ConsGlobal.InstrumentType.Stock).ToList(); // if (tempStockTradeList.Any()) // { // var stockTradeSpanlist = StockMarginCalculation(userId, userName, tempStockTradeList, settleDate, isEodSettle); // if (stockTradeSpanlist.Count > 0) // { // tradeSpans.AddRange(stockTradeSpanlist); // } // } // var tempFutureTradeList = tradeList.Where(t => t.UnderlyingInstrumentType == ConsGlobal.InstrumentType.CommodityFutures).ToList(); // if (tempFutureTradeList.Any()) // { // if (!(priceDict?.Count > 0)) // { // var codes = tempFutureTradeList.Select(O => O.UnderlyingCode).ToArray(); // priceDict = base.GetSettlePrice(codes, settleDate); // } // if (priceDict.Count > 0) // { // var futureTradeSpanlist = FutureMarginCalculation(userId, userName, tempFutureTradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, volType); // if (futureTradeSpanlist.Count > 0) // { // tradeSpans.AddRange(futureTradeSpanlist); // } // } // } // } // return tradeSpans; // } // /// // /// 股票类期权计算保证金 // /// // public List StockMarginCalculation(int userId, string userName, List tradeList, DateTime settleDate, bool isEodSettle) // { // List tradeSpans = new List(); // if (tradeList != null && tradeList.Count > 0) // { // using (YLContext db = new YLContext()) // { // var marginRation = valuedateBLL.SystemDate.MarginRatio ?? 0.15; // var clientIds = tradeList.Select(t => t.ClientId).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(); // if (clientList != null) // { // tradeList.ForEach(t => // { // var client = clientList.FirstOrDefault(c => c.client.id == t.ClientId); // if (client != null) // { // var clientRatio = client.clientlevel == null ? 1.0 : (client.clientlevel.Ratio ?? 1.0); // //如果是股票去名义本金,如果是期货取:份额 * 即期价格 // var value = (t.StockEqvNotional ?? (t.Notional * t.SpotPrice ?? 0.0)) * marginRation * (t.BuySell == "买入" ? 1 : 0) * clientRatio; // if (t.TradeType == "自定义交易") // { // var eodTradeRiskManual = db.eod_trade_risk_manual.Where(x => x.ValueDate <= settleDate && x.TradeId == t.id).OrderByDescending(x => x.ValueDate).FirstOrDefault(); // //收盘时如果自定义交易还活着且没有维护当日风险,并且收的时系统日期当日的盘,抛出exception // if (isEodSettle && !ConsTrade.TradeCompleteStatus.Contains(t.TradeStatus) && settleDate == valuedateBLL.SystemDate.ValueDate) // { // if (eodTradeRiskManual == null || eodTradeRiskManual.ValueDate != settleDate) // { // var error = $"TradeNumber:{t.TradeNumber}在{settleDate.ToString("yyyy-MM-dd")}需先进行交易风险维护"; // throw new Exception(error); // } // } // value = eodTradeRiskManual?.Margin ?? 0; // } // tradeSpans.Add(new trade_span // { // TradeId = t.id, // OptDate = DateTime.Now, // OptId = userId, // OptName = userName, // ClientId = client.client.id, // UnderlyingId = t.UnderlyingId, // UnderlyingCode = t.UnderlyingCode, // ValueDate = settleDate, // Spv1 = value, // Spv2 = value, // Spv3 = value, // Spv4 = value, // WorstCastClientPayable = value // }); // } // }); // } // } // } // return tradeSpans; // } // /// // /// 商品期权计算保证金 // /// // public List FutureMarginCalculation(int userId, string userName, List futureTradeList, DateTime settleDate, Dictionary priceDict, bool hasOptionInfo = false, bool isEodSettle = false, string volType = "交易") // { // if (futureTradeList == null || !futureTradeList.Any()) // { // return new List(0); // } // var tradeSpans = new List(); // using (var db = new YLContext()) // { // if (!hasOptionInfo) // { // tradeBLL.SetFieldsByTradeType(futureTradeList); // } // var underlyingCodes = futureTradeList.Select(t => t.UnderlyingCode).ToHashSet(); // var mpProvider = new MarginParamProvider(new OptUserInfo(0, "系统"), settleDate).Initialize(underlyingCodes, MarginParamTypeEnum.MarginRate); // var overrideVolsForTrades = VolCaculator.Instance.GetVol(futureTradeList, settleDate); // var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(userId + "", settleDate, futureTradeList, priceDict, ValueCalculator.BASIC_GREEKS, null, isEodSettle, volType, overrideVolsForTrade: overrideVolsForTrades, isUseTradeVol: PS.Config.IsTradeVol, PreciseTimeMode: !isEodSettle); // logger.Info($"商品期货保证金计算,交易入:[{futureTradeList.Count}条],返回[{tradeRiskResult.Results.Count}],错误:{tradeRiskResult.ErrorMessage}"); // var alphaRate = valuedateBLL.SystemDate.FutureMarginAlphaRate ?? 1; // var FutureMarginAddRatio = valuedateBLL.SystemDate.FutureMarginAddRatio ?? 0; // //客户对应等级系数 // var clientIds = futureTradeList.Select(t => t.ClientId).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(); // if (tradeRiskResult.Results.Count > 0) // { // var underlyingCodeLookup = futureTradeList.ToLookup(t => new { t.UnderlyingId, t.ClientId }); // foreach (var trade in futureTradeList) // { // var closePrice = priceDict.ContainsKey(trade.UnderlyingId) ? priceDict[trade.UnderlyingId] : 0.0; // var optionValueList = tradeRiskResult.Results.Where(t => t.Trade.id == trade.id && t.ValueResult != null && t.Trade != null && !double.IsNaN(t.ValueResult.Delta) && !double.IsNaN(t.ValueResult.Vega) && !double.IsNaN(t.ValueResult.Gamma)).ToList(); // //未设置相关保证金系数默认为1.0 // var client = clientList.FirstOrDefault(c => c.client.id == trade.ClientId); // var clientRatio = client == null ? 1.0 : (client.clientlevel == null ? 1.0 : (client.clientlevel.Ratio ?? 1.0)); // var clientAddRatio = client == null ? 0.0 : (client.clientlevel == null ? 0.0 : (client.clientlevel.AddRatio ?? 0.0)); // if (optionValueList.Any()) // { // var deltaMerge = 0.0; // var deltaShort = optionValueList.Sum(t => t.ValueResult.Delta * (t.Trade.BuySell == "买入" ? 1 : 0)); // var deltaMax = optionValueList.Sum(t => t.ValueResult.DeltaMax * (t.Trade.BuySell == "买入" ? 1 : 0)); // //跨式组合和宽跨式组合用到的是组合交易里面的Max Delta作为deltaMerge参与保证金的计算 // deltaMerge = trade.TradeType == "结构化交易" && (trade.StructureType == "跨式组合" || trade.StructureType == "宽跨式组合") ? Math.Abs(deltaMax) : Math.Abs(deltaShort); // logger.Info("交易id为" + trade.id + "的delta:" + deltaMerge); // //if (deltaLong * deltaShort == 0) // //{ // // deltaMerge = Math.Abs(deltaShort); // //} // //else if (deltaLong * deltaShort < 0) // //{ // // if (Math.Abs(deltaLong) >= Math.Abs(deltaShort)) // // { // // deltaMerge = 0; // // } // // else // // { // // deltaMerge = Math.Abs(deltaShort) - Math.Abs(deltaLong); // // } // //} // //else // //{ // // deltaMerge = Math.Abs(deltaShort); // //} // mpProvider.TryGetMarginRate(trade.UnderlyingCode, out double marginRate); // //保证金 = (交易保证金率+公司保证金率加点)*合约名义金额(期货价格*数量)*delta // var value = deltaMerge * closePrice * (marginRate + FutureMarginAddRatio + clientAddRatio) * alphaRate * clientRatio; // if (trade.TradeType == "自定义交易") // { // var eodTradeRiskManual = db.eod_trade_risk_manual.Where(x => x.ValueDate <= settleDate && x.TradeId == trade.id).OrderByDescending(x => x.ValueDate).FirstOrDefault(); // //收盘时如果自定义交易还活着且没有维护当日风险,并且收的时系统日期当日的盘,抛出exception // if (isEodSettle && !ConsTrade.TradeCompleteStatus.Contains(trade.TradeStatus) && settleDate == valuedateBLL.SystemDate.ValueDate) // { // if (eodTradeRiskManual == null || eodTradeRiskManual.ValueDate != settleDate) // { // var error = $"TradeNumber:{trade.TradeNumber}在{settleDate.ToString("yyyy-MM-dd")}需先进行交易风险维护"; // throw new Exception(error); // } // } // value = eodTradeRiskManual?.Margin ?? 0; // } // tradeSpans.Add(new trade_span // { // TradeId = trade.id,//默认记录为第一条交易记录中 // OptDate = DateTime.Now, // OptId = userId, // OptName = userName, // ClientId = trade.ClientId, // ValueDate = settleDate, // UnderlyingId = trade.UnderlyingId, // UnderlyingCode = trade.UnderlyingCode, // Spv1 = value, // Spv2 = value, // Spv3 = value, // Spv4 = value, // WorstCastClientPayable = value, // Comment = $"标的{trade.UnderlyingCode},deltaMerge:{deltaMerge},closePrice:{closePrice},Margin:{marginRate},FutureMarginAddRatio:{FutureMarginAddRatio},clientAddRatio:{clientAddRatio},alphaRate:{alphaRate},clientRatio:{clientRatio}" // }); // } // else // { // var nanTradeValue = tradeRiskResult.Results.Where(t => t.Trade.id == trade.id && (double.IsNaN(t.ValueResult.Delta) || !double.IsNaN(t.ValueResult.Vega) || !double.IsNaN(t.ValueResult.Gamma))).Select(t => t.ValueResult).ToList(); // nanTradeValue.ForEach(optionValue => // { // logger.Error($"交易ID:{trade.UnderlyingId},Delta:{optionValue.Delta},DeltaCash{optionValue.DeltaCash},Vega{optionValue.Vega},Gamma:{optionValue.Gamma},vol:{optionValue.Vol}"); // }); // } // } // } // return tradeSpans; // } // } // public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false) // { // using (YLContext db = new YLContext()) // { // if (trade.TradeType == "结构化交易") // { // trade.SubTrades = db.trade.Where(x => x.ParentTradeId == trade.id).ToList(); // } // } // var tradeMargin = RunMarginCalculation(0, "系统", new List { trade }, isInitialMargin ? (trade.TradeDate ?? valuedateBLL.ValueDate) : valuedateBLL.ValueDate, new Dictionary { { trade.UnderlyingId, price } }, hasOptionInfo: hasOptionInfo); // if (null != tradeMargin) // { // return tradeMargin.FirstOrDefault()?.WorstCastClientPayable ?? 0.0; // } // return 0.0; // } // } //}