chore(swap): 删除全部期货公司定制保证金计算死代码——36个厂商类+东吴DongWu子目录+调度器四处厂商switch收敛Default直调+MarginTypeEnum三个不可达枚举项;连带YLErpUnitTest厂商类历史快照副本与4个厂商测试(3个零断言草稿/1个招证金标准)。本分支Company=国联无专属case,厂商路径本就永不执行;顺带消除Debug配置残留的格林大华#if DEBUG两处编译错误。-23231行,Release/Debug/UnitTestProject三处构建0错误
This commit is contained in:
@@ -1,81 +0,0 @@
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using YLErp.BLL.MarginCalculation;
|
||||
using YLErp.Modules.DataProviderModule;
|
||||
using GTJAMarginCalculationNew = YLErp.BLL.MarginCalculation.GTJAMarginCalculation;
|
||||
//using GTJAMarginCalculationOld = YLErp.BLL.MarginCalculationBak.GTJAMarginCalculation;
|
||||
|
||||
namespace YLErp.Modules.MarginModule
|
||||
{
|
||||
[TestClass]
|
||||
public class GTJAMarginTest : UnitTestBase
|
||||
{
|
||||
[TestMethod("国君保证金比较新方法和老方法")]
|
||||
public void TestOldNew()
|
||||
{
|
||||
var req = new RunMarginCalculationReq
|
||||
{
|
||||
forOtherSide = false,
|
||||
forSingleTrade = true,
|
||||
hasOptionInfo = false,
|
||||
//isEodSettle = false,
|
||||
//isInitialMargin = false,
|
||||
settleDate = DateTime.Today,
|
||||
userId = 1,
|
||||
userName = "系统用户",
|
||||
volType = "交易"
|
||||
};
|
||||
|
||||
using (var db = DbContextFactory.GetYLDbContext())
|
||||
{
|
||||
req.tradeList = db.trade.Where(n => n.id == 106969)
|
||||
.Where(t => t.ValidState != ConsGlobal.InValid && t.ClientId > 0
|
||||
&& t.TradeType != "结构化交易" && t.TradeStatus == "确认成交" && t.SpotPrice != null)
|
||||
.OrderByDescending(n => n.id).Take(100).ToList();
|
||||
}
|
||||
|
||||
var priceDic = new Dictionary<string, double>();
|
||||
|
||||
foreach (var t in req.tradeList)
|
||||
{
|
||||
if (!priceDic.ContainsKey(t.UnderlyingCode))
|
||||
{
|
||||
priceDic[t.UnderlyingCode] = t.SpotPrice.Value * 1.08;
|
||||
}
|
||||
}
|
||||
|
||||
req.PriceProvider = (ManualPriceProvider)priceDic;
|
||||
|
||||
var resultNew = GTJAMarginCalculationNew.Instance.RunMarginCalculation(req.Clone())
|
||||
.ToDictionary(n => n.TradeId);
|
||||
|
||||
//var resultOld = GTJAMarginCalculationOld.Instance.RunMarginCalculation(
|
||||
// req.userId, req.userName, req.tradeList, req.settleDate, priceDic, req.hasOptionInfo, req.isEodSettle, req.forOtherSide, req.volType, req.forOtherSide
|
||||
// );
|
||||
|
||||
//foreach (var ro in resultOld)
|
||||
//{
|
||||
// if (resultNew.TryGetValue(ro.TradeId, out var rn))
|
||||
// {
|
||||
// Console.WriteLine("trade id: " + ro.TradeId);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv1 ?? 0) - (rn.Spv1 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv2 ?? 0) - (rn.Spv2 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv3 ?? 0) - (rn.Spv3 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv4 ?? 0) - (rn.Spv4 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv5 ?? 0) - (rn.Spv5 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv6 ?? 0) - (rn.Spv6 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv7 ?? 0) - (rn.Spv7 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.Spv8 ?? 0) - (rn.Spv8 ?? 0)) < 1e-6);
|
||||
// Assert.IsTrue(Math.Abs((ro.WorstCastClientPayable ?? 0) - (rn.WorstCastClientPayable ?? 0)) < 1e-6);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Assert.Fail();
|
||||
// System.Diagnostics.Debug.WriteLine("没有取到新保证金");
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.Model;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 安粮
|
||||
// /// </summary>
|
||||
// public class ALQHMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly ALQHMarginCalculation Instance;
|
||||
|
||||
// static ALQHMarginCalculation()
|
||||
// {
|
||||
// Instance = new ALQHMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private ALQHMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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> tradeSpans = new List<trade_span>();
|
||||
// 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, priceDict, hasOptionInfo, 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 = tradeList.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;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 股票类期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> StockMarginCalculation(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false)
|
||||
// {
|
||||
// List<trade_span> tradeSpans = new List<trade_span>();
|
||||
// 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)
|
||||
// {
|
||||
// //未设置相关保证金系数默认为1.0
|
||||
// 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 : (PS.Config.ErpElement.TwoSideMargin && client.client.HasTwoSideMargin == 1 ? -1 : 0)) * clientRatio;
|
||||
// var twoSideMargin = (t.StockEqvNotional ?? (t.Notional * t.SpotPrice ?? 0.0)) * marginRation * (t.BuySell == "买入" ? 1 : -1) * clientRatio;
|
||||
// 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,
|
||||
// TwoSideMargin = twoSideMargin
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 商品期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> FutureMarginCalculation(int userId, string userName, List<trade> futureTradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, string volType = "交易")
|
||||
// {
|
||||
// var tradeSpans = new List<trade_span>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(futureTradeList);
|
||||
// }
|
||||
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(userId + "", settleDate, futureTradeList, priceDict, ValueCalculator.BASIC_GREEKS, null, isEodSettle, volType, isUseTradeVol: PS.Config.IsTradeVol, PreciseTimeMode: !isEodSettle);
|
||||
// var deltaCoefficient = valuedateBLL.SystemDate.FutureMarginDeltaCoefficient ?? 1;
|
||||
// var vegaCoefficient = valuedateBLL.SystemDate.FutureMarginVegaCoefficient ?? 3;
|
||||
// var omegaCoefficient = valuedateBLL.SystemDate.FutureMarginOmegaCoefficient ?? 2.5;
|
||||
// var alphaRate = valuedateBLL.SystemDate.FutureMarginAlphaRate ?? 1;
|
||||
// //客户对应等级系数
|
||||
// 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();
|
||||
|
||||
// foreach (var item in tradeRiskResult.Results)
|
||||
// {
|
||||
// var tempTrade = futureTradeList.FirstOrDefault(t => t.id == item.Trade.id);
|
||||
// var optionValue = item.ValueResult;
|
||||
// var tempVariety = _underlyingDataProvider.GetVariety(tempTrade.UnderlyingId);
|
||||
// var closePrice = priceDict.ContainsKey(tempTrade.UnderlyingId) ? priceDict[tempTrade.UnderlyingId] : 0.0;
|
||||
// var client = clientList.FirstOrDefault(c => c.client.id == item.Trade.ClientId);
|
||||
// if (tempTrade != null && item.ValueResult != null && tempVariety != null)
|
||||
// {
|
||||
// //未设置相关保证金系数默认为1.0
|
||||
// var clientRatio = client == null ? 1.0 : (client.clientlevel == null ? 1.0 : (client.clientlevel.Ratio ?? 1.0));
|
||||
// //保证金 = ( a * DeltaCash + b* GammaCash * PricingVol / 16) * 当前标的保证金率 + c * Vega
|
||||
// var value = ((optionValue.DeltaCash * deltaCoefficient
|
||||
// + optionValue.GammaCash * 0.01 * (optionValue.Vol / 16) * omegaCoefficient) * tempVariety.Margin
|
||||
// + optionValue.Vega * vegaCoefficient
|
||||
// ) * alphaRate * (tempTrade.BuySell == "买入" ? 1 : (PS.Config.ErpElement.TwoSideMargin && client.client.HasTwoSideMargin == 1 ? 1 : 0)) * clientRatio;
|
||||
// var twoSideMargin = ((optionValue.DeltaCash * deltaCoefficient
|
||||
// + optionValue.GammaCash * 0.01 * (optionValue.Vol / 16) * omegaCoefficient) * tempVariety.Margin
|
||||
// + optionValue.Vega * vegaCoefficient
|
||||
// ) * alphaRate * (tempTrade.BuySell == "买入" ? 1 : -1) * clientRatio;
|
||||
// tradeSpans.Add(new trade_span
|
||||
// {
|
||||
// TradeId = tempTrade.id,
|
||||
// OptDate = DateTime.Now,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// ClientId = tempTrade.ClientId,
|
||||
// UnderlyingId = tempTrade.UnderlyingId,
|
||||
// UnderlyingCode = tempTrade.UnderlyingCode,
|
||||
// ValueDate = settleDate,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value,
|
||||
// TwoSideMargin = twoSideMargin
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// }
|
||||
|
||||
// public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,415 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.BLL.Eod;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 渤海荣盛
|
||||
// /// </summary>
|
||||
// public class BHRSMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly BHRSMarginCalculation Instance;
|
||||
|
||||
// static BHRSMarginCalculation()
|
||||
// {
|
||||
// Instance = new BHRSMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private BHRSMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// public override bool MarginCalcNeedSpecial
|
||||
// {
|
||||
// get
|
||||
// {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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> tradeSpans = new List<trade_span>();
|
||||
// if (tradeList != null && tradeList.Count > 0)
|
||||
// {
|
||||
// if (!(priceDict?.Count > 0))
|
||||
// {
|
||||
// var codes = tradeList.Select(O => O.UnderlyingCode).ToArray();
|
||||
// priceDict = base.GetSettlePrice(codes, settleDate);
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// var tempStockTradeList = tradeList.Where(t => t.UnderlyingInstrumentType == ConsGlobal.InstrumentType.Stock).ToList();
|
||||
// if (tempStockTradeList.Any())
|
||||
// {
|
||||
// var stockTradeSpanlist = StockMarginCalculation(userId, userName, tempStockTradeList, settleDate, priceDict, hasOptionInfo, isEodSettle);
|
||||
// if (stockTradeSpanlist.Count > 0)
|
||||
// {
|
||||
// tradeSpans.AddRange(stockTradeSpanlist);
|
||||
// }
|
||||
// }
|
||||
// var tempFutureTradeList = tradeList.Where(t => t.UnderlyingInstrumentType == ConsGlobal.InstrumentType.CommodityFutures).ToList();
|
||||
// if (tempFutureTradeList.Any())
|
||||
// {
|
||||
// if (forSingleTrade)
|
||||
// {
|
||||
// var futureTradeSpanlist = FutureMarginCalculationForSingleTrade(userId, userName, tempFutureTradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, volType);
|
||||
// if (futureTradeSpanlist.Count > 0)
|
||||
// {
|
||||
// tradeSpans.AddRange(futureTradeSpanlist);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// var futureTradeSpanlist = FutureMarginCalculation(userId, userName, tempFutureTradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, volType);
|
||||
// if (futureTradeSpanlist.Count > 0)
|
||||
// {
|
||||
// tradeSpans.AddRange(futureTradeSpanlist);
|
||||
// }
|
||||
// }
|
||||
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 股票类期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> StockMarginCalculation(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false)
|
||||
// {
|
||||
// List<trade_span> tradeSpans = new List<trade_span>();
|
||||
// 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 : (PS.Config.ErpElement.TwoSideMargin && client.client.HasTwoSideMargin == 1 ? -1 : 0)) * clientRatio;
|
||||
// var twoSideMargin = (t.StockEqvNotional ?? (t.Notional * t.SpotPrice ?? 0.0)) * marginRation * (t.BuySell == "买入" ? 1 : -1) * 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;
|
||||
// twoSideMargin = 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,
|
||||
// TwoSideMargin = twoSideMargin
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 商品期权计算保证金 OLD
|
||||
// /// </summary>
|
||||
// public List<trade_span> FutureMarginCalculation(int userId, string userName, List<trade> futureTradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, string volType = "交易")
|
||||
// {
|
||||
// //
|
||||
// List<trade_span> tradeSpans = new List<trade_span>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(futureTradeList);
|
||||
// }
|
||||
|
||||
// var futureManualTradeList = futureTradeList.Where(x => x.TradeType == "自定义交易");
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(userId + "", settleDate, futureTradeList, priceDict, ValueCalculator.BASIC_GREEKS, null, isEodSettle, volType, isUseTradeVol: PS.Config.IsTradeVol, PreciseTimeMode: !isEodSettle);
|
||||
// logger.Info($"商品期货保证金计算,交易入:[{futureTradeList.Count}条],返回[{tradeRiskResult.Results.Count}],错误:{tradeRiskResult.ErrorMessage}");
|
||||
// //计算保证金包含错误信息时弹出错误信息
|
||||
// if (!string.IsNullOrWhiteSpace(tradeRiskResult.ErrorMessage))
|
||||
// {
|
||||
// throw new Exception(tradeRiskResult.ErrorMessage);
|
||||
// }
|
||||
// var vegaCoefficient = valuedateBLL.SystemDate.FutureMarginVegaCoefficient ?? 3;
|
||||
// var omegaCoefficient = valuedateBLL.SystemDate.FutureMarginOmegaCoefficient ?? 2.5;
|
||||
// var alphaRate = valuedateBLL.SystemDate.FutureMarginAlphaRate ?? 1;
|
||||
// //客户对应等级系数
|
||||
// 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 item in underlyingCodeLookup)
|
||||
// {
|
||||
// var tempTrades = item.ToList();
|
||||
// var tradeIds = tempTrades.Select(t => t.id).ToList();
|
||||
// var tempVariety = _underlyingDataProvider.GetVariety(item.Key.UnderlyingId);
|
||||
// var closePrice = priceDict.ContainsKey(item.Key.UnderlyingId) ? priceDict[item.Key.UnderlyingId] : 0.0;
|
||||
// var optionValueList = tradeRiskResult.Results.Where(t => tradeIds.Contains(t.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 == item.Key.ClientId);
|
||||
// var clientRatio = client == null ? 1.0 : (client.clientlevel == null ? 1.0 : (client.clientlevel.Ratio ?? 1.0));
|
||||
|
||||
// if (optionValueList.Any() && tempVariety != null)
|
||||
// {
|
||||
// var optionValueListWithOutManual = optionValueList.Where(x => x.Trade.TradeType != "自定义交易");
|
||||
// var deltaMerge = 0.0;
|
||||
// var deltaLong = optionValueListWithOutManual.Sum(t => (t.ValueResult.Delta) * (t.Trade.BuySell == "卖出" ? 1 : 0));
|
||||
// var deltaShort = optionValueListWithOutManual.Sum(t => (t.ValueResult.Delta) * (t.Trade.BuySell == "买入" ? 1 : 0));
|
||||
// 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);
|
||||
// }
|
||||
// var vegaMerge = Math.Max(optionValueListWithOutManual.Sum(t => Math.Abs(t.ValueResult.Vega) * EodOperationBase.GetSign(t.Trade.BuySell)), 0);
|
||||
// var gammaMerge = Math.Max(optionValueListWithOutManual.Sum(t => Math.Abs(t.ValueResult.Gamma) * EodOperationBase.GetSign(t.Trade.BuySell)), 0);
|
||||
// //保证金 = SUM((DELTA值 * 数量 * 标的资产收盘价)场内期权保证金率 + Vega值 * 数量 * 0.01 * 3 + Gamma金额 * vol / 16 * 2.5 场内期权保证金率)
|
||||
// var value = ((deltaMerge * closePrice) * (tempVariety.Margin)
|
||||
// + vegaMerge * 0.01 * vegaCoefficient
|
||||
// + gammaMerge * Math.Pow(closePrice, 2) * 0.01 * (optionValueListWithOutManual.First().ValueResult.Vol / 16) * omegaCoefficient * tempVariety.Margin
|
||||
// ) * alphaRate * clientRatio;
|
||||
|
||||
// //如果非自定义交易的保证金为负,会将其算作0,再加上自定义交易的保证金,算出总和,会使得得到的保证金高于实际保证金(暂时理解为对客户有利,不做处理)
|
||||
// if (futureManualTradeList.Any())
|
||||
// {
|
||||
// var manualTradeIds = futureManualTradeList.Select(x => x.id);
|
||||
// var eodTradeRiskManuals = db.eod_trade_risk_manual.Where(x => manualTradeIds.Contains(x.id) && x.ValueDate <= settleDate).OrderByDescending(x => x.ValueDate);
|
||||
|
||||
// foreach (var riskManual in eodTradeRiskManuals)
|
||||
// {
|
||||
// var trade = futureManualTradeList.FirstOrDefault(x => x.id == riskManual.TradeId);
|
||||
// if (trade != null)
|
||||
// {
|
||||
// value += riskManual.Margin * EodOperationBase.GetSign(trade.BuySell);
|
||||
// }
|
||||
// }
|
||||
// value = Math.Max(value ?? 0, 0);
|
||||
// }
|
||||
|
||||
// tradeSpans.Add(new trade_span
|
||||
// {
|
||||
// TradeId = tempTrades.First().id,//默认记录为第一条交易记录中
|
||||
// OptDate = DateTime.Now,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// ClientId = item.Key.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = item.Key.UnderlyingId,
|
||||
// UnderlyingCode = tempTrades.First().UnderlyingCode,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value,
|
||||
// Comment = $"标的{tempTrades.First().UnderlyingCode} 合计计算:{string.Join(",", tempTrades.Select(t => t.id).ToList())}"
|
||||
// });
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// var nanTradeValue = tradeRiskResult.Results.Where(t => tradeIds.Contains(t.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:{item.Key.UnderlyingId},Delta:{optionValue.Delta},DeltaCash{optionValue.DeltaCash},Vega{optionValue.Vega},Gamma:{optionValue.Gamma},vol:{optionValue.Vol}");
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 商品期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> FutureMarginCalculationForSingleTrade(int userId, string userName, List<trade> futureTradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, string volType = "交易")
|
||||
// {
|
||||
// //
|
||||
// List<trade_span> tradeSpans = new List<trade_span>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(futureTradeList);
|
||||
// }
|
||||
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(userId + "", settleDate, futureTradeList, priceDict, ValueCalculator.BASIC_GREEKS, null, isEodSettle, volType, isUseTradeVol: PS.Config.IsTradeVol, PreciseTimeMode: !isEodSettle);
|
||||
// logger.Info($"商品期货保证金计算,交易入:[{futureTradeList.Count}条],返回[{tradeRiskResult.Results.Count}],错误:{tradeRiskResult.ErrorMessage}");
|
||||
// //计算保证金包含错误信息时弹出错误信息
|
||||
// if (!string.IsNullOrWhiteSpace(tradeRiskResult.ErrorMessage))
|
||||
// {
|
||||
// throw new Exception(tradeRiskResult.ErrorMessage);
|
||||
// }
|
||||
// var vegaCoefficient = valuedateBLL.SystemDate.FutureMarginVegaCoefficient ?? 3;
|
||||
// var omegaCoefficient = valuedateBLL.SystemDate.FutureMarginOmegaCoefficient ?? 2.5;
|
||||
// var alphaRate = valuedateBLL.SystemDate.FutureMarginAlphaRate ?? 1;
|
||||
// //客户对应等级系数
|
||||
// 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 item in tradeRiskResult.Results)
|
||||
// {
|
||||
// var tempVariety = _underlyingDataProvider.GetVariety(item.Trade.UnderlyingId);
|
||||
// var closePrice = priceDict.ContainsKey(item.Trade.UnderlyingId) ? priceDict[item.Trade.UnderlyingId] : 0.0;
|
||||
|
||||
// //未设置相关保证金系数默认为1.0
|
||||
// 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));
|
||||
|
||||
// var deltaMerge = item.ValueResult.Delta;
|
||||
// var vegaMerge = item.ValueResult.Vega;
|
||||
// var gammaMerge = item.ValueResult.Gamma;
|
||||
// //保证金 = SUM((DELTA值 * 数量 * 标的资产收盘价)场内期权保证金率 + Vega值 * 数量 * 0.01 * 3 + Gamma金额 * vol / 16 * 2.5 场内期权保证金率)
|
||||
// var value = ((deltaMerge * closePrice) * (tempVariety.Margin ?? 0.0)
|
||||
// + vegaMerge * 0.01 * vegaCoefficient
|
||||
// + gammaMerge * Math.Pow(closePrice, 2) * 0.01 * (item.ValueResult.Vol / 16) * omegaCoefficient * (tempVariety.Margin ?? 0.0)
|
||||
// ) * alphaRate * clientRatio;
|
||||
|
||||
// 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;
|
||||
// }
|
||||
|
||||
// tradeSpans.Add(new trade_span
|
||||
// {
|
||||
// TradeId = item.Trade.id,//默认记录为第一条交易记录中
|
||||
// OptDate = DateTime.Now,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// ClientId = item.Trade.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = item.Trade.UnderlyingId,
|
||||
// UnderlyingCode = item.Trade.UnderlyingCode,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value,
|
||||
// Comment = $"delta:{deltaMerge},closePrice:{closePrice},vega:{vegaMerge},gamma{gammaMerge},buySell:{item.Trade.BuySell}"
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// }
|
||||
|
||||
// public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// using (var db = new YLContext())
|
||||
// {
|
||||
// if (trade.TradeType == "结构化交易")
|
||||
// {
|
||||
// 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,477 +0,0 @@
|
||||
//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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,338 +0,0 @@
|
||||
//using BaseOUDAL;
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.BLL.Eod;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.Modules.DataCacheModule;
|
||||
//using YLErp.Modules.TradeDalModule;
|
||||
//using YLErp.Modules.VolatilityModule;
|
||||
//using YLErp.QdpModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 方顿
|
||||
// /// </summary>
|
||||
// public class FDMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly FDMarginCalculation Instance;
|
||||
|
||||
// static FDMarginCalculation()
|
||||
// {
|
||||
// Instance = new FDMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private FDMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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> tradeSpans = new List<trade_span>();//结果集
|
||||
// if (!(priceDict?.Count > 0))
|
||||
// {
|
||||
// var codes = tradeList.Select(O => O.UnderlyingCode).ToArray();
|
||||
// priceDict = base.GetSettlePrice(codes, settleDate);
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(tradeList);
|
||||
// }
|
||||
|
||||
// var lastSettleDate = EodOperationBase.GetLastSettlementDate(settleDate, true);
|
||||
// var tradeIds = tradeList.Select(t => t.id).ToList();
|
||||
// var tradeMetaDatas = db.TradeMeta.Where(m => tradeIds.Contains(m.TradeId)).ToList().GroupBy(t => t.TradeId).ToDictionary(g => g.Key, g => g.ToDictionary(m => m.MetaKey, m => m.MetaValue));
|
||||
// var positionMaginRatioDic = db.TradeMeta.Where(m => tradeIds.Contains(m.TradeId) && m.MetaKey == ConsTradeMetaKey.PositionMarginRate)
|
||||
// .ToList().ToDictionary(m => m.TradeId, m => DataConvert.ToDouble(m.MetaValue));
|
||||
|
||||
// new TradeDalService(new OptUserInfo(userId, userName)).SetSubTradeList(tradeList);
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(userId + "", settleDate, tradeList, priceDict, ValueCalculator.BASIC_PRICING, null, isEodSettle, volType, isUseTradeVol: PS.Config.IsTradeVol);
|
||||
// logger.Info($"商品期货保证金计算,交易入:[{tradeList.Count}条],返回[{tradeRiskResult.Results.Count}],错误:{tradeRiskResult.ErrorMessage}");
|
||||
|
||||
// //客户对应等级系数
|
||||
// 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 (!string.IsNullOrWhiteSpace(tradeRiskResult.ErrorMessage))
|
||||
// {
|
||||
// throw new ServiceException(tradeRiskResult.ErrorMessage);
|
||||
// }
|
||||
// if (tradeRiskResult.Results.Count > 0)
|
||||
// {
|
||||
// var lastTradeSpanList = db.trade_span.Where(s => s.ValueDate == lastSettleDate).ToList();
|
||||
// foreach (var item in tradeRiskResult.Results)
|
||||
// {
|
||||
// var client = clientList.FirstOrDefault(c => c.client.id == item.Trade.ClientId);
|
||||
|
||||
// Dictionary<string, string> metaDics = null;
|
||||
// if (tradeMetaDatas.ContainsKey(item.Trade.id))
|
||||
// {
|
||||
// metaDics = tradeMetaDatas[item.Trade.id];
|
||||
// }
|
||||
// #region 维持保证金率
|
||||
// var positionMaginRatio = 0.0;
|
||||
// if (metaDics != null && metaDics.ContainsKey(ConsTradeMetaKey.PositionMarginRate))
|
||||
// {
|
||||
// positionMaginRatio = DataConvert.ToDouble(metaDics[ConsTradeMetaKey.PositionMarginRate]);
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region 当前保证金额
|
||||
// var cashDeposit = 0.0;
|
||||
// var lastTradeSpan = lastTradeSpanList.FirstOrDefault(s => s.TradeId == item.Trade.id);
|
||||
// if (lastTradeSpan != null)
|
||||
// {
|
||||
// cashDeposit = (lastTradeSpan.CashDeposit ?? 0) + (lastTradeSpan.Margin ?? 0);
|
||||
// }
|
||||
// else if (metaDics != null && metaDics.ContainsKey(ConsTradeMetaKey.InitialMarginMoney))
|
||||
// {
|
||||
// cashDeposit = DataConvert.ToDouble(metaDics[ConsTradeMetaKey.InitialMarginMoney]);
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// var value = Math.Abs(item.ValueResult.DeltaCash) * positionMaginRatio * (item.Trade.BuySell == "买入" ? 1 : (PS.Config.ErpElement.TwoSideMargin && client.client.HasTwoSideMargin == 1 ? -1 : 0));
|
||||
// var twoSideMargin = Math.Abs(item.ValueResult.DeltaCash) * positionMaginRatio * (item.Trade.BuySell == "买入" ? 1 : -1);
|
||||
|
||||
// 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:yyyy-MM-dd}需先进行交易风险维护";
|
||||
// throw new Exception(error);
|
||||
// }
|
||||
// }
|
||||
|
||||
// value = eodTradeRiskManual?.Margin ?? 0;
|
||||
// twoSideMargin = eodTradeRiskManual?.Margin ?? 0;
|
||||
// }
|
||||
|
||||
// #region 风险敞口
|
||||
// var riskExposure = 0.0;
|
||||
// if (item.Trade.BuySell == "买入")
|
||||
// {
|
||||
// //这个地方很诡异,GetAsianFinalPrice和ActualStrike使用了相同的逻辑取均价,不同的地方在于ActualStrike使用的是系统日期,但这样又会造成历史收盘的偏差
|
||||
// riskExposure = Math.Max(0, (trade_asian_optionBLL.GetAsianFinalPrice(item.Trade, settleDate) - item.Trade.ActualStrike ?? 0) * (item.Trade.OptionType == "看涨" ? 1 : -1)) * item.Trade.Notional;
|
||||
// }
|
||||
// #endregion
|
||||
// //是否需要追保
|
||||
// var needMargin = (riskExposure - cashDeposit) > 0;
|
||||
|
||||
// tradeSpans.Add(new trade_span
|
||||
// {
|
||||
// TradeId = item.Trade.id,//默认记录为第一条交易记录中
|
||||
// OptDate = DateTime.Now,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// ClientId = item.Trade.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = item.Trade.UnderlyingId,
|
||||
// UnderlyingCode = item.Trade.UnderlyingCode,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value,
|
||||
// TwoSideMargin = twoSideMargin,
|
||||
// RiskExposure = riskExposure,
|
||||
// CashDeposit = cashDeposit,
|
||||
// Margin = needMargin ? (riskExposure - cashDeposit + Math.Max(value, 0)) : 0,
|
||||
// Comment = $"DeltaCash:{item.ValueResult.DeltaCash},PositionMaginRatio:{positionMaginRatio}"
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取初始保证金率
|
||||
// /// </summary>
|
||||
// /// <param name="trade"></param>
|
||||
// /// <returns></returns>
|
||||
// public double? GetInitialMarginRatio(trade trade)
|
||||
// {
|
||||
// if (trade == null)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
// if (!trade.VarietyId.HasValue || trade.VarietyId <= 0)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
// if (!trade.StockEqvNotional.HasValue)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
// var variety = DataCacheManager.GetVarietyDataSource().GetData(trade.VarietyId ?? 0);
|
||||
// if (variety == null)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
// //OTC-8856 Start
|
||||
// var UpLimitValue = variety.UpLimitValue;
|
||||
// //var UpLimitValue =((Math.Abs(trade.Underlying.UpDownLimitValue) > 1e-5) ? trade.Underlying.UpDownLimitValue : variety.UpLimitValue);
|
||||
// //End
|
||||
|
||||
// if (trade.StockEqvNotional <= 5000000)
|
||||
// {
|
||||
// return 2 * UpLimitValue;
|
||||
// }
|
||||
// else if (trade.StockEqvNotional <= 10000000)
|
||||
// {
|
||||
// return 2.5 * UpLimitValue;
|
||||
// }
|
||||
// else if (trade.StockEqvNotional <= 20000000)
|
||||
// {
|
||||
// return 3 * UpLimitValue;
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取维持保证金率
|
||||
// /// </summary>
|
||||
// /// <param name="trade"></param>
|
||||
// /// <returns></returns>
|
||||
// public double? GetPositionMarginRatio(trade trade)
|
||||
// {
|
||||
// if (trade == null)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
// if (!trade.VarietyId.HasValue || trade.VarietyId <= 0)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
// if (!trade.StockEqvNotional.HasValue)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
// //underlying_manager
|
||||
|
||||
|
||||
// var variety = DataCacheManager.GetVarietyDataSource().GetData(trade.VarietyId ?? 0);
|
||||
// if (variety == null)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
// if (trade.StockEqvNotional <= 5000000)
|
||||
// {
|
||||
// return 1.5 * variety.UpLimitValue;
|
||||
// }
|
||||
// else if (trade.StockEqvNotional <= 10000000)
|
||||
// {
|
||||
// return 2 * variety.UpLimitValue;
|
||||
// }
|
||||
// else if (trade.StockEqvNotional <= 20000000)
|
||||
// {
|
||||
// return 2.5 * variety.UpLimitValue;
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取初始保证金
|
||||
// /// </summary>
|
||||
// /// <param name="trade"></param>
|
||||
// /// <returns></returns>
|
||||
// public double GetInitialMargin(trade trade)
|
||||
// {
|
||||
// return DoInitialMarginCalculationV2(trade);
|
||||
// }
|
||||
|
||||
// public double DoInitialMarginCalculationV2(trade trade)
|
||||
// {
|
||||
// if (trade.BuySell == "卖出")
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
// var underlying = DataCacheManager.GetUnderlyingDataSource().GetData(trade.UnderlyingId);
|
||||
// underlying.QuotationDate = trade.TradeDate;
|
||||
|
||||
// var spotPrices = new double[] { trade.SpotPrice ?? 0 };
|
||||
|
||||
// string userGroup = UserBLL.GetUserGroup(trade.TraderId ?? 0);
|
||||
// var volSurfaceData = VolatilityHelper.GetVol(underlying.QuotationDate.Value, "交易", underlying.UnderlyingCode, userGroup);
|
||||
|
||||
// var vol = OptionCalculator.GetInterpolatedVol(
|
||||
// VolConstructionType.Normal,
|
||||
// trade.OptId.ToString(),
|
||||
// volSurfaceData,
|
||||
// underlying.QuotationDate?.ToString("yyyy-MM-dd"),
|
||||
// underlying.UnderlyingCode,
|
||||
// trade.ExerciseDate?.ToString("yyyy-MM-dd"),
|
||||
// trade.Strike ?? 0.0,
|
||||
// isBuy: true,
|
||||
// isCall: trade.CallPut == "Call",
|
||||
// spotPrice: spotPrices[0],
|
||||
// isMoneynessOption: trade.IsMoneynessOptionData,
|
||||
// timeToMaturityDays: trade.TTMDays ?? double.NaN);
|
||||
|
||||
// if (!trade.NoRiskRate.HasValue)
|
||||
// {
|
||||
// trade.NoRiskRate = (valuedateBLL.SystemDate.RiskFreeRate ?? 0) * 0.01;
|
||||
// }
|
||||
|
||||
// string fixing = null;
|
||||
// //亚式期权
|
||||
// if (trade.TradeType == "亚式期权" || trade.StructureType == "亚式熊市价差")
|
||||
// {
|
||||
// fixing = CalculatorHelper.GetFixingStringForAsianOption(trade, trade.TradeDate);
|
||||
// }
|
||||
// var optionValue = ValueCalculator.GetOptionValueResultV2(
|
||||
// trade.OptId.ToString(),
|
||||
// underlying,
|
||||
// trade,
|
||||
// new double[] { vol },
|
||||
// spotPrices,
|
||||
// fixing,
|
||||
// commodityFuturesPreciseTimeMode: true);
|
||||
// //保证金初始价值=期初期权价值+CashDelta(t)*保证金初始比例(保证金初始比例)
|
||||
// return (trade.TradePrice ?? 0) + ((optionValue == null) ? 0 : Math.Abs(optionValue.DeltaCash)) * (trade.InitialMarginRatio ?? 0);
|
||||
// }
|
||||
|
||||
// public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,608 +0,0 @@
|
||||
//using BaseOUDAL;
|
||||
//using Qdp.Foundation.Implementations;
|
||||
//using Qdp.Pricing.Base.Implementations;
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.Commons;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.Modules.DataCacheModule;
|
||||
//using YLErp.Modules.VolatilityModule;
|
||||
//using YLErp.Modules.VolatilityModule.SkewMapVolModule;
|
||||
//using YLErp.QdpModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// public class GDGZMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例(单例模式)
|
||||
// public static readonly GDGZMarginCalculation Instance;
|
||||
|
||||
// static GDGZMarginCalculation()
|
||||
// {
|
||||
// Instance = new GDGZMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private GDGZMarginCalculation()
|
||||
// {
|
||||
|
||||
// }
|
||||
|
||||
// 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)
|
||||
// {
|
||||
// //结果集
|
||||
// Dictionary<int, trade_span> resultMap = new Dictionary<int, trade_span>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// //为了算客户角度的一个保证金数值
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// tradeList.ForEach(x => x.BuySell = x.BuySell == "买入" ? "卖出" : "买入");
|
||||
// }
|
||||
// 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 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;
|
||||
// }
|
||||
|
||||
// //2.涨跌停板幅度
|
||||
// if (!string.IsNullOrWhiteSpace(t.UpDownLimit))
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.UpDownLimit;//百分比或绝对值
|
||||
// DownLimitDict[t.id] = t.UpDownLimit;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.defUpLimit?.ToString() ?? "5%";
|
||||
// DownLimitDict[t.id] = t.defDownLimit?.ToString() ?? "5%";
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(tradeList);
|
||||
// }
|
||||
|
||||
// var tradeVolatilityRateDic = tradeList.ToDictionary(t => t.id, t => umVolatilityRateDic.ContainsKey(t.UnderlyingId) ? umVolatilityRateDic[t.UnderlyingId] : 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>();
|
||||
// double tempDouble;
|
||||
// //根据涨跌幅限制以及当日结算价计算涨停价以及跌停价
|
||||
// foreach (var t in priceDict)
|
||||
// {
|
||||
// //OTC-8856 Start
|
||||
// //UpLimit
|
||||
// if (UpLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = UpLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// upLimitPrices[t.Key] = t.Value * (1 + (tempDouble * 0.01));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// upLimitPrices[t.Key] = t.Value + Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// upLimitPrices[t.Key] = t.Value * 1.05;
|
||||
// }
|
||||
|
||||
// //DownLimit
|
||||
// if (DownLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = DownLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// downLimitPrices[t.Key] = t.Value * (1 - (tempDouble * 0.01));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// downLimitPrices[t.Key] = t.Value - Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// downLimitPrices[t.Key] = t.Value * 0.95;
|
||||
// }
|
||||
// //End
|
||||
// }
|
||||
// eodPriceDict["up"] = upLimitPrices;
|
||||
// eodPriceDict["down"] = downLimitPrices;
|
||||
|
||||
// //波动率变化
|
||||
// var addVolRateList = new List<Dictionary<int, double>> { null, tradeVolatilityRateDic };
|
||||
|
||||
// //交易对应客户信息
|
||||
// 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();
|
||||
|
||||
// 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));
|
||||
|
||||
// var noMinusPv = !PS.Config.ErpElement.TwoSideMargin || client == null || client.client == null || client.client.HasTwoSideMargin != 1;
|
||||
|
||||
// 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":
|
||||
// resultMap[item.Trade.id].Spv1 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_1":
|
||||
// resultMap[item.Trade.id].Spv2 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_0":
|
||||
// resultMap[item.Trade.id].Spv3 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// resultMap[item.Trade.id].Spv4 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// //非双向保证金,pv为负的情况置为0
|
||||
// if (noMinusPv)
|
||||
// {
|
||||
// resultMap[item.Trade.id].Spv1 = Math.Max(resultMap[item.Trade.id].Spv1 ?? 0, 0);
|
||||
// resultMap[item.Trade.id].Spv2 = Math.Max(resultMap[item.Trade.id].Spv2 ?? 0, 0);
|
||||
// resultMap[item.Trade.id].Spv3 = Math.Max(resultMap[item.Trade.id].Spv3 ?? 0, 0);
|
||||
// resultMap[item.Trade.id].Spv4 = Math.Max(resultMap[item.Trade.id].Spv4 ?? 0, 0);
|
||||
// }
|
||||
// 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":
|
||||
// tempTradeSpan.Spv1 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_1":
|
||||
// tempTradeSpan.Spv2 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_0":
|
||||
// tempTradeSpan.Spv3 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// tempTradeSpan.Spv4 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// //非双向保证金,pv为负的情况置为0
|
||||
// if (noMinusPv)
|
||||
// {
|
||||
// tempTradeSpan.Spv1 = Math.Max(tempTradeSpan.Spv1 ?? 0, 0);
|
||||
// tempTradeSpan.Spv2 = Math.Max(tempTradeSpan.Spv2 ?? 0, 0);
|
||||
// tempTradeSpan.Spv3 = Math.Max(tempTradeSpan.Spv3 ?? 0, 0);
|
||||
// tempTradeSpan.Spv4 = Math.Max(tempTradeSpan.Spv4 ?? 0, 0);
|
||||
// }
|
||||
// resultMap[item.Trade.id] = tempTradeSpan;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// //上面的计算用到静态生成market,需要清除
|
||||
// QdpMarketManager.Instance.RemovePrebuiltMarketProxy(userIdNew);
|
||||
// }
|
||||
|
||||
// //为了保持原有交易买卖方向不变
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// tradeList.ForEach(x => x.BuySell = x.BuySell == "买入" ? "卖出" : "买入");
|
||||
// }
|
||||
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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
|
||||
// {
|
||||
// UnderlyingId = t.Key,
|
||||
// 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)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0);
|
||||
|
||||
// item.TwoSideMargin = Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0);
|
||||
|
||||
// #region 更新tradeSpan,使得每笔交易的持仓保证金和客户保证金计算用的Spv组保持一致
|
||||
|
||||
// var tradeSpansUpdate = db.trade_span.Where(x => x.ClientId == item.ClientId && x.UnderlyingId == item.UnderlyingId && x.ValueDate == settleDate).ToList();
|
||||
// if (item.WorstCastClientPayable == item.Spv1)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv1);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv2)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv2);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv3)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv3);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv4);
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// if (!PS.Config.ErpElement.TwoSideMargin || clientList.FirstOrDefault(x => x.id == clientGroup.Key) == null || clientList.FirstOrDefault(x => x.id == clientGroup.Key).HasTwoSideMargin != 1)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(item.WorstCastClientPayable.Value, 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)
|
||||
// {
|
||||
// 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> { 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;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取初始保证金
|
||||
// /// </summary>
|
||||
// public double GetInitialMargin(trade trade)
|
||||
// {
|
||||
// return DoInitialMarginCalculationV2(trade);
|
||||
// }
|
||||
|
||||
// public double DoInitialMarginCalculationV2(trade trade)
|
||||
// {
|
||||
// if (trade.BuySell == "卖出")
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
// //string userId = "0";
|
||||
|
||||
// var underlying = DataCacheManager.GetUnderlyingDataSource().GetData(trade.UnderlyingId);
|
||||
// var under = underlying.Clone();
|
||||
// under.QuotationDate = trade.TradeDate;
|
||||
// var variety = DataCacheManager.GetVarietyDataSource().GetData(under.UnderlyingTypeId);
|
||||
// double clientRatio = 1;
|
||||
// if (trade.ClientId > 0)
|
||||
// {
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// var query = from c in db.client
|
||||
// join cl in db.clientlevel on c.LevelId equals cl.id
|
||||
// where c.id == trade.ClientId
|
||||
// select cl.Ratio;
|
||||
// clientRatio = query.FirstOrDefault() ?? 1;
|
||||
// }
|
||||
// }
|
||||
|
||||
// if (PS.Config.IsTradeVol)
|
||||
// {
|
||||
// //如果没有开仓波动率,则调用接口计算出一个开仓波动率
|
||||
// if (trade.TradeOpenVolatility == null || trade.TradeOpenVolatility == 0)
|
||||
// {
|
||||
|
||||
// string userGroup = UserBLL.GetUserGroup(trade.TraderId ?? 0);
|
||||
// var vol = VolatilityHelper.GetVol(
|
||||
// trade.TradeDate.Value,
|
||||
// "交易",
|
||||
// under.UnderlyingCode,
|
||||
// userGroup);
|
||||
// var baseVol = BaseVolService.GetBaseVol(new BaseVolReq(under, trade), trade.TraderId ?? 0);
|
||||
// var skewvol = new SkewVolReq
|
||||
// {
|
||||
// AskVar = vol.GetAskVar(),
|
||||
// BidVar = vol.GetBidVar(),
|
||||
// BaseVol = baseVol
|
||||
// };
|
||||
// trade.TradeOpenVolatility = SingleVolService.GetSingleVol(new SingleVolReq(trade, under, skewvol), trade.TraderId ?? 0);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// throw new ServiceException("光大光子仅支持TradeVol");
|
||||
// }
|
||||
|
||||
// if (under.QuotationDate != valuedateBLL.ValueDate.Date)
|
||||
// {
|
||||
// //为了暂时修复一个QDP计算方式与客户需求不匹配的情况
|
||||
// //在非精确模式下,QDP不包括交易日当天的时间价值,但根据报价需求,需要将交易日当天的时间价值计算在内,
|
||||
// //所以要将交易日向前移动一天。未来QDP支持传递TTM来计算时,可以直接在TTM上加1,而不用移动交易日
|
||||
// //注意:当前这个临时修改必须在InitializeMarketProxy之前调用,这样才能正确设置波动率日期
|
||||
// var calendar = CalendarImpl.Get("chn");
|
||||
// var qdpDate = new Date(DateTime.Parse(under.QuotationDate.ToString()));
|
||||
// under.QuotationDate = calendar.PrevBizDay(qdpDate).DateTime;
|
||||
// }
|
||||
|
||||
// //OTC-8856 Start
|
||||
// //UpLimit
|
||||
// double priceUp = 0;
|
||||
// if (!string.IsNullOrWhiteSpace(under.UpDownLimit))
|
||||
// {
|
||||
// var tempVaue = under.UpDownLimit;
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out double tempDouble);
|
||||
// priceUp = (trade.SpotPrice ?? 0) * (1 + (tempDouble * 0.01));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// priceUp = (trade.SpotPrice ?? 0) + Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// double.TryParse(variety?.UpLimit?.Replace("%", ""), out double tempDouble);
|
||||
// priceUp = (trade.SpotPrice ?? 0) * (1 + (tempDouble * 0.01));
|
||||
// }
|
||||
|
||||
// //
|
||||
// double priceDown = 0;
|
||||
// if (!string.IsNullOrWhiteSpace(under.UpDownLimit))
|
||||
// {
|
||||
// var tempVaue = under.UpDownLimit;
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out double tempDouble);
|
||||
// priceDown = (trade.SpotPrice ?? 0) * (1 - (tempDouble * 0.01));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// priceDown = (trade.SpotPrice ?? 0) - Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// double.TryParse(variety?.DownLimit?.Replace("%", ""), out double tempDouble);
|
||||
// priceDown = (trade.SpotPrice ?? 0) * (1 - (tempDouble * 0.01));
|
||||
// }
|
||||
|
||||
// DataConvert.TryParsePercentValue(under.VolatilityRate, out double volatilityRate);
|
||||
// if (Math.Abs(volatilityRate) < 1e-5)
|
||||
// {
|
||||
// volatilityRate = variety.VolatilityRateValue;
|
||||
// }
|
||||
|
||||
// var tradeSpan = new trade_span();
|
||||
// var userId = Guid.NewGuid().ToString();
|
||||
|
||||
// var result = ValueCalculator.GetOptionValueResultV2(userId, under, trade, new double[] { trade.TradeOpenVolatility.Value }, new double[] { priceUp }, request: ValueCalculator.PV_ONLY);
|
||||
// tradeSpan.Spv1 = (double.IsNaN(result.Pv) ? 0 : result.Pv) * clientRatio;
|
||||
// result = ValueCalculator.GetOptionValueResultV2(userId, under, trade, new double[] { trade.TradeOpenVolatility.Value * (1 + volatilityRate) }, new double[] { priceUp }, request: ValueCalculator.PV_ONLY);
|
||||
// tradeSpan.Spv2 = (double.IsNaN(result.Pv) ? 0 : result.Pv) * clientRatio;
|
||||
// result = ValueCalculator.GetOptionValueResultV2(userId, under, trade, new double[] { trade.TradeOpenVolatility.Value }, new double[] { priceDown }, request: ValueCalculator.PV_ONLY);
|
||||
// tradeSpan.Spv3 = (double.IsNaN(result.Pv) ? 0 : result.Pv) * clientRatio;
|
||||
// result = ValueCalculator.GetOptionValueResultV2(userId, under, trade, new double[] { trade.TradeOpenVolatility.Value * (1 + volatilityRate) }, new double[] { priceDown }, request: ValueCalculator.PV_ONLY);
|
||||
// tradeSpan.Spv4 = (double.IsNaN(result.Pv) ? 0 : result.Pv) * clientRatio;
|
||||
|
||||
// tradeSpan.setWorstCastClientPayable4();
|
||||
|
||||
// return tradeSpan.WorstCastClientPayable ?? 0;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,487 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.Commons;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.QdpModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 国泰君安保证金计算
|
||||
// /// </summary>
|
||||
// public class GTJAMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly GTJAMarginCalculation Instance;
|
||||
|
||||
// static GTJAMarginCalculation()
|
||||
// {
|
||||
// Instance = new GTJAMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// protected GTJAMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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)
|
||||
// {
|
||||
// //结果集
|
||||
// Dictionary<int, trade_span> resultMap = new Dictionary<int, trade_span>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// //为了算客户角度的一个保证金数值
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// tradeList.ForEach(x => x.BuySell = x.BuySell == "买入" ? "卖出" : "买入");
|
||||
// }
|
||||
// if (!(priceDict?.Count > 0))
|
||||
// {
|
||||
// var codes = tradeList.Select(O => O.UnderlyingCode).ToArray();
|
||||
// priceDict = GetSettlePrice(codes, settleDate, "收盘价");
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// var underlyingIds = priceDict.Keys.ToList();
|
||||
|
||||
// //获取标的涨跌幅限制
|
||||
// var umDatas = (from um in db.underlying_manager
|
||||
// join variety in db.variety on um.UnderlyingTypeId equals variety.id into t_variety
|
||||
// from variety in t_variety.DefaultIfEmpty()
|
||||
// where underlyingIds.Contains(um.id)
|
||||
// select new
|
||||
// {
|
||||
// um.id,
|
||||
// um.VolatilityRate,
|
||||
// um.UpDownLimit,
|
||||
// defUpLimit = variety == null ? null : variety.UpLimit,
|
||||
// defDownLimit = variety == null ? null : variety.DownLimit,
|
||||
// defVolatilityRate = variety == null ? null : 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;
|
||||
// }
|
||||
|
||||
// //2.涨跌停板幅度
|
||||
// if (!string.IsNullOrWhiteSpace(t.UpDownLimit))
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.UpDownLimit;//百分比或绝对值
|
||||
// DownLimitDict[t.id] = t.UpDownLimit;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.defUpLimit?.ToString() ?? "5%";
|
||||
// DownLimitDict[t.id] = t.defDownLimit?.ToString() ?? "5%";
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(tradeList);
|
||||
// }
|
||||
|
||||
// //判断当日结算价是否已经入库
|
||||
// //if (priceDict == null || priceDict.Count == 0)
|
||||
// //{
|
||||
// // throw new Exception("当日结算价还未同步,请等待结算价自动同步完成或手动同步后再执行收盘操作!");
|
||||
// //}
|
||||
|
||||
// var tradeVolatilityRateDic = tradeList.ToDictionary(t => t.id, t => umVolatilityRateDic.ContainsKey(t.UnderlyingId) ? umVolatilityRateDic[t.UnderlyingId] : 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>();
|
||||
// double tempDouble;
|
||||
// //根据涨跌幅限制以及当日结算价计算涨停价以及跌停价
|
||||
// if (priceDict != null && priceDict.Count > 0)
|
||||
// {
|
||||
// foreach (var t in priceDict)
|
||||
// {
|
||||
// //OTC-8856 Start
|
||||
// //UpLimit
|
||||
// if (UpLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = UpLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// upLimitPrices[t.Key] = t.Value + Math.Abs(t.Value * tempDouble * 0.01);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// upLimitPrices[t.Key] = t.Value + Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// upLimitPrices[t.Key] = t.Value * 1.05;
|
||||
// }
|
||||
|
||||
// //DownLimit
|
||||
// if (DownLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = DownLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// downLimitPrices[t.Key] = t.Value - Math.Abs(t.Value * tempDouble * 0.01);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// downLimitPrices[t.Key] = t.Value - Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// downLimitPrices[t.Key] = t.Value * 0.95;
|
||||
// }
|
||||
// //End
|
||||
// }
|
||||
// eodPriceDict["up"] = upLimitPrices;
|
||||
// eodPriceDict["down"] = downLimitPrices;
|
||||
// }
|
||||
// //波动率变化
|
||||
// var addVolRateList = new List<Dictionary<int, double>> { null, tradeVolatilityRateDic };
|
||||
// //交易对应客户信息
|
||||
// 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();
|
||||
|
||||
// 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;
|
||||
// }
|
||||
// else if (item.Trade.TradeType == "权益互换")
|
||||
// {
|
||||
// value = (item.Trade.trade_swap.GetMarginRate ?? 0) * (item.Trade.StockEqvNotional ?? 0) + Math.Max((double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv), 0);
|
||||
// }
|
||||
// if (resultMap.ContainsKey(item.Trade.id))
|
||||
// {
|
||||
// switch (key)
|
||||
// {
|
||||
// case "up_0":
|
||||
// resultMap[item.Trade.id].Spv1 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_1":
|
||||
// resultMap[item.Trade.id].Spv2 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_0":
|
||||
// resultMap[item.Trade.id].Spv3 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// resultMap[item.Trade.id].Spv4 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * 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":
|
||||
// tempTradeSpan.Spv1 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_1":
|
||||
// tempTradeSpan.Spv2 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_0":
|
||||
// tempTradeSpan.Spv3 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// tempTradeSpan.Spv4 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// resultMap[item.Trade.id] = tempTradeSpan;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// //上面的计算用到静态生成market,需要清除
|
||||
// QdpMarketManager.Instance.RemovePrebuiltMarketProxy(userIdNew);
|
||||
// }
|
||||
|
||||
// //为了保持原有交易买卖方向不变
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// tradeList.ForEach(x => x.BuySell = x.BuySell == "买入" ? "卖出" : "买入");
|
||||
// }
|
||||
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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 tradeSpanInfoOtherSide = (from tradeSpan in tradeSpansOtherSide
|
||||
// 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
|
||||
// {
|
||||
// UnderlyingId = t.Key,
|
||||
// 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)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0);
|
||||
|
||||
// item.TwoSideMargin = Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0);
|
||||
|
||||
// #region 更新tradeSpan,使得每笔交易的持仓保证金和客户保证金计算用的Spv组保持一致
|
||||
|
||||
// var tradeSpansUpdate = db.trade_span.Where(x => x.ClientId == item.ClientId && x.UnderlyingId == item.UnderlyingId && x.ValueDate == settleDate).ToList();
|
||||
// if (item.WorstCastClientPayable == item.Spv1)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv1);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv2)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv2);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv3)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv3);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv4);
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// if (!PS.Config.ErpElement.NonInterBankMarginNetting)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(item.WorstCastClientPayable.Value, 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);
|
||||
// }
|
||||
|
||||
// //处理从客户角度的保证金计算(将交易买卖方向反向处理)
|
||||
// var clientGroupsOtherSide = tradeSpanInfoOtherSide.GroupBy(t => t.trade.ClientId);
|
||||
// foreach (var clientGroup in clientGroupsOtherSide)
|
||||
// {
|
||||
// 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);
|
||||
// }
|
||||
// }
|
||||
|
||||
// var clientSpan = clientSpanNews.FirstOrDefault(x => x.ClientId == clientGroup.Key && x.ValueDate == settleDate);
|
||||
// clientSpan.OtherSideMargin = (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;
|
||||
// }
|
||||
|
||||
// //span类型为实时删除所有实时计算的交易的保证金信息
|
||||
// if (SpanType == client_span.SpanType_RealTime)
|
||||
// {
|
||||
// if (RefreshClientIds != null)
|
||||
// {
|
||||
// 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.BulkInsert(db, clientSpanNews);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// 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)
|
||||
// .Select(n => new { n.ValueDate, n.ClientId }).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)
|
||||
// {
|
||||
// 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> { 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,502 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.Commons;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.QdpModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 国泰君安保证金计算
|
||||
// /// </summary>
|
||||
// public class HaiTongMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly HaiTongMarginCalculation Instance;
|
||||
|
||||
// static HaiTongMarginCalculation()
|
||||
// {
|
||||
// Instance = new HaiTongMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// protected HaiTongMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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)
|
||||
// {
|
||||
// //结果集
|
||||
// Dictionary<int, trade_span> resultMap = new Dictionary<int, trade_span>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// //为了算客户角度的一个保证金数值
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// tradeList.ForEach(x => x.BuySell = x.BuySell == "买入" ? "卖出" : "买入");
|
||||
// }
|
||||
// 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 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>();
|
||||
// var downVolatilityRateDic = 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;
|
||||
// downVolatilityRateDic[t.id] = -pvalue;
|
||||
// }
|
||||
// else if (DataConvert.TryParsePercentValue(t.defVolatilityRate, out pvalue) && (Math.Abs(pvalue) >= 1e-5))
|
||||
// {
|
||||
// umVolatilityRateDic[t.id] = pvalue;
|
||||
// downVolatilityRateDic[t.id] = -pvalue;
|
||||
// }
|
||||
|
||||
// //2.涨跌停板幅度
|
||||
// if (!string.IsNullOrWhiteSpace(t.UpDownLimit))
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.UpDownLimit;//百分比或绝对值
|
||||
// DownLimitDict[t.id] = t.UpDownLimit;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.defUpLimit?.ToString() ?? "5%";
|
||||
// DownLimitDict[t.id] = t.defDownLimit?.ToString() ?? "5%";
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(tradeList);
|
||||
// }
|
||||
|
||||
// var tradeVolatilityRateDicUp = tradeList.ToDictionary(t => t.id, t => umVolatilityRateDic.ContainsKey(t.UnderlyingId) ? umVolatilityRateDic[t.UnderlyingId] : 0)
|
||||
// .Where(d => d.Value > 0).ToDictionary(d => d.Key, d => d.Value);
|
||||
// var tradeVolatilityRateDicDown = tradeList.ToDictionary(t => t.id, t => downVolatilityRateDic.ContainsKey(t.UnderlyingId) ? downVolatilityRateDic[t.UnderlyingId] : 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>();
|
||||
// var normalLimitPrices = new Dictionary<int, double>();
|
||||
// double tempDouble;
|
||||
// //根据涨跌幅限制以及当日结算价计算涨停价以及跌停价
|
||||
// foreach (var t in priceDict)
|
||||
// {
|
||||
// //UpLimit
|
||||
// if (UpLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = UpLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// upLimitPrices[t.Key] = t.Value * (1 + (tempDouble * 0.01));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// upLimitPrices[t.Key] = t.Value + Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// upLimitPrices[t.Key] = t.Value * 1.05;
|
||||
// }
|
||||
|
||||
// //DownLimit
|
||||
// if (DownLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = DownLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// downLimitPrices[t.Key] = t.Value * (1 - (tempDouble * 0.01));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// downLimitPrices[t.Key] = t.Value - Math.Abs(tempAbs);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// downLimitPrices[t.Key] = t.Value * 0.95;
|
||||
// }
|
||||
|
||||
// //Normal
|
||||
// normalLimitPrices[t.Key] = t.Value;
|
||||
// }
|
||||
// eodPriceDict["up"] = upLimitPrices;
|
||||
// eodPriceDict["down"] = downLimitPrices;
|
||||
// eodPriceDict["normal"] = normalLimitPrices;
|
||||
|
||||
// //波动率变化
|
||||
// var addVolRateDic = new Dictionary<int, Dictionary<int, double>>();
|
||||
// addVolRateDic[0] = null;
|
||||
// addVolRateDic[1] = tradeVolatilityRateDicUp;
|
||||
// addVolRateDic[2] = tradeVolatilityRateDicDown;
|
||||
|
||||
// //交易对应客户信息
|
||||
// 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();
|
||||
|
||||
// var userIdNew = UniqueTimeId.Get().ToString();
|
||||
|
||||
// try
|
||||
// {
|
||||
// foreach (var price in eodPriceDict)
|
||||
// {
|
||||
// foreach (var itemDic in addVolRateDic)
|
||||
// {
|
||||
// var key = $"{price.Key}_{itemDic.Key}";
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(
|
||||
// userIdNew, // userId + "_" + price.Key,
|
||||
// settleDate,
|
||||
// tradeList,
|
||||
// price.Value,
|
||||
// ValueCalculator.PV_ONLY,
|
||||
// itemDic.Value,
|
||||
// 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_1":
|
||||
// resultMap[item.Trade.id].Spv1 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_0":
|
||||
// resultMap[item.Trade.id].Spv2 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_2":
|
||||
// resultMap[item.Trade.id].Spv3 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_1":
|
||||
// resultMap[item.Trade.id].Spv4 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_2":
|
||||
// resultMap[item.Trade.id].Spv5 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// resultMap[item.Trade.id].Spv6 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_0":
|
||||
// resultMap[item.Trade.id].Spv7 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_2":
|
||||
// resultMap[item.Trade.id].Spv8 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// resultMap[item.Trade.id].setWorstCastClientPayable8();
|
||||
// }
|
||||
// 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_1":
|
||||
// tempTradeSpan.Spv1 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_0":
|
||||
// tempTradeSpan.Spv2 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "up_2":
|
||||
// tempTradeSpan.Spv3 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_1":
|
||||
// tempTradeSpan.Spv4 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_2":
|
||||
// tempTradeSpan.Spv5 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// tempTradeSpan.Spv6 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_0":
|
||||
// tempTradeSpan.Spv7 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_2":
|
||||
// tempTradeSpan.Spv8 = item.Trade.TradeType == "自定义交易" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// resultMap[item.Trade.id] = tempTradeSpan;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// //上面的计算用到静态生成market,需要清除
|
||||
// QdpMarketManager.Instance.RemovePrebuiltMarketProxy(userIdNew);
|
||||
// }
|
||||
|
||||
// //为了保持原有交易买卖方向不变
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// tradeList.ForEach(x => x.BuySell = x.BuySell == "买入" ? "卖出" : "买入");
|
||||
// }
|
||||
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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
|
||||
// {
|
||||
// UnderlyingId = t.Key,
|
||||
// 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),
|
||||
// Spv5 = t.Sum(g => g.tradeSpan.Spv5) * (-1),
|
||||
// Spv6 = t.Sum(g => g.tradeSpan.Spv6) * (-1),
|
||||
// Spv7 = t.Sum(g => g.tradeSpan.Spv7) * (-1),
|
||||
// Spv8 = t.Sum(g => g.tradeSpan.Spv8) * (-1),
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// SpanType = SpanType
|
||||
// }).ToList();
|
||||
// foreach (var item in underlyingGroup)
|
||||
// {
|
||||
// item.WorstCastClientPayable = new double[] {
|
||||
// item.Spv1 ?? 0, item.Spv2 ?? 0, item.Spv3 ?? 0, item.Spv4 ?? 0, item.Spv5 ?? 0, item.Spv6 ?? 0, item.Spv7 ?? 0, item.Spv8 ?? 0
|
||||
// }.Min();
|
||||
|
||||
// #region 更新tradeSpan,使得每笔交易的持仓保证金和客户保证金计算用的Spv组保持一致
|
||||
|
||||
// var tradeSpansUpdate = db.trade_span.Where(x => x.ClientId == item.ClientId && x.UnderlyingId == item.UnderlyingId && x.ValueDate == settleDate).ToList();
|
||||
// if (item.WorstCastClientPayable == item.Spv1)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv1);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv2)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv2);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv3)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv3);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv4)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv4);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv5)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv5);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv6)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv6);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv7)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv7);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv8);
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// if (!PS.Config.ErpElement.NonInterBankMarginNetting)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(item.WorstCastClientPayable.Value, 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),
|
||||
// Spv5 = underlyingGroup.Sum(g => g.Spv5),
|
||||
// Spv6 = underlyingGroup.Sum(g => g.Spv6),
|
||||
// Spv7 = underlyingGroup.Sum(g => g.Spv7),
|
||||
// Spv8 = underlyingGroup.Sum(g => g.Spv8),
|
||||
// //负数代表客户应缴保证金,正数代表客户应收保证金
|
||||
// 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)
|
||||
// {
|
||||
// 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> { 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,202 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.QdpModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// public class HongYuanMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// //定义一个静态变量来保存类的实例(单例模式)
|
||||
// public static readonly HongYuanMarginCalculation Instance;
|
||||
|
||||
// static HongYuanMarginCalculation()
|
||||
// {
|
||||
// Instance = new HongYuanMarginCalculation();
|
||||
// }
|
||||
|
||||
// //定义私有构造函数,使外界不能创建该类实例
|
||||
// private HongYuanMarginCalculation()
|
||||
// {
|
||||
|
||||
// }
|
||||
|
||||
// private List<trade_span> CalculationSingleTrade(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool isInitialMargin = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易")
|
||||
// {
|
||||
// //结果集
|
||||
// var resultMap = new Dictionary<int, trade_span>();
|
||||
// var tempTradeList = new List<trade>();
|
||||
// var codes = new HashSet<string>(tradeList.Select(O => O.UnderlyingCode).ToArray());
|
||||
// if (!(priceDict?.Count > 0))
|
||||
// {
|
||||
// //结算的时候价格列表一定是空的;
|
||||
// priceDict = base.GetSettlePrice(codes, settleDate);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //价格列表不是空的说明是计算实时保证金或期初保证金
|
||||
// //宏源在计算实时保证金的时候使用前一天的收盘价这个逻辑是一开始确认的,后续对数据的时候要再次确认 --时嬴政
|
||||
// var lastDate = QdpCalendarHelper.GetNonHolidayDefore(settleDate.AddDays(-1));
|
||||
// priceDict = base.GetSettlePrice(codes, lastDate);
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// var clientIds = new HashSet<int>(tradeList.Select(O => O.ClientId ?? 0).ToArray());
|
||||
// var clientClassDict = new clientBLL().GetClients(clientIds.ToList()).ToDictionary(K => K.id, V => V.ProperClientClass);
|
||||
// var ratioDict = new clientlevelBLL().GetClientlevels(clientIds).ToDictionary(K => K.Key, V => isInitialMargin ? (V.Value.Ratio1 ?? 1) : (V.Value.Ratio ?? 1));
|
||||
// var vols = new Dictionary<int, double>();
|
||||
// tradeList.ForEach(t =>
|
||||
// {
|
||||
// double vol = t.TradeOpenVolatility ?? 0;
|
||||
// if (!clientClassDict.ContainsKey(t.ClientId ?? 0))
|
||||
// {
|
||||
// throw new Exception($"交易编号为{t.TradeNumber}的客户适当性类型不存在,无法计算保证金!");
|
||||
// }
|
||||
// if (clientClassDict[t.ClientId ?? 0].Contains("普通投资者"))
|
||||
// {
|
||||
// vol = vol * 1.2;
|
||||
// }
|
||||
// vols[t.id] = vol;
|
||||
// tempTradeList.Add(t.Clone());
|
||||
// if (!priceDict.ContainsKey(t.UnderlyingId))
|
||||
// { priceDict[t.UnderlyingId] = t.SpotPrice ?? 0; }
|
||||
// });
|
||||
// Action<trade> changeUmIdFunction = (t) =>
|
||||
// {
|
||||
// if (t.OptionType == "看跌")
|
||||
// {
|
||||
// t.UnderlyingId = t.UnderlyingId * -1;
|
||||
// if (t.trade_spread_option != null)
|
||||
// {
|
||||
// t.trade_spread_option.UnderlyingId1 = t.trade_spread_option.UnderlyingId1 * -1;
|
||||
// t.trade_spread_option.UnderlyingId2 = t.trade_spread_option.UnderlyingId2 * -1;
|
||||
// t.trade_spread_option.UnderlyingId3 = t.trade_spread_option.UnderlyingId3 * -1;
|
||||
// t.trade_spread_option.UnderlyingId4 = t.trade_spread_option.UnderlyingId4 * -1;
|
||||
// }
|
||||
// if (t.trade_rainbow_option != null)
|
||||
// {
|
||||
// t.trade_rainbow_option.UnderlyingId1 = t.trade_rainbow_option.UnderlyingId1 * -1;
|
||||
// t.trade_rainbow_option.UnderlyingId2 = t.trade_rainbow_option.UnderlyingId2 * -1;
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// Dictionary<int, double[]> dict = base.GetUpDownLimitPrice(priceDict);
|
||||
// Dictionary<int, double> underlyingPrice = new Dictionary<int, double>();
|
||||
// tempTradeList.ForEach(t =>
|
||||
// {
|
||||
// changeUmIdFunction(t);
|
||||
// underlyingPrice[t.UnderlyingId] = t.OptionType == "看涨" ? dict[t.UnderlyingId][0] : dict[t.UnderlyingId][1];
|
||||
// });
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(
|
||||
// userId.ToString(), // userId + "_" + price.Key,
|
||||
// settleDate,
|
||||
// tempTradeList,
|
||||
// underlyingPrice,
|
||||
// ValueCalculator.PV_ONLY,
|
||||
// null,
|
||||
// isEndOfDate: true,
|
||||
// volType: volType,
|
||||
// overrideVolsForTrade: vols,
|
||||
// isUseTradeVol: PS.Config.IsTradeVol,
|
||||
// PreciseTimeMode: !isEodSettle);
|
||||
|
||||
// tradeRiskResult.Results.ForEach(r =>
|
||||
// {
|
||||
// System.Diagnostics.Debug.WriteLine($"{r.Trade.StructureType}-{r.Trade.SpotPrice}-{r.Trade.TradeOpenVolatility}-{r.ValueResult.Pv}");
|
||||
// //保证金= 次日最大亏损;
|
||||
// double value = ratioDict[r.Trade.ClientId ?? 0] * r.ValueResult.Pv;
|
||||
// if (r.Trade.BuySell == "买入") { value = Math.Abs(value); } else { value = 0 - Math.Abs(value); }
|
||||
// var tempTradeSpan = new trade_span
|
||||
// {
|
||||
// TradeId = r.Trade.id,
|
||||
// ClientId = r.Trade.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = Math.Abs(r.Trade.UnderlyingId),
|
||||
// UnderlyingCode = r.Trade.UnderlyingCode,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value
|
||||
// };
|
||||
// resultMap[r.Trade.id] = tempTradeSpan;
|
||||
// });
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
|
||||
// private List<trade_span> CalcMargin(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool isInitialMargin = false, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易")
|
||||
// {
|
||||
// //结果集
|
||||
// List<trade_span> resultMap = new List<trade_span>();
|
||||
|
||||
// List<trade> tList = tradeList.Where(O => O.TradeType == "结构化交易").ToList();
|
||||
// if (tList.Count > 0)
|
||||
// {
|
||||
// for (int i = 0; i < tList.Count; i++)
|
||||
// {
|
||||
// int tempId = int.MaxValue;
|
||||
// tList[i].SubTrades.ToList().ForEach(t => t.id = tempId--);
|
||||
// List<trade_span> spans = CalculationSingleTrade(userId, userName, tList[i].SubTrades.ToList(), settleDate, priceDict, isInitialMargin, isEodSettle, forSingleTrade, volType);
|
||||
// double margin = 0;
|
||||
// if (tList[i].StructureType.Contains("跨式"))
|
||||
// { margin = spans.Max(O => O.WorstCastClientPayable ?? 0); }
|
||||
// else
|
||||
// { margin = spans.Sum(O => O.WorstCastClientPayable ?? 0); }
|
||||
// resultMap.Add(new trade_span
|
||||
// {
|
||||
// TradeId = tList[i].id,
|
||||
// ClientId = tList[i].ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = tList[i].UnderlyingId,
|
||||
// UnderlyingCode = tList[i].UnderlyingCode,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// Spv1 = margin,
|
||||
// Spv2 = margin,
|
||||
// Spv3 = margin,
|
||||
// Spv4 = margin,
|
||||
// WorstCastClientPayable = margin
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// tList = tradeList.Where(O => O.TradeType != "结构化交易").ToList();
|
||||
// if (tList.Count > 0)
|
||||
// {
|
||||
// resultMap.AddRange(CalculationSingleTrade(userId, userName, tList, settleDate, priceDict, isInitialMargin, isEodSettle, forSingleTrade, volType));
|
||||
// }
|
||||
// return resultMap;
|
||||
// }
|
||||
|
||||
// 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)
|
||||
// {
|
||||
// return CalcMargin(userId, userName, tradeList, settleDate, priceDict, false, hasOptionInfo, isEodSettle, forSingleTrade, volType);
|
||||
// }
|
||||
|
||||
// public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// if (trade.TradeType == "结构化交易" && (trade.SubTrades == null || trade.SubTrades.Count() == 0))
|
||||
// {
|
||||
// using (YLContext db = new YLContext())
|
||||
// { trade.SubTrades = db.trade.Where(x => x.ParentTradeId == trade.id).ToList(); }
|
||||
// }
|
||||
|
||||
// var tradeMargin = CalcMargin(0, "系统", new List<trade> { trade }, isInitialMargin ? (trade.TradeDate ?? valuedateBLL.ValueDate) : valuedateBLL.ValueDate, price == 0 ? null : new Dictionary<int, double> { { trade.UnderlyingId, price } }, isInitialMargin, hasOptionInfo);
|
||||
// if (null != tradeMargin)
|
||||
// {
|
||||
// return tradeMargin.FirstOrDefault()?.WorstCastClientPayable ?? 0.0;
|
||||
// }
|
||||
// return 0.0;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace YLErp.BLL.Calculation
|
||||
{
|
||||
public static class CalculatorHelperOld
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using YLErp.BLL;
|
||||
|
||||
namespace YLErp.Modules.MarginModule
|
||||
{
|
||||
public class eod_commodity_future_priceBLLBak
|
||||
{
|
||||
private readonly YLContext db = new YLContext();
|
||||
|
||||
public static List<string> DataSources = new List<string> { "系统", "人工" };
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定日期的收盘价或结算价
|
||||
/// </summary>
|
||||
/// <param name="codes">标的代码</param>
|
||||
/// <param name="date">日期</param>
|
||||
/// <param name="priceType">
|
||||
/// 价格类型:
|
||||
/// <para>0:最高价;</para>
|
||||
/// <para>1:最低价;</para>
|
||||
/// <para>2:收盘价;</para>
|
||||
/// <para>3:结算价;</para>
|
||||
/// </param>
|
||||
/// <returns></returns>
|
||||
public Dictionary<string, double> GetEodPrice(IEnumerable<string> codes, DateTime date, int priceType)
|
||||
{
|
||||
if (priceType < 0 || priceType > 3) { throw new ArgumentOutOfRangeException("priceType"); }
|
||||
var result = new Dictionary<string, double>();
|
||||
#region 商品期货
|
||||
var futurePirce =
|
||||
(from priceDb in db.eod_commodity_future_price
|
||||
where priceDb.ValueDate == date
|
||||
&& codes.Contains(priceDb.UnderlyingCode)
|
||||
select new { priceDb.UnderlyingCode, priceDb.HighPrice, priceDb.LowPrice, priceDb.ClosePrice, priceDb.SettlePrice })
|
||||
.ToDictionary(
|
||||
K => K.UnderlyingCode,
|
||||
V => { switch (priceType) { case 0: return V.HighPrice ?? 0; case 1: return V.LowPrice ?? 0; case 2: return V.ClosePrice; case 3: return V.SettlePrice; default: return 0; } }
|
||||
, StringComparer.OrdinalIgnoreCase);
|
||||
#endregion
|
||||
#region 股票
|
||||
var stockPirce =
|
||||
(from priceDb in db.eod_stock_price
|
||||
where priceDb.ValueDate == date
|
||||
&& codes.Contains(priceDb.UnderlyingCode)
|
||||
select new { priceDb.UnderlyingCode, priceDb.HighPrice, priceDb.LowPrice, priceDb.ClosePrice })
|
||||
.ToDictionary(
|
||||
K => K.UnderlyingCode,
|
||||
V => { switch (priceType) { case 0: return V.HighPrice ?? 0; case 1: return V.LowPrice ?? 0; case 2: return V.ClosePrice; case 3: return V.ClosePrice; default: return 0; } }
|
||||
, StringComparer.OrdinalIgnoreCase);
|
||||
#endregion
|
||||
#region 场内期权
|
||||
var exchangePirce =
|
||||
(from priceDb in db.eod_exchange_option_price
|
||||
where priceDb.ValueDate == date
|
||||
&& codes.Contains(priceDb.UnderlyingCode)
|
||||
select new { priceDb.UnderlyingCode, priceDb.HighPrice, priceDb.LowPrice, priceDb.ClosePrice, priceDb.SettlePrice })
|
||||
.ToDictionary(
|
||||
K => K.UnderlyingCode,
|
||||
V => { switch (priceType) { case 0: return V.HighPrice ?? 0; case 1: return V.LowPrice ?? 0; case 2: return V.ClosePrice; case 3: return V.SettlePrice; default: return 0; } }
|
||||
, StringComparer.OrdinalIgnoreCase);
|
||||
#endregion
|
||||
var errorCode = new List<string>();
|
||||
foreach (var item in codes)
|
||||
{
|
||||
if (!futurePirce.ContainsKey(item) &&
|
||||
!stockPirce.ContainsKey(item) &&
|
||||
!exchangePirce.ContainsKey(item))
|
||||
{ errorCode.Add(item); }
|
||||
if (futurePirce.ContainsKey(item))
|
||||
{ result[item] = futurePirce[item]; }
|
||||
else if (stockPirce.ContainsKey(item))
|
||||
{ result[item] = stockPirce[item]; }
|
||||
else if (exchangePirce.ContainsKey(item))
|
||||
{ result[item] = exchangePirce[item]; }
|
||||
else { result[item] = 0; }
|
||||
}
|
||||
if (errorCode.Count > 0)
|
||||
{ throw new Exception($"{string.Join(",", errorCode)} 价格缺失"); }
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定日期的收盘价或结算价
|
||||
/// </summary>
|
||||
/// <param name="codes">标的代码</param>
|
||||
/// <param name="date">日期</param>
|
||||
/// <param name="priceType">
|
||||
/// 价格类型:
|
||||
/// <para>0:最高价;</para>
|
||||
/// <para>1:最低价;</para>
|
||||
/// <para>2:收盘价;</para>
|
||||
/// <para>3:结算价;</para>
|
||||
/// </param>
|
||||
/// <returns></returns>
|
||||
public Dictionary<int, double> GetEodPriceToId(IEnumerable<string> codes, DateTime date, int priceType)
|
||||
{
|
||||
var result = new Dictionary<int, double>();
|
||||
var dict = GetEodPrice(codes, date, priceType);
|
||||
foreach (var item in dict)
|
||||
{
|
||||
var um = DataCacheProvider.GetUnderlyingDataSource().GetData(item.Key);
|
||||
if (um == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
result[um.id] = item.Value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,338 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.Modules.MarginModule;
|
||||
//using YLErp.Modules.VolatilityModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// public class MaoChuanMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例(单例模式)
|
||||
// public static readonly MaoChuanMarginCalculation Instance;
|
||||
|
||||
// static MaoChuanMarginCalculation()
|
||||
// {
|
||||
// Instance = new MaoChuanMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private MaoChuanMarginCalculation()
|
||||
// {
|
||||
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 计算香草期权和亚式期权保证金
|
||||
// /// </summary>
|
||||
// private List<trade_span> CalculationNormalOptionMargin(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易")
|
||||
// {
|
||||
// var resultMap = new Dictionary<int, trade_span>();
|
||||
|
||||
// var codes = tradeList.Select(O => O.UnderlyingCode).ToHashSet();
|
||||
// var mpProvider = new MarginParamProvider(new OptUserInfo(0, "系统"), settleDate)
|
||||
// .Initialize(codes, MarginParamTypeEnum.MarginRate);
|
||||
// //客户要求用AskVol计算保证金,所以先把所有交易方向改为卖出并把VolType赋值为 BidAskVol;
|
||||
// //Dictionary<int, string> buySellDict = tradeList.ToDictionary(K => K.id, V => V.BuySell);
|
||||
// //tradeList.ForEach(t => t.BuySell = "卖出");
|
||||
// var vols = new Dictionary<int, double>();
|
||||
// foreach (var t in tradeList)
|
||||
// {
|
||||
// string vType = t.VolType;
|
||||
// t.VolType = "报价Ask";
|
||||
// var um = _underlyingDataProvider.GetUnderlying(t.UnderlyingCode);
|
||||
// if (um == null)
|
||||
// {
|
||||
// throw new MarginCalcException($"[保证金计算]找不到标的数据(交易编号:{t.TradeNumber},标的代码:{t.UnderlyingCode})");
|
||||
// }
|
||||
// double vol = SingleVolService.GetSingleVol(new SingleVolReq(t, um), userId);
|
||||
// vols[t.id] = vol;
|
||||
// t.VolType = vType;
|
||||
// }
|
||||
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(
|
||||
// userId.ToString(),
|
||||
// settleDate,
|
||||
// tradeList,
|
||||
// priceDict,
|
||||
// ValueCalculator.BASIC_PRICING,
|
||||
// null,
|
||||
// isEndOfDate: true,
|
||||
// volType: null,
|
||||
// overrideVolsForTrade: vols,
|
||||
// isUseTradeVol: PS.Config.IsTradeVol,
|
||||
// PreciseTimeMode: !isEodSettle);
|
||||
|
||||
// //tradeList.ForEach(t => t.BuySell = buySellDict[t.id]);
|
||||
|
||||
// foreach (var r in tradeRiskResult.Results)
|
||||
// {
|
||||
// if (!mpProvider.TryGetMarginRate(r.Trade.UnderlyingCode, out var marginRate))
|
||||
// {
|
||||
// throw new MarginCalcException($"{r.Trade.UnderlyingCode} 保证金比率不存在");
|
||||
// }
|
||||
// var trade = tradeList.FirstOrDefault(t => t.id == r.Trade.id);
|
||||
// double price = priceDict == null ? r.Trade.SpotPrice ?? 0 : priceDict[r.Trade.UnderlyingId];
|
||||
// logger.Info($"茂川标准保证金计算:[{r.Trade.TradeType}_{r.Trade.BuySell}_{r.Trade.OptionType}_{r.Trade.Strike}] => Vol:{r.ValueResult.Vol};Delta:{r.ValueResult.Delta}");
|
||||
// //保证金= Delta*标的期货保证金比率*标的期货价格*持仓规模 (qdp计算出的Delta已经乘过数量了,所以这里不用再乘了);
|
||||
// double value = Math.Abs(r.ValueResult.Delta) * marginRate * price;// * r.Trade.Notional;
|
||||
// if (r.Trade.BuySell == "买入") { value = Math.Abs(value); } else { value = 0 - Math.Abs(value); }
|
||||
// var tempTradeSpan = new trade_span
|
||||
// {
|
||||
// TradeId = r.Trade.id,
|
||||
// ClientId = trade.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = trade.UnderlyingId,
|
||||
// UnderlyingCode = trade.UnderlyingCode,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value
|
||||
// };
|
||||
// resultMap[r.Trade.id] = tempTradeSpan;
|
||||
// }
|
||||
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 计算其他期权保证金
|
||||
// /// </summary>
|
||||
// private List<trade_span> CalculationOtherOptionMargin(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易")
|
||||
// {
|
||||
// var resultMap = new Dictionary<int, trade_span>();
|
||||
// var tempTradeList = new List<trade>();
|
||||
// var vols = new Dictionary<int, double>();
|
||||
// foreach (var t in tradeList)
|
||||
// {
|
||||
// string vType = t.VolType;
|
||||
// t.VolType = "报价Ask";
|
||||
// var um = _underlyingDataProvider.GetUnderlying(t.UnderlyingCode);
|
||||
// double vol = SingleVolService.GetSingleVol(new SingleVolReq(t, um), userId);
|
||||
// vols[t.id] = vol;
|
||||
// t.VolType = vType;
|
||||
// tempTradeList.Add(t.Clone());
|
||||
// }
|
||||
|
||||
// var tradeRiskResult = CalculatorHelper.CalculateRisksForTrades(
|
||||
// userId.ToString(), // userId + "_" + price.Key,
|
||||
// settleDate,
|
||||
// tempTradeList,
|
||||
// priceDict,
|
||||
// ValueCalculator.BASIC_PRICING,
|
||||
// null,
|
||||
// isEndOfDate: true,
|
||||
// volType: null,
|
||||
// overrideVolsForTrade: vols,
|
||||
// isUseTradeVol: PS.Config.IsTradeVol,
|
||||
// PreciseTimeMode: !isEodSettle);
|
||||
// Action<trade> changeUmIdFunction = (t) =>
|
||||
// {
|
||||
// if (t.OptionType == "看跌")
|
||||
// {
|
||||
// t.UnderlyingId = t.UnderlyingId * -1;
|
||||
// if (t.trade_spread_option != null)
|
||||
// {
|
||||
// t.trade_spread_option.UnderlyingId1 = t.trade_spread_option.UnderlyingId1 * -1;
|
||||
// t.trade_spread_option.UnderlyingId2 = t.trade_spread_option.UnderlyingId2 * -1;
|
||||
// t.trade_spread_option.UnderlyingId3 = t.trade_spread_option.UnderlyingId3 * -1;
|
||||
// t.trade_spread_option.UnderlyingId4 = t.trade_spread_option.UnderlyingId4 * -1;
|
||||
// }
|
||||
// if (t.trade_rainbow_option != null)
|
||||
// {
|
||||
// t.trade_rainbow_option.UnderlyingId1 = t.trade_rainbow_option.UnderlyingId1 * -1;
|
||||
// t.trade_rainbow_option.UnderlyingId2 = t.trade_rainbow_option.UnderlyingId2 * -1;
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// if (priceDict == null)
|
||||
// {
|
||||
// priceDict = new Dictionary<int, double>();
|
||||
// Dictionary<int, string[]> rateDict = base.GetUpDownLimitRate(tradeList.Select(O => O.UnderlyingId).ToArray());
|
||||
// tempTradeList.ForEach(t =>
|
||||
// {
|
||||
// double[] arr = base.GetUpDownLimitPrice(rateDict[t.id], (t.SpotPrice ?? 0), double.Parse(rateDict[t.id][2]));
|
||||
// changeUmIdFunction(t);
|
||||
// priceDict[t.UnderlyingId] = t.OptionType == "看涨" ? arr[1] : arr[0];
|
||||
// });
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Dictionary<int, double[]> dict = base.GetUpDownLimitPrice(priceDict);
|
||||
// tempTradeList.ForEach(t =>
|
||||
// {
|
||||
// changeUmIdFunction(t);
|
||||
// priceDict[t.UnderlyingId] = t.OptionType == "看涨" ? dict[t.id][1] : dict[t.id][0];
|
||||
// });
|
||||
// }
|
||||
|
||||
// var newTradeRiskResult = CalculatorHelper.CalculateRisksForTrades(
|
||||
// userId.ToString(), // userId + "_" + price.Key,
|
||||
// settleDate,
|
||||
// tempTradeList,
|
||||
// priceDict,
|
||||
// ValueCalculator.BASIC_PRICING,
|
||||
// null,
|
||||
// isEndOfDate: true,
|
||||
// volType: null,
|
||||
// overrideVolsForTrade: vols,
|
||||
// isUseTradeVol: PS.Config.IsTradeVol,
|
||||
// PreciseTimeMode: !isEodSettle);
|
||||
// tempTradeList.ForEach(t =>
|
||||
// {
|
||||
// double cPv = tradeRiskResult.Results.FirstOrDefault(O => O.ValueResult.TradeId == t.id).ValueResult.Pv;
|
||||
// double nPv = newTradeRiskResult.Results.FirstOrDefault(O => O.ValueResult.TradeId == t.id).ValueResult.Pv;
|
||||
// //保证金= 次日最大亏损;
|
||||
// double value = t.OptionType == "看涨" ? cPv - nPv : cPv + nPv;
|
||||
// logger.Info($"茂川奇异保证金计算:[{t.TradeType}_{t.BuySell}_{t.OptionType}_{t.Strike}] => 当日Pv:{cPv};次日Pv:{nPv}");
|
||||
// var tempTradeSpan = new trade_span
|
||||
// {
|
||||
// TradeId = t.id,
|
||||
// ClientId = t.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = Math.Abs(t.UnderlyingId),
|
||||
// UnderlyingCode = t.UnderlyingCode,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// Spv1 = value,
|
||||
// Spv2 = value,
|
||||
// Spv3 = value,
|
||||
// Spv4 = value,
|
||||
// WorstCastClientPayable = value
|
||||
// };
|
||||
// resultMap[t.id] = tempTradeSpan;
|
||||
// });
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
|
||||
|
||||
// private List<trade_span> CalculationStructureOptionMargin(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, bool forSingleTrade = true, string volType = "交易")
|
||||
// {
|
||||
// List<trade_span> resultMap = new List<trade_span>();
|
||||
// for (int i = 0; i < tradeList.Count; i++)
|
||||
// {
|
||||
// int tempId = int.MaxValue;
|
||||
// tradeList[i].SubTrades.ToList().ForEach(t => t.id = tempId--);
|
||||
// List<trade_span> childrenSpans = RunMarginCalculation(userId, userName, tradeList[i].SubTrades.ToList(), settleDate, null, hasOptionInfo, isEodSettle, forSingleTrade, volType);
|
||||
|
||||
// double margin = 0;
|
||||
// switch (tradeList[i].StructureType)
|
||||
// {
|
||||
// case "牛市价差":
|
||||
// case "熊市价差":
|
||||
// case "亚式熊市价差":
|
||||
// case "三领口组合":
|
||||
// for (int j = 0; j < childrenSpans.Count; j++)
|
||||
// {
|
||||
// margin += childrenSpans[j].WorstCastClientPayable ?? 0;
|
||||
// }
|
||||
// break;
|
||||
// case "跨式组合":
|
||||
// case "宽跨式组合":
|
||||
// for (int j = 0; j < childrenSpans.Count; j++)
|
||||
// {
|
||||
// double absMargin = Math.Abs(childrenSpans[j].WorstCastClientPayable ?? 0);
|
||||
// if (margin < absMargin)
|
||||
// {
|
||||
// margin = absMargin;
|
||||
// }
|
||||
// }
|
||||
// break;
|
||||
// case "复制标的资产":
|
||||
// case "蝶式组合":
|
||||
// case "飞鹰式组合":
|
||||
// case "比例价差":
|
||||
// case "日历价差":
|
||||
// case "箱式价差":
|
||||
// case "风险逆转":
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// var tempTradeSpan = new trade_span
|
||||
// {
|
||||
// TradeId = tradeList[i].id,
|
||||
// ClientId = tradeList[i].ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// UnderlyingId = tradeList[i].UnderlyingId,
|
||||
// UnderlyingCode = tradeList[i].UnderlyingCode,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// Spv1 = margin,
|
||||
// Spv2 = margin,
|
||||
// Spv3 = margin,
|
||||
// Spv4 = margin,
|
||||
// WorstCastClientPayable = margin
|
||||
// };
|
||||
// resultMap.Add(tempTradeSpan);
|
||||
// }
|
||||
// return resultMap;
|
||||
// }
|
||||
|
||||
// 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>();
|
||||
// if (!(priceDict?.Count > 0))
|
||||
// {
|
||||
// var codes = tradeList.Select(O => O.UnderlyingCode).ToArray();
|
||||
// priceDict = base.GetSettlePrice(codes, settleDate);
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return resultMap;
|
||||
// }
|
||||
// if (forOtherSide)
|
||||
// {
|
||||
// return RunMarginCalculationOtherSide(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType);
|
||||
// }
|
||||
|
||||
|
||||
// List<trade> tList = tradeList.Where(O => O.TradeType == "结构化交易").ToList();
|
||||
// if (tList.Count > 0)
|
||||
// {
|
||||
// resultMap.AddRange(CalculationStructureOptionMargin(userId, userName, tList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType));
|
||||
// }
|
||||
|
||||
// tList = tradeList.Where(O => O.TradeType == "香草期权" || O.TradeType == "亚式期权").ToList();
|
||||
// if (tList.Count > 0)
|
||||
// {
|
||||
// resultMap.AddRange(CalculationNormalOptionMargin(userId, userName, tList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType));
|
||||
// }
|
||||
// tList = tradeList.Where(O => O.TradeType != "结构化交易" && O.TradeType != "香草期权" && O.TradeType != "亚式期权").ToList();
|
||||
// if (tList.Count > 0)
|
||||
// {
|
||||
// resultMap.AddRange(CalculationOtherOptionMargin(userId, userName, tList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType));
|
||||
// }
|
||||
// return resultMap;
|
||||
// }
|
||||
|
||||
// public override double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// if (trade.TradeType == "结构化交易" && (trade.SubTrades == null || trade.SubTrades.Count() == 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,15 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace YLErp.BLL.MarginCalculationBak
|
||||
{
|
||||
/// <summary>
|
||||
/// 保证金计算错误
|
||||
/// </summary>
|
||||
public class MarginCalcException : Exception
|
||||
{
|
||||
public MarginCalcException(string message, Exception innerException = null) : base(message, innerException)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.Configuration;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.Model;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// ///
|
||||
// /// </summary>
|
||||
// public static class MarginDefault
|
||||
// {
|
||||
// /// <summary>
|
||||
// /// 计算日终保证金
|
||||
// /// </summary>
|
||||
// /// <param name="userId"></param>
|
||||
// /// <param name="userName"></param>
|
||||
// /// <param name="tradeList"></param>
|
||||
// /// <param name="settleDate"></param>
|
||||
// /// <param name="priceDict">如需要根据不同客户配置选取价格,应传null</param>
|
||||
// /// <param name="hasOptionInfo"></param>
|
||||
// /// <param name="isEodSettle"></param>
|
||||
// /// <param name="forSingleTrade"></param>
|
||||
// /// <param name="volType"></param>
|
||||
// /// <param name="forOtherSide"></param>
|
||||
// /// <returns></returns>
|
||||
// public static 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)
|
||||
// {
|
||||
// switch (PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.国泰君安:
|
||||
// case CompanyEnum.上期资本:
|
||||
// case CompanyEnum.中财资本:
|
||||
// return GTJAMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.光大光子:
|
||||
// return GDGZMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.渤海:
|
||||
// case CompanyEnum.安粮:
|
||||
// return BHRSMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.申万:
|
||||
// return SYWGMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.格林大华:
|
||||
// return UniversalMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.方顿:
|
||||
// return FDMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.茂川资本:
|
||||
// return MaoChuanMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.宏源:
|
||||
// return HongYuanMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.伴兴:
|
||||
// return BXMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.海通:
|
||||
// return HaiTongMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// case CompanyEnum.瑞达:
|
||||
// return RDMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// default:
|
||||
// return GTJAMarginCalculation.Instance.RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, forOtherSide);
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static bool CalcClientMargin(int userId, string userName, DateTime settleDate, List<trade_span> tradeSpans, List<trade_span> tradeSpansOtherSide, int SpanType = 0, List<int> RefreshClientIds = null, Dictionary<int, double> clientAdditionalMarginDic = null)
|
||||
// {
|
||||
// switch (PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.国泰君安:
|
||||
// return GTJAMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// case CompanyEnum.光大光子:
|
||||
// return GDGZMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// case CompanyEnum.渤海:
|
||||
// return BHRSMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// case CompanyEnum.安粮:
|
||||
// return BHRSMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false, clientAdditionalMarginDic);
|
||||
// case CompanyEnum.申万:
|
||||
// return SYWGMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, !PS.Config.ErpElement.TwoSideMargin);
|
||||
// case CompanyEnum.格林大华:
|
||||
// return UniversalMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, !PS.Config.ErpElement.TwoSideMargin);
|
||||
// case CompanyEnum.伴兴:
|
||||
// return BXMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// case CompanyEnum.海通:
|
||||
// return HaiTongMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// case CompanyEnum.瑞达:
|
||||
// return RDMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// default:
|
||||
// return GTJAMarginCalculation.Instance.CalcClientMargin(userId, userName, settleDate, tradeSpans, tradeSpansOtherSide, SpanType, RefreshClientIds, false);
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static bool isMarginCalcNeedSpecial()
|
||||
// {
|
||||
// switch (YLErp.PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.渤海:
|
||||
// case CompanyEnum.安粮:
|
||||
// return BHRSMarginCalculation.Instance.MarginCalcNeedSpecial;
|
||||
// case CompanyEnum.国泰君安:
|
||||
// case CompanyEnum.申万:
|
||||
// case CompanyEnum.格林大华:
|
||||
// default:
|
||||
// return SYWGMarginCalculation.Instance.MarginCalcNeedSpecial;
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static double? GetInitialMarginRatio(trade trade)
|
||||
// {
|
||||
// switch (PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.方顿:
|
||||
// return FDMarginCalculation.Instance.GetInitialMarginRatio(trade);
|
||||
// default:
|
||||
// return 0;
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static double? GetPositionMarginRatio(trade trade)
|
||||
// {
|
||||
// switch (PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.方顿:
|
||||
// return FDMarginCalculation.Instance.GetPositionMarginRatio(trade);
|
||||
// default:
|
||||
// return 0;
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static double GetInitialMargin(trade trade, bool hasOptionInfo = false)
|
||||
// {
|
||||
// if (trade is null)
|
||||
// {
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
// switch (PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.方顿:
|
||||
// return FDMarginCalculation.Instance.GetInitialMargin(trade);
|
||||
// case CompanyEnum.光大光子:
|
||||
// return GDGZMarginCalculation.Instance.GetInitialMargin(trade);
|
||||
// default:
|
||||
// return GetTradeMargin(trade, (trade.SpotPrice ?? 0), true, hasOptionInfo);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// isInitialMargin为true: 为初始保证金
|
||||
// /// isInitialMargin为false: 为实时保证金
|
||||
// /// </summary>
|
||||
// public static double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// if (trade.TradeType == "结构化交易")
|
||||
// {
|
||||
// var option = StructureOption_Code.StructureOptions.FirstOrDefault(o => o.Name == trade.StructureType || o.CnName == trade.StructureType);
|
||||
// //自由组合时不在变更StructureType字段值,保持原有结构化交易的内容;
|
||||
// if (option != null)
|
||||
// { trade.StructureType = option.CnName; }
|
||||
// }
|
||||
// double? tempInitialMargin = null;
|
||||
// if (!isInitialMargin && trade.CalcFlag == 1)
|
||||
// {
|
||||
// tempInitialMargin = trade.InitialMargin;
|
||||
// trade.InitialMargin = null;
|
||||
// }
|
||||
// try
|
||||
// {
|
||||
// switch (PS.Config.Company)
|
||||
// {
|
||||
// case CompanyEnum.国泰君安:
|
||||
// case CompanyEnum.上期资本:
|
||||
// case CompanyEnum.光大光子:
|
||||
// return GTJAMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.渤海:
|
||||
// return BHRSMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.安粮:
|
||||
// return BHRSMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.申万:
|
||||
// return SYWGMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.格林大华:
|
||||
// return UniversalMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.茂川资本:
|
||||
// return MaoChuanMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.宏源:
|
||||
// return HongYuanMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.伴兴:
|
||||
// return BXMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.海通:
|
||||
// return HaiTongMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// case CompanyEnum.瑞达:
|
||||
// return RDMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// default:
|
||||
// return GTJAMarginCalculation.Instance.GetTradeMargin(trade, price, isInitialMargin, hasOptionInfo);
|
||||
// }
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// if (isInitialMargin && trade.CalcFlag == 1 && trade.InitialMargin == null)
|
||||
// {
|
||||
// trade.InitialMargin = tempInitialMargin;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// public class MarginResult
|
||||
// {
|
||||
// public trade trade;
|
||||
// public double Margin;
|
||||
// }
|
||||
//}
|
||||
@@ -1,381 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using System.Text.RegularExpressions;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.Helpers;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.Modules.DataProviderModule;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 保证金计算
|
||||
// /// </summary>
|
||||
// public class MarginCalculationBase
|
||||
// {
|
||||
// protected static readonly Abstract.ILogger logger = LogFactory.GetLogger("保证金计算");
|
||||
|
||||
// protected readonly UnderlyingDataProvider _underlyingDataProvider;
|
||||
|
||||
// protected MarginCalculationBase()
|
||||
// {
|
||||
// _underlyingDataProvider = new UnderlyingDataProvider();
|
||||
// }
|
||||
|
||||
// public virtual bool MarginCalcNeedSpecial => false;
|
||||
|
||||
// public virtual 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 = true, Dictionary<int, double> clientAdditionalMarginDic = null)
|
||||
// {
|
||||
// using (var 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();
|
||||
// if (OnlyBuyer)
|
||||
// {
|
||||
// tradeSpanInfo = tradeSpanInfo.Where(t => t.trade.BuySell == "买入").ToList();
|
||||
// }
|
||||
|
||||
// var clientSpanNews = new List<client_span>(100);
|
||||
// var clientGroups = tradeSpanInfo.GroupBy(t => t.trade.ClientId);
|
||||
// foreach (var clientGroup in clientGroups)
|
||||
// {
|
||||
// var spvList = new[] {
|
||||
// clientGroup.Sum(g => g.tradeSpan.Spv1??0),
|
||||
// clientGroup.Sum(g => g.tradeSpan.Spv2??0),
|
||||
// clientGroup.Sum(g => g.tradeSpan.Spv3??0),
|
||||
// clientGroup.Sum(g => g.tradeSpan.Spv4??0)
|
||||
// };
|
||||
// var maxSpv = spvList.Max();
|
||||
// var twoSideMargin = PS.Config.ErpElement.TwoSideMargin && clientList.FirstOrDefault(x => x.id == clientGroup.Key)?.HasTwoSideMargin == 1;
|
||||
// var clientSpan = new client_span
|
||||
// {
|
||||
// ClientId = clientGroup.Key,
|
||||
// ValueDate = settleDate,
|
||||
// Spv1 = -spvList[0],
|
||||
// Spv2 = -spvList[1],
|
||||
// Spv3 = -spvList[2],
|
||||
// Spv4 = -spvList[3],
|
||||
// WorstCastClientPayable = twoSideMargin ? -maxSpv : -Math.Max(maxSpv, 0),
|
||||
// TwoSideMargin = -maxSpv,
|
||||
// RiskExposure = -clientGroup.Sum(g => g.tradeSpan.RiskExposure),
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// SpanType = SpanType,
|
||||
// AdditionalWorstCastClientPayable = clientAdditionalMarginDic != null && clientAdditionalMarginDic.TryGetValue(clientGroup.Key ?? 0, out var dd) ? dd : 0
|
||||
// };
|
||||
// clientSpanNews.Add(clientSpan);
|
||||
// }
|
||||
|
||||
// var tradeSpanInfoOtherSide = (from tradeSpan in tradeSpansOtherSide
|
||||
// join trade in tradeList on tradeSpan.TradeId equals trade.id
|
||||
// where tradeSpan.ValueDate == settleDate
|
||||
// select new { trade, tradeSpan }).ToList();
|
||||
|
||||
// //处理从客户角度的保证金计算(将交易买卖方向反向处理)
|
||||
// var compareZero = !PS.Config.ErpElement.NonInterBankMarginNetting;
|
||||
// var clientGroupsOtherSide = tradeSpanInfoOtherSide.GroupBy(t => t.trade.ClientId);
|
||||
// foreach (var clientGroup in clientGroupsOtherSide)
|
||||
// {
|
||||
// var clientSpan = clientSpanNews.FirstOrDefault(x => x.ClientId == clientGroup.Key && x.ValueDate == settleDate);
|
||||
// if (clientSpan != null)
|
||||
// {
|
||||
// clientSpan.OtherSideMargin = clientGroup.Sum(g =>
|
||||
// {
|
||||
// var arr = new[] { g.tradeSpan.Spv1 ?? 0, g.tradeSpan.Spv2 ?? 0, g.tradeSpan.Spv3 ?? 0, g.tradeSpan.Spv4 ?? 0 };
|
||||
// return compareZero ? Math.Min(arr.Min(), 0) : arr.Min();
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
// //span类型为实时删除所有实时计算的交易的保证金信息
|
||||
// if (SpanType == client_span.SpanType_RealTime)
|
||||
// {
|
||||
// if (RefreshClientIds != null)
|
||||
// {
|
||||
// db.BulkDelete<client_span>($"{nameof(client_span.ClientId)} in @ids", new { ids = RefreshClientIds });
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// db.BulkDelete<client_span>($"{nameof(client_span.SpanType)}={SpanType}");
|
||||
// }
|
||||
|
||||
// MySqlBulkExtensions.BulkInsert(db, clientSpanNews);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// var sql = $"{nameof(client_span.ValueDate)}='{settleDate.ToSqlDate()}' and {nameof(client_span.SpanType)}={SpanType} and {nameof(client_span.ModifiedFlag)}=0";
|
||||
// db.BulkDelete<client_span>(sql);
|
||||
|
||||
// var clientSpanOldsWithFlag = db.client_span.Where(t => t.ValueDate == settleDate && t.SpanType == SpanType && t.ModifiedFlag)
|
||||
// .Select(n => new { n.ValueDate, n.ClientId }).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 virtual 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)
|
||||
// {
|
||||
// var tradeSpans = new List<trade_span>();
|
||||
// if (tradeList != null && tradeList.Count > 0)
|
||||
// {
|
||||
// using (var 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)
|
||||
// {
|
||||
// //未设置相关保证金系数默认为1.0
|
||||
// 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 : (PS.Config.ErpElement.TwoSideMargin && client.client.HasTwoSideMargin == 1 ? -1 : 0)) * clientRatio;
|
||||
// var twoSideMargin = (t.StockEqvNotional ?? (t.Notional * t.SpotPrice ?? 0.0)) * marginRation * (t.BuySell == "买入" ? 1 : -1) * clientRatio;
|
||||
// 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,
|
||||
// TwoSideMargin = twoSideMargin
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
|
||||
// public virtual double GetTradeMargin(trade trade, double price, bool isInitialMargin = false, bool hasOptionInfo = false)
|
||||
// {
|
||||
// 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;
|
||||
// }
|
||||
|
||||
// private double GetUpDownValue(string upDownLimit, double settlePrice, double minPriceChange)
|
||||
// {
|
||||
// double result = 0, haifPrice = minPriceChange / 2;
|
||||
// if (upDownLimit.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(upDownLimit.Replace("%", ""), out result);
|
||||
// result = settlePrice * (result * 0.01);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(upDownLimit, out result);
|
||||
// }
|
||||
// double diff = result % minPriceChange;
|
||||
// result -= diff;
|
||||
// if (diff >= haifPrice) { result += minPriceChange; }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取涨跌幅
|
||||
// /// </summary>
|
||||
// /// <param name="underlyingId">标的Id</param>
|
||||
// /// <returns>
|
||||
// /// <para>Key:标的Id;</para>
|
||||
// /// <para>Value:[0]:涨幅;</para>
|
||||
// /// <para>Value:[1]:跌幅;</para>
|
||||
// /// <para>Value:[2]:最小价格变动;</para>
|
||||
// /// </returns>
|
||||
// protected Dictionary<int, string[]> GetUpDownLimitRate(IEnumerable<int> underlyingId)
|
||||
// {
|
||||
// Dictionary<int, string[]> result = new Dictionary<int, string[]>();
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// var underlyingIds = underlyingId.ToList();
|
||||
|
||||
// //获取标的涨跌幅限制
|
||||
// var umDatas = (from um in db.underlying_manager
|
||||
// join variety in db.variety on um.UnderlyingTypeId equals variety.id
|
||||
// where underlyingIds.Contains(um.id)
|
||||
// select new
|
||||
// {
|
||||
// um.id,
|
||||
// um.VolatilityRate,
|
||||
// um.UpDownLimit,
|
||||
// variety.MinPriceChange,
|
||||
// defUpLimit = variety.UpLimit,
|
||||
// defDownLimit = variety.DownLimit,
|
||||
// defVolatilityRate = variety.VolatilityRate
|
||||
// }).ToList();
|
||||
|
||||
// if (umDatas != null && umDatas.Count > 0)
|
||||
// {
|
||||
// umDatas.ForEach(t =>
|
||||
// {
|
||||
// string[] limitArr = new string[3];
|
||||
// if (!string.IsNullOrWhiteSpace(t.UpDownLimit))
|
||||
// {
|
||||
// limitArr[0] = t.UpDownLimit;//百分比或绝对值
|
||||
// limitArr[1] = t.UpDownLimit;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// limitArr[0] = t.defUpLimit?.ToString() ?? "5%";
|
||||
// limitArr[1] = t.defDownLimit?.ToString() ?? "5%";
|
||||
// }
|
||||
// if (string.IsNullOrEmpty(t.MinPriceChange))
|
||||
// {
|
||||
// limitArr[2] = "0.01";
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// limitArr[2] = Regex.Match(t.MinPriceChange, @"\d+(?=元.+)").Value;
|
||||
// if (string.IsNullOrEmpty(t.MinPriceChange))
|
||||
// {
|
||||
// limitArr[2] = "0.01";
|
||||
// }
|
||||
// }
|
||||
// result[t.id] = limitArr;
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取涨跌幅价格
|
||||
// /// </summary>
|
||||
// /// <param name="upDownLimit">
|
||||
// /// <para>[0]:涨幅;</para>
|
||||
// /// <para>[1]:跌幅;</para>
|
||||
// /// </param>
|
||||
// /// <param name="price">基准价</param>
|
||||
// /// <param name="minPriceChange">最小价格变动</param>
|
||||
// /// <returns>
|
||||
// /// <para>[0]:涨停价;</para>
|
||||
// /// <para>[1]:跌停价;</para>
|
||||
// /// </returns>
|
||||
// protected double[] GetUpDownLimitPrice(string[] upDownLimit, double price, double minPriceChange)
|
||||
// {
|
||||
// double[] priceArr = new double[2];
|
||||
// double tempDouble, haifPrice = minPriceChange / 2;
|
||||
// #region 涨幅
|
||||
// tempDouble = GetUpDownValue(upDownLimit[0], price, minPriceChange);
|
||||
// priceArr[0] = price + Math.Abs(tempDouble);
|
||||
// #endregion
|
||||
// #region 跌幅
|
||||
// tempDouble = GetUpDownValue(upDownLimit[1], price, minPriceChange);
|
||||
// priceArr[1] = price - Math.Abs(tempDouble);
|
||||
// #endregion
|
||||
// return priceArr;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取涨跌停价格
|
||||
// /// </summary>
|
||||
// /// <param name="priceDict">
|
||||
// /// 当前价格
|
||||
// /// <para>Key:标的Id;</para>
|
||||
// /// <para>Value:标的价格;</para>
|
||||
// /// </param>
|
||||
// /// <returns>
|
||||
// /// <para>Key:标的Id;</para>
|
||||
// /// <para>Value:[0]:涨停价;</para>
|
||||
// /// <para>Value:[1]:跌停价;</para>
|
||||
// /// </returns>
|
||||
// protected Dictionary<int, double[]> GetUpDownLimitPrice(Dictionary<int, double> priceDict)
|
||||
// {
|
||||
// Dictionary<int, double[]> result = new Dictionary<int, double[]>();
|
||||
// Dictionary<int, string[]> upDownLimitRate = GetUpDownLimitRate(priceDict.Keys);
|
||||
// foreach (var item in upDownLimitRate)
|
||||
// { result[item.Key] = GetUpDownLimitPrice(item.Value, priceDict[item.Key], double.Parse(item.Value[2])); }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
// //为了算客户角度的一个保证金数值
|
||||
// //RunMarginCalculation时forOtherSide为true时调用
|
||||
// protected List<trade_span> RunMarginCalculationOtherSide(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo, bool isEodSettle, bool forSingleTrade, string volType)
|
||||
// {
|
||||
// void RevertBuySell()
|
||||
// {
|
||||
// foreach (var x in tradeList)
|
||||
// {
|
||||
// x.BuySell = x.BuySell == "买入" ? "卖出" : "买入";
|
||||
// if (x.SubTrades != null && x.SubTrades.Any())
|
||||
// {
|
||||
// foreach (var xs in x.SubTrades)
|
||||
// {
|
||||
// xs.BuySell = xs.BuySell == "买入" ? "卖出" : "买入";
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// RevertBuySell();
|
||||
// var results = RunMarginCalculation(userId, userName, tradeList, settleDate, priceDict, hasOptionInfo, isEodSettle, forSingleTrade, volType, false);
|
||||
// RevertBuySell();
|
||||
// return results;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取currentDate参数前一日的结算价
|
||||
// /// </summary>
|
||||
// /// <param name="codes"></param>
|
||||
// /// <param name="currentDate">当前日期</param>
|
||||
// /// <param name="settlePriceMode">
|
||||
// /// 结算价模式,默认为结算价模式
|
||||
// /// <para>valuedate.EodSettlePriceMode_***</para>
|
||||
// /// </param>
|
||||
// /// <returns></returns>
|
||||
// protected Dictionary<int, double> GetSettlePrice(IEnumerable<string> codes, DateTime currentDate, string settlePriceMode = "")
|
||||
// {
|
||||
// //默认情况选择结算价
|
||||
// bool isClosePrice = "收盘价".Equals(settlePriceMode ?? "");
|
||||
// codes = codes.ToHashSet();
|
||||
// Dictionary<int, double> priceDict = new Modules.MarginModule.eod_commodity_future_priceBLLBak().GetEodPriceToId(codes, currentDate, isClosePrice ? 2 : 3);
|
||||
// return priceDict;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,578 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.BLL.Calculation.V2;
|
||||
//using YLErp.Commons;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.Modules.DataCacheModule;
|
||||
//using YLErp.Modules.MarginModule;
|
||||
//using YLErp.QdpModule;
|
||||
//using CalculatorHelper = YLErp.BLL.Calculation.CalculatorHelperOld;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 瑞达保证金计算
|
||||
// /// </summary>
|
||||
// public class RDMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly RDMarginCalculation Instance;
|
||||
|
||||
// static RDMarginCalculation()
|
||||
// {
|
||||
// Instance = new RDMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// protected RDMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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)
|
||||
// {
|
||||
// //结果集
|
||||
// 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 = GetSettlePrice(codes, settleDate, "收盘价");
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// var underlyingIds = priceDict.Keys.ToList();
|
||||
|
||||
// //获取标的涨跌幅限制
|
||||
// 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;
|
||||
// }
|
||||
|
||||
// //2.涨跌停板幅度
|
||||
// if (!string.IsNullOrWhiteSpace(t.UpDownLimit))
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.UpDownLimit;//百分比或绝对值
|
||||
// DownLimitDict[t.id] = t.UpDownLimit;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// UpLimitDict[t.id] = t.defUpLimit?.ToString() ?? "5%";
|
||||
// DownLimitDict[t.id] = t.defDownLimit?.ToString() ?? "5%";
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// if (!hasOptionInfo)
|
||||
// {
|
||||
// tradeBLL.SetFieldsByTradeType(tradeList);
|
||||
// }
|
||||
|
||||
// //判断当日结算价是否已经入库
|
||||
// //if (priceDict == null || priceDict.Count == 0)
|
||||
// //{
|
||||
// // throw new Exception("当日结算价还未同步,请等待结算价自动同步完成或手动同步后再执行收盘操作!");
|
||||
// //}
|
||||
|
||||
// var tradeVolatilityRateDic = tradeList.ToDictionary(t => t.id, t => priceDict[t.UnderlyingId] / t.ActualStrike < 0.9 && t.OptionType == "看涨" || priceDict[t.UnderlyingId] / t.ActualStrike > 1.1 && t.OptionType == "看跌" ? 0.2 : (umVolatilityRateDic.ContainsKey(t.UnderlyingId) ? umVolatilityRateDic[t.UnderlyingId] : 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 upLimitPricesTwoThirds = new Dictionary<int, double>();
|
||||
// var upLimitPricesOneThird = new Dictionary<int, double>();
|
||||
// var downLimitPrices = new Dictionary<int, double>();
|
||||
// var downLimitPricesTwoThirds = new Dictionary<int, double>();
|
||||
// var downLimitPricesOneThird = new Dictionary<int, double>();
|
||||
// var normalLimitPrices = new Dictionary<int, double>();
|
||||
// double tempDouble;
|
||||
// //根据涨跌幅限制以及当日结算价计算涨停价以及跌停价
|
||||
// if (priceDict != null && priceDict.Count > 0)
|
||||
// {
|
||||
// foreach (var t in priceDict)
|
||||
// {
|
||||
// //OTC-8856 Start
|
||||
// //UpLimit
|
||||
// if (UpLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = UpLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// upLimitPrices[t.Key] = t.Value * (1 + (tempDouble * 0.01));
|
||||
// upLimitPricesTwoThirds[t.Key] = t.Value * (1 + (tempDouble * 0.01) * 2.0 / 3.0);
|
||||
// upLimitPricesOneThird[t.Key] = t.Value * (1 + (tempDouble * 0.01) / 3.0);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// upLimitPrices[t.Key] = t.Value + Math.Abs(tempAbs);
|
||||
// upLimitPricesTwoThirds[t.Key] = t.Value + Math.Abs(tempAbs) * 2.0 / 3.0;
|
||||
// upLimitPricesOneThird[t.Key] = t.Value + Math.Abs(tempAbs) / 3.0;
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// upLimitPrices[t.Key] = t.Value * (1 + 0.05);
|
||||
// upLimitPricesTwoThirds[t.Key] = t.Value * (1 + 0.05 * 2.0 / 3.0);
|
||||
// upLimitPricesOneThird[t.Key] = t.Value * (1 + 0.05 / 3.0);
|
||||
// }
|
||||
|
||||
// //DownLimit
|
||||
// if (DownLimitDict.ContainsKey(t.Key))
|
||||
// {
|
||||
// var tempVaue = DownLimitDict[t.Key];
|
||||
// if (tempVaue.Contains("%"))
|
||||
// {
|
||||
// //百分比
|
||||
// double.TryParse(tempVaue.Replace("%", ""), out tempDouble);
|
||||
// downLimitPrices[t.Key] = t.Value * (1 - (tempDouble * 0.01));
|
||||
// downLimitPricesTwoThirds[t.Key] = t.Value * (1 - (tempDouble * 0.01) * 2.0 / 3.0);
|
||||
// downLimitPricesOneThird[t.Key] = t.Value * (1 - (tempDouble * 0.01) / 3.0);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //绝对值
|
||||
// double.TryParse(tempVaue, out double tempAbs);
|
||||
// downLimitPrices[t.Key] = t.Value - Math.Abs(tempAbs);
|
||||
// downLimitPricesTwoThirds[t.Key] = t.Value - Math.Abs(tempAbs) * 2.0 / 3.0;
|
||||
// downLimitPricesOneThird[t.Key] = t.Value - Math.Abs(tempAbs) / 3.0;
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// downLimitPrices[t.Key] = t.Value * (1 - 0.05);
|
||||
// downLimitPricesTwoThirds[t.Key] = t.Value * (1 - 0.05 * 2.0 / 3.0);
|
||||
// downLimitPricesOneThird[t.Key] = t.Value * (1 - 0.05 / 3.0);
|
||||
// }
|
||||
|
||||
// //Normal
|
||||
// normalLimitPrices[t.Key] = t.Value;
|
||||
// }
|
||||
// eodPriceDict["up"] = upLimitPrices;
|
||||
// eodPriceDict["upTwoThirds"] = upLimitPricesTwoThirds;
|
||||
// eodPriceDict["upOneThird"] = upLimitPricesOneThird;
|
||||
// eodPriceDict["down"] = downLimitPrices;
|
||||
// eodPriceDict["downTwoThirds"] = downLimitPricesTwoThirds;
|
||||
// eodPriceDict["downOneThird"] = downLimitPricesOneThird;
|
||||
// eodPriceDict["normal"] = normalLimitPrices;
|
||||
// }
|
||||
// //波动率变化
|
||||
// var addVolRateList = new List<Dictionary<int, double>> { null, tradeVolatilityRateDic };
|
||||
// //交易对应客户信息
|
||||
// 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();
|
||||
|
||||
// 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;
|
||||
// }
|
||||
// else if (item.Trade.TradeType == "权益互换")
|
||||
// {
|
||||
// value = (item.Trade.trade_swap.GetMarginRate ?? 0) * (item.Trade.StockEqvNotional ?? 0) + Math.Max((double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv), 0);
|
||||
// }
|
||||
// if (resultMap.ContainsKey(item.Trade.id))
|
||||
// {
|
||||
// switch (key)
|
||||
// {
|
||||
// case "up_1":
|
||||
// resultMap[item.Trade.id].Spv1 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "upTwoThirds_1":
|
||||
// resultMap[item.Trade.id].Spv2 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "upOneThird_1":
|
||||
// resultMap[item.Trade.id].Spv3 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_1":
|
||||
// resultMap[item.Trade.id].Spv4 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// resultMap[item.Trade.id].Spv5 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "downTwoThirds_1":
|
||||
// resultMap[item.Trade.id].Spv6 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "downOneThird_1":
|
||||
// resultMap[item.Trade.id].Spv7 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_0":
|
||||
// resultMap[item.Trade.id].Delta = item.ValueResult.Delta;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// resultMap[item.Trade.id].setWorstCastClientPayable8();
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// var trade = tradeList.FirstOrDefault(t => t.id == item.Trade.id);
|
||||
// var underlying = DataCacheManager.GetUnderlyingDataSource().GetData(trade.UnderlyingCode);
|
||||
// var tempTradeSpan = new trade_span
|
||||
// {
|
||||
// TradeId = item.Trade.id,
|
||||
// ClientId = trade.ClientId,
|
||||
// ValueDate = settleDate,
|
||||
// VarietyId = underlying.UnderlyingTypeId,
|
||||
// UnderlyingId = trade.UnderlyingId,
|
||||
// UnderlyingCode = trade.UnderlyingCode,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now
|
||||
// };
|
||||
// switch (key)
|
||||
// {
|
||||
// case "up_1":
|
||||
// tempTradeSpan.Spv1 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "upTwoThirds_1":
|
||||
// tempTradeSpan.Spv2 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "upOneThird_1":
|
||||
// tempTradeSpan.Spv3 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_1":
|
||||
// tempTradeSpan.Spv4 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "down_1":
|
||||
// tempTradeSpan.Spv5 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "downTwoThirds_1":
|
||||
// tempTradeSpan.Spv6 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "downOneThird_1":
|
||||
// tempTradeSpan.Spv7 = item.Trade.TradeType == "自定义交易" || item.Trade.TradeType == "权益互换" ? value : (double.IsNaN(item.ValueResult.Pv) ? 0 : item.ValueResult.Pv) * clientRatio;
|
||||
// break;
|
||||
// case "normal_0":
|
||||
// tempTradeSpan.Delta = item.ValueResult.Delta;
|
||||
// break;
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// resultMap[item.Trade.id] = tempTradeSpan;
|
||||
// }
|
||||
|
||||
// resultMap[item.Trade.id].UnderlyingPrice = priceDict[item.Trade.UnderlyingId];
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// //上面的计算用到静态生成market,需要清除
|
||||
// QdpMarketManager.Instance.RemovePrebuiltMarketProxy(userIdNew);
|
||||
// }
|
||||
|
||||
// return resultMap.Values.ToList();
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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())
|
||||
// {
|
||||
// var underlyingCodes = tradeSpans.Select(t => t.UnderlyingCode).ToHashSet();
|
||||
// var mpProvider = new MarginParamProvider(new OptUserInfo(0, "系统"), settleDate).Initialize(underlyingCodes, MarginParamTypeEnum.MarginRate);
|
||||
|
||||
// //删除
|
||||
// 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)
|
||||
// {
|
||||
// #region Span Margin Method
|
||||
|
||||
// var underlyingGroup = clientGroup.GroupBy(t => t.trade.UnderlyingId).Select(t => new client_span
|
||||
// {
|
||||
// UnderlyingId = t.Key,
|
||||
// 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),
|
||||
// Spv5 = t.Sum(g => g.tradeSpan.Spv5) * (-1),
|
||||
// Spv6 = t.Sum(g => g.tradeSpan.Spv6) * (-1),
|
||||
// Spv7 = t.Sum(g => g.tradeSpan.Spv7) * (-1),
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// SpanType = SpanType
|
||||
// }).ToList();
|
||||
// foreach (var item in underlyingGroup)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(item.Spv1 ?? 0, item.Spv2 ?? 0), item.Spv3 ?? 0), item.Spv4 ?? 0), item.Spv5 ?? 0), item.Spv6 ?? 0), item.Spv7 ?? 0);
|
||||
|
||||
// #region 更新tradeSpan,使得每笔交易的持仓保证金和客户保证金计算用的Spv组保持一致
|
||||
|
||||
// var tradeSpansUpdate = db.trade_span.Where(x => x.ClientId == item.ClientId && x.UnderlyingId == item.UnderlyingId && x.ValueDate == settleDate).ToList();
|
||||
// if (item.WorstCastClientPayable == item.Spv1)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv1);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv2)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv2);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv3)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv3);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv4)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv4);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv5)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv5);
|
||||
// }
|
||||
// else if (item.WorstCastClientPayable == item.Spv6)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv6);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x => x.WorstCastClientPayable = x.Spv7);
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// if (!PS.Config.ErpElement.NonInterBankMarginNetting)
|
||||
// {
|
||||
// item.WorstCastClientPayable = Math.Min(item.WorstCastClientPayable.Value, 0);
|
||||
// }
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// #region Delta Margin Method
|
||||
|
||||
// var varietyGroup = clientGroup.GroupBy(t => t.trade.VarietyId).Select(t => new client_span
|
||||
// {
|
||||
// VarietyId = t.Key,
|
||||
// ClientId = clientGroup.Key,
|
||||
// ValueDate = settleDate,
|
||||
// MaxSpotPrice = t.Max(g => g.tradeSpan.UnderlyingPrice),
|
||||
// DeltaSell = t.Sum(g => -g.tradeSpan.Delta * (g.trade.BuySell == "买入" ? 1 : 0)),
|
||||
// DeltaBuy = t.Sum(g => -g.tradeSpan.Delta * (g.trade.BuySell == "卖出" && g.tradeSpan.Delta < 0 ? 1 : 0)),
|
||||
// DeltaBuyMinus = t.Sum(g => -g.tradeSpan.Delta * (g.trade.BuySell == "卖出" && g.tradeSpan.Delta > 0 ? 1 : 0)),
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// SpanType = SpanType
|
||||
// }).ToList();
|
||||
|
||||
// foreach (var item in varietyGroup)
|
||||
// {
|
||||
// #region 更新tradeSpan,通过Delta品种级别求和算法,给tradeSpan的deltaMargin赋值
|
||||
|
||||
// var marginRate = mpProvider.GetVarietyData(item.VarietyId ?? 0, MarginParamTypeEnum.MarginRate);
|
||||
|
||||
// var tradeSpansUpdate = db.trade_span.Where(x => x.ClientId == item.ClientId && x.VarietyId == item.VarietyId && x.ValueDate == settleDate).ToList();
|
||||
// //DeltaSell为客户角度卖出,且为客户角度看Delta
|
||||
// if (item.DeltaSell > 0)
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x =>
|
||||
// {
|
||||
// var trade = tradeSpanInfo.FirstOrDefault(y => y.trade.id == x.TradeId).trade;
|
||||
// //客户角度卖出的交易
|
||||
// //客户角度买入的交易,客户角度Delta<0,即交易员角度Delta>0
|
||||
// if (trade.BuySell == "买入" || x.Delta > 0)
|
||||
// {
|
||||
// x.DeltaMargin = -x.Delta * item.MaxSpotPrice * marginRate;
|
||||
// }
|
||||
// });
|
||||
// item.DeltaMargin = -Math.Max((item.DeltaSell ?? 0 + item.DeltaBuyMinus ?? 0), 0) * item.MaxSpotPrice * marginRate;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// tradeSpansUpdate.ForEach(x =>
|
||||
// {
|
||||
// var trade = tradeSpanInfo.FirstOrDefault(y => y.trade.id == x.TradeId).trade;
|
||||
// //客户角度卖出的交易
|
||||
// //客户角度买入的交易,客户角度Delta>0,即交易员角度Delta<0
|
||||
// if (trade.BuySell == "买入" || x.Delta < 0)
|
||||
// {
|
||||
// x.DeltaMargin = x.Delta * item.MaxSpotPrice * marginRate;
|
||||
// }
|
||||
// });
|
||||
// item.DeltaMargin = Math.Min((item.DeltaSell ?? 0 + item.DeltaBuyMinus ?? 0), 0) * item.MaxSpotPrice * marginRate;
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
// 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),
|
||||
// Spv5 = underlyingGroup.Sum(g => g.Spv5),
|
||||
// Spv6 = underlyingGroup.Sum(g => g.Spv6),
|
||||
// Spv7 = underlyingGroup.Sum(g => g.Spv7),
|
||||
// DeltaMargin = varietyGroup.Sum(g => g.DeltaMargin),
|
||||
// //负数代表客户应缴保证金,正数代表客户应收保证金
|
||||
// WorstCastClientPayable = underlyingGroup.Sum(g => g.WorstCastClientPayable) < 0 ? underlyingGroup.Sum(g => g.WorstCastClientPayable) : 0,
|
||||
// OptId = userId,
|
||||
// OptName = userName,
|
||||
// OptDate = DateTime.Now,
|
||||
// SpanType = SpanType,
|
||||
// AdditionalWorstCastClientPayable = clientAdditionalMarginDic == null ? 0 : (clientAdditionalMarginDic.ContainsKey(clientGroup.Key ?? 0) ? clientAdditionalMarginDic[clientGroup.Key ?? 0] : 0)
|
||||
// };
|
||||
// if (clientSpan.WorstCastClientPayable > clientSpan.DeltaMargin)
|
||||
// {
|
||||
// clientSpan.WorstCastClientPayable = clientSpan.DeltaMargin;
|
||||
// }
|
||||
// clientSpanNews.Add(clientSpan);
|
||||
// }
|
||||
|
||||
// //span类型为实时删除所有实时计算的交易的保证金信息
|
||||
// if (SpanType == client_span.SpanType_RealTime)
|
||||
// {
|
||||
// if (RefreshClientIds != null)
|
||||
// {
|
||||
// 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.BulkInsert(db, clientSpanNews);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// 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)
|
||||
// .Select(n => new { n.ValueDate, n.ClientId }).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)
|
||||
// {
|
||||
// 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> { 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,288 +0,0 @@
|
||||
//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
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 申银万国
|
||||
// /// </summary>
|
||||
// public class SYWGMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly SYWGMarginCalculation Instance;
|
||||
|
||||
// static SYWGMarginCalculation()
|
||||
// {
|
||||
// Instance = new SYWGMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private SYWGMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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> tradeSpans = new List<trade_span>();
|
||||
// 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;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 股票类期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> StockMarginCalculation(int userId, string userName, List<trade> tradeList, DateTime settleDate, bool isEodSettle)
|
||||
// {
|
||||
// List<trade_span> tradeSpans = new List<trade_span>();
|
||||
// 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;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 商品期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> FutureMarginCalculation(int userId, string userName, List<trade> futureTradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false, string volType = "交易")
|
||||
// {
|
||||
// if (futureTradeList == null || !futureTradeList.Any())
|
||||
// {
|
||||
// return new List<trade_span>(0);
|
||||
// }
|
||||
|
||||
// var tradeSpans = new List<trade_span>();
|
||||
// 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> { 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,182 +0,0 @@
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using YLErp.DBModels;
|
||||
//using YLErp.DBModels.Consts;
|
||||
//using YLErp.Model;
|
||||
//using YLErp.Modules.MarginModule;
|
||||
|
||||
//namespace YLErp.BLL.MarginCalculationBak
|
||||
//{
|
||||
// public class UniversalMarginCalculation : MarginCalculationBase
|
||||
// {
|
||||
// // 定义一个静态变量来保存类的实例
|
||||
// public static readonly UniversalMarginCalculation Instance;
|
||||
|
||||
// static UniversalMarginCalculation()
|
||||
// {
|
||||
// Instance = new UniversalMarginCalculation();
|
||||
// }
|
||||
|
||||
// // 定义私有构造函数,使外界不能创建该类实例
|
||||
// private UniversalMarginCalculation()
|
||||
// {
|
||||
// }
|
||||
|
||||
// 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> tradeSpans = new List<trade_span>();
|
||||
// if (!(priceDict?.Count > 0))
|
||||
// {
|
||||
// var codes = tradeList.Select(O => O.UnderlyingCode).ToArray();
|
||||
// priceDict = base.GetSettlePrice(codes, settleDate);
|
||||
// }
|
||||
// if (priceDict.Count == 0)
|
||||
// {
|
||||
// //如果价格没有传入也没从数据库获取到,就直接返回,没必要往下运行了。但不应该报错;
|
||||
// return tradeSpans;
|
||||
// }
|
||||
// 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, priceDict, hasOptionInfo, isEodSettle);
|
||||
// if (stockTradeSpanlist.Count > 0)
|
||||
// {
|
||||
// tradeSpans.AddRange(stockTradeSpanlist);
|
||||
// }
|
||||
// }
|
||||
// var tempFutureTradeList = tradeList.Where(t => t.UnderlyingInstrumentType == ConsGlobal.InstrumentType.CommodityFutures).ToList();
|
||||
// if (tempFutureTradeList.Any())
|
||||
// {
|
||||
// var futureTradeSpanlist = FutureMarginCalculation(userId, userName, tempFutureTradeList, settleDate, priceDict, hasOptionInfo, isEodSettle);
|
||||
// if (futureTradeSpanlist.Count > 0)
|
||||
// {
|
||||
// tradeSpans.AddRange(futureTradeSpanlist);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return tradeSpans;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 股票类期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> StockMarginCalculation(int userId, string userName, List<trade> tradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false)
|
||||
// {
|
||||
// throw new Exception("未实现");
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 商品期权计算保证金
|
||||
// /// </summary>
|
||||
// public List<trade_span> FutureMarginCalculation(int userId, string userName, List<trade> futureTradeList, DateTime settleDate, Dictionary<int, double> priceDict, bool hasOptionInfo = false, bool isEodSettle = false)
|
||||
// {
|
||||
// List<trade_span> tradeSpans = new List<trade_span>();
|
||||
// if (futureTradeList != null && futureTradeList.Count > 0)
|
||||
// {
|
||||
// using (YLContext db = new YLContext())
|
||||
// {
|
||||
// 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();
|
||||
|
||||
// var underlyingCodes = futureTradeList.Select(O => O.UnderlyingCode).ToHashSet();
|
||||
// var mpProvider = new MarginParamProvider(new OptUserInfo(0, "系统"), settleDate)
|
||||
// .Initialize(underlyingCodes, MarginParamTypeEnum.MarginRate);
|
||||
|
||||
// if (clientList != null)
|
||||
// {
|
||||
// foreach (var t in futureTradeList)
|
||||
// {
|
||||
// priceDict.TryGetValue(t.UnderlyingId, out double price);
|
||||
// mpProvider.TryGetMarginRate(t.UnderlyingCode, out double marginRate);
|
||||
// var contractSize = (_underlyingDataProvider.GetUnderlying(t.UnderlyingCode)?.ContractSize) ?? 0;
|
||||
// double diffPrice = 0;
|
||||
// switch (t.OptionType)
|
||||
// {
|
||||
// case "看涨":
|
||||
// diffPrice = (t.Strike ?? 0) - price;
|
||||
// break;
|
||||
// case "看跌":
|
||||
// diffPrice = price - (t.Strike ?? 0);
|
||||
// break;
|
||||
// }
|
||||
// double visualValue = Math.Max(diffPrice, 0) * contractSize;
|
||||
// double futureMargin = price * marginRate * contractSize;
|
||||
// double optionMargin1 = (t.StockEqvNotional ?? 0) + futureMargin - 0.5 * visualValue;
|
||||
// double optionMargin2 = (t.StockEqvNotional ?? 0) + futureMargin * 0.5;
|
||||
|
||||
// var client = clientList.FirstOrDefault(c => c.client.id == t.ClientId);
|
||||
// if (client != null)
|
||||
// {
|
||||
// var value = Math.Max(optionMargin1, optionMargin2);
|
||||
|
||||
// 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: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 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> { 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;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
Reference in New Issue
Block a user