using YLErp.BLL.Eod; using YLErp.DBModels.Enums; using YLErp.DBModels.Helpers; using YLErp.Modules.DataProviderModule; namespace YLErp.Modules.ExchangeTradeModule { /// /// 交易持仓服务 /// public class ExchangeTradePositionService : YLBaseService { public ExchangeTradePositionService(OptUserInfo userInfo) : base(userInfo) { } /// /// 同步对冲交易持仓 /// public void ResetExchangeTradePosition() { var valueDate = SystemValueDate; var tdQuery = from trad in DbContext.ExchangeTrade.AsNoTracking() where trad.IsValid select new TdTradePositionEx { TradeType = trad.TradeType, BookId = trad.AssetBookId, InstrumentCode = trad.OptionCode, Position = trad.Notional, BuySell = trad.TradeSide, UnderlyingCode = trad.UnderlyingCode, TradeSinglePrice = trad.TradeSinglePrice }; var positionList = tdQuery.ToList(); var dic = new Dictionary(positionList.Count); foreach (var n in positionList) { var tradeType1 = TradeHelper.GetTradeType1(n.TradeType); var positionType = TradeHelper.GetPositionType(n.BuySell); var key = $"{n.BookId}^{(int)tradeType1}^{n.UnderlyingCode}^{n.InstrumentCode}"; var position = n.IsEod ? n.Position : TradeHelper.GetPositionNotional(n.BuySell, n.Position); var positionCost = n.IsEod ? n.PositionCost : position * n.TradeSinglePrice; if (dic.TryGetValue(key, out var pos)) { System.Diagnostics.Debug.Assert(!n.IsEod); pos.Position += position; pos.PositionCost += positionCost; } else { dic[key] = pos = new TradePosition { TradeType = n.TradeType, BookId = n.BookId, InstrumentCode = n.InstrumentCode, TradeType1 = tradeType1, UnderlyingId = n.UnderlyingId, UnderlyingCode = n.UnderlyingCode, CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Position = position, PositionCost = positionCost, PositionType = positionType }; DateTime maturityDate; if (pos.TradeType1 == TradeTypeFlag.Stocks) { maturityDate = DateTime.Today.AddYears(10); } else if (pos.TradeType1 == TradeTypeFlag.Options) { ExchangeOptionDataProvider.TryGetMaturityDate(pos.InstrumentCode, out var date); maturityDate = date; } else if (!UnderlyingDataProvider.TryGetMaturityDate(pos.UnderlyingCode, out maturityDate)) { maturityDate = DateTime.Today.AddMonths(1); } pos.MaturityDate = maturityDate; } } //删除原来的对冲交易 var sql = "truncate trade_position;"; DbContext.Database.ExecuteSqlRaw(sql); DbContext.TradePosition.AddRange(dic.Values); DbContext.SaveChanges(); } class TradePositionEx : TradePositionDto { public virtual bool IsEod => true; public string BuySell { get; set; } public double TradeSinglePrice { get; set; } } class TdTradePositionEx : TradePositionEx { public override bool IsEod => false; } } }