Files
zszq-trs/YLErpWeb/Controllers/SwapTradeController.cs
T
2024-05-09 14:06:26 +08:00

1199 lines
48 KiB
C#

using Newtonsoft.Json;
using YLErp.BLL.Eod;
using YLErp.Configuration;
using YLErp.Enums;
using YLErp.Model.Enum;
using YLErp.Models.Tag;
using YLErp.Modules.ClientModule;
using YLErp.Modules.EodModule;
using YLErp.Modules.ReportModule;
using YLErp.Modules.SalesModule;
using YLErp.Modules.TagModule;
using YLErp.Modules.TradeModule;
using YLErp.Modules.TradeModule.SwapModule;
using YLErp.Modules.UnderlyingModule;
using YLErp.QdpModule;
namespace YLErp.Web.Controllers
{
public class SwapTradeController : BaseController
{
[MyAuthorize("交易管理-互换交易")]
public ActionResult TradeList(string settleDate = null, string observationDate = null)
{
ViewBag.settleDate = settleDate ?? "";
ViewBag.observationDate = observationDate;
return View();
}
[MyAuthorize("交易管理-互换交易")]
public ActionResult MultiCloseList()
{
return View();
}
[MyAuthorize("交易管理-交易流水查看")]
public ActionResult TradeFlowList()
{
return View();
}
public ActionResult TradeFlowHistory()
{
return View();
}
public ActionResult TradeFlowCheck()
{
return View();
}
[MyAuthorize("基础参数管理-交易市场")]
public ActionResult ClientVarietyConfigList()
{
return View();
}
[HttpPost]
public JsonResult TradeQuery(TradeReq req)
{
var tss = new TradeSwapService(CurUser);
req.AssetIdList = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.AssetIdList).ToList();
req.UserAssets = CurUser.GetAssetUnitIds();
req.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
var sList = tss.SearchList(req, out var gsum, false);
Dictionary<int, List<TagDto>> tradeTagList = null;
if (sList != null && sList.rows != null && sList.rows.Any())
{
using (var service = new TagService(CurUser))
{
tradeTagList = service.GetTagByTradeIds(sList.rows.Select(p => p.id).Distinct().ToList());
}
}
if (tradeTagList == null)
{
tradeTagList = new Dictionary<int, List<TagDto>>();
}
var tradeids = sList.rows.Select(r => r.id).ToList();
var swapTrades = yldb.trade_swap.Where(t => tradeids.Contains(t.TradeId)).ToList();
var list = yldb.trade_contract_r.Where(O => tradeids.Contains(O.TradeId) && O.IsValid && O.Type == "交易确认书").AsEnumerable();
var contractCodeDict = list.GroupBy(O => O.TradeId).ToDictionary(K => K.Key, V => V.LastOrDefault().ContractCode);
var eodTrades = yldb.eod_trade.Where(t => tradeids.Contains(t.TradeId)).ToList();
var tradeCashPredicate = PredicateBuilder.Create<trade_cash>(n => tradeids.Contains(n.TradeId) && !n.IsDeleted && n.Action == ClientCashInCashOut.系统操作_互换);
if (req.ValueDate != null)
{
tradeCashPredicate = tradeCashPredicate.And(x => (x.HappenedDate ?? x.ValueDate) == req.ValueDate);
}
var cashTrades = yldb.trade_cash.Where(tradeCashPredicate).ToList();
var opencashTrades = yldb.trade_cash.Where(n => tradeids.Contains(n.TradeId) && !n.IsDeleted && n.Action == ClientCashInCashOut.系统操作_期权费).ToList();
var underlyingSource = Modules.DataCacheModule.DataCacheManager.GetUnderlyingDataSource();
foreach (var r in sList.rows)
{
r.trade_swap = swapTrades.FirstOrDefault(x => x.TradeId == r.id);
r.eod_trade = eodTrades.FirstOrDefault(x => x.TradeId == r.id);
r.trade_cash = cashTrades.FirstOrDefault(x => x.TradeId == r.id);
r.MetaDic.Add("PayUnderlyingName", (underlyingSource.GetData(r.trade_swap?.PayUnderlyingCode)?.UnderlyingName) ?? "");
r.MetaDic.Add("GetUnderlyingName", (underlyingSource.GetData(r.trade_swap?.GetUnderlyingCode)?.UnderlyingName) ?? "");
r.ContractCode = contractCodeDict.TryGetValue(r.id, out var code) ? code : "";
if (r.trade_swap.IsGetFloatingProfit)
{
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(r.trade_swap.GetUnderlyingId ?? 0);
if (underlying != null && underlying.ContractSize > 0)
{
r.trade_swap.GetOpenPrice = r.trade_swap.GetSpotPrice + (r.trade_swap.GetLongShort == "多头" ? 1 : -1) * ((r.trade_swap.PaySingleFee ?? 0) / underlying.ContractSize + (r.trade_swap.GetSpotPrice * r.trade_swap.PayUnAnnualRate ?? 0));
r.trade_swap.GetLot = r.trade_swap.GetNotional / underlying.ContractSize;
r.TradeAmount = r.Notional / underlying.CountRatio;
}
}
else if (r.trade_swap.IsPayFloatingProfit)
{
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(r.trade_swap.PayUnderlyingId ?? 0);
if (underlying != null && underlying.ContractSize > 0)
{
r.trade_swap.PayOpenPrice = r.trade_swap.PaySpotPrice + (r.trade_swap.PayLongShort == "多头" ? 1 : -1) * ((r.trade_swap.GetSingleFee ?? 0) / underlying.ContractSize + (r.trade_swap.PaySpotPrice * r.trade_swap.GetUnAnnualRate ?? 0));
r.trade_swap.PayLot = r.trade_swap.PayNotional / underlying.ContractSize;
r.TradeAmount = r.Notional / underlying.CountRatio;
}
}
//拼装标签值
if (tradeTagList.ContainsKey(r.id))
{
r.Tags = tradeTagList[r.id];
r.OutputTags = TagService.GetOutputTagsStr(r.Tags);
}
if (PS.Config.IsGuoJun)
{
r.ClientNumber = DataCacheProvider.GetClientDataSource().GetData(r.ClientId).Number;
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(r.UnderlyingCode);
underlying.Variety = DataCacheProvider.GetVarietyDataSource().GetData(underlying.CommodityCode);
r.QuoteCurrency = underlying.Variety.QuoteCurrency ?? ConsGlobal.Currency.CNY;
r.CountRatio = underlying?.CountRatio ?? 1;
r.UnderlyingName = underlying?.UnderlyingName;
r.trade_swap_gj.LongShort = string.IsNullOrWhiteSpace(r.trade_swap.GetLongShort) ? r.trade_swap.PayLongShort : r.trade_swap.GetLongShort;
r.SpotPrice = r.trade_swap.GetSpotPrice ?? r.trade_swap.PaySpotPrice;
r.trade_swap_gj.OpenPrice = r.trade_swap.GetOpenPrice ?? r.trade_swap.PayOpenPrice;
var opencash = opencashTrades.FirstOrDefault(x => x.TradeId == r.id);
r.trade_swap_gj.OpenCurrencyRate = opencash?.CurrencyRate ?? 1;
r.OriginalStockEqvNotional = r.trade_swap_gj.OpenPrice * r.OriginalNotional * r.trade_swap_gj.OpenCurrencyRate;
r.StockEqvNotional = (r.trade_swap_gj.OpenPrice * r.Notional * r.trade_swap_gj.OpenCurrencyRate) ?? 0;
r.trade_swap_gj.PricingOriginalStockEqvNotional = r.trade_swap_gj.OpenPrice * r.OriginalNotional;
r.trade_swap_gj.PricingStockEqvNotional = r.trade_swap_gj.OpenPrice * r.Notional;
r.trade_swap_gj.TradeCommission = r.trade_swap.GetTradePrice ?? (-r.trade_swap.PayTradePrice) ?? 0;
r.trade_swap_gj.SwapTimeAndRate = r.trade_swap.IsGetFloatingProfit ? r.trade_swap.PaySwapTimeAndRate : r.trade_swap.GetSwapTimeAndRate;
}
}
return Json(sList);
}
[HttpPost]
public JsonResult SearchGroupChildrenList(int id)
{
var trades = new TradeQueryService(CurUser).SearchGroupChildrenList(id);
var tradeids = trades.Select(r => r.id).ToList();
var swapTrades = yldb.trade_swap.Where(t => tradeids.Contains(t.TradeId)).ToList();
foreach (var r in trades)
{
r.trade_swap = swapTrades.FirstOrDefault(x => x.TradeId == r.id);
r.MetaDic.Add("GetUnderlyingName", r.trade_swap.GetUnderlyingCode == null ? "" : Modules.DataCacheModule.DataCacheManager.GetUnderlyingDataSource().GetData(r.trade_swap.GetUnderlyingCode).UnderlyingName);
r.MetaDic.Add("PayUnderlyingName", r.trade_swap.PayUnderlyingCode == null ? "" : Modules.DataCacheModule.DataCacheManager.GetUnderlyingDataSource().GetData(r.trade_swap.PayUnderlyingCode).UnderlyingName);
r.SalesCommission = new SalesCommissionDataService(CurUser).GetTradeCommissionInfo(r.id);
if (PS.Config.ErpElement.SalesCommissionCalculation == "公式1" && r.SalesCommission?.Commission != null)
{
r.SalesCommission.Commission = r.SalesCommission.Commission * r.SalesCommission.SalesIds.Count();
}
}
return Json(trades);
}
[HttpPost]
public JsonResult TradeFlowQuery(TradeFlowReq req)
{
var tss = new TradeSwapService(CurUser);
var sList = tss.SearchFlowList(req);
return Json(sList);
}
[HttpPost]
public JsonResult TradeFlowHistoryQuery(TradeFlowReq req)
{
var tss = new TradeSwapService(CurUser);
var sList = tss.SearchFlowHistoryList(req);
foreach (var item in sList.rows)
{
item.ClientName = ClientDataQueryService.GetClient(item.ClientId).Name;
}
return Json(sList);
}
[HttpPost]
public JsonResult TradeFlowCheckResultQuery(TradeFlowCheckResultReq req)
{
var tss = new SwapTradeFlowCheckService(CurUser);
var sList = tss.SearchFlowCheckResultList(req);
return Json(sList);
}
[HttpPost]
public JsonResult ClientVarietyConfigQuery(ClientVarietyConfigReq req)
{
var tss = new TradeSwapService(CurUser);
var sList = tss.SearchClientVarietyConfigList(req);
return Json(sList);
}
public JsonResult GetBasketUnderlyingDetails(int? underlyingId)
{
var details = new List<trade_swap_detail>();
if (underlyingId == null)
{
return Json(details);
}
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(underlyingId.Value);
if (underlying != null && !string.IsNullOrEmpty(underlying.SubData))
{
var items = JsonConvert.DeserializeObject<List<BasketUnderlyingItem>>(underlying.SubData);
var useWhiteCode = new StockBlackWhiteService(CurUser).GetStockBlackWhiteList(Configuration.Enums.LimitRangeEnum.Swap, out var Codes);
items.ForEach(x =>
{
if (Codes != null && useWhiteCode == Codes.Contains(x.code))
{
return;
}
var underlyingDetail = DataCacheProvider.GetUnderlyingDataSource().GetData(x.code);
details.Add(new trade_swap_detail() { UnderlyingCode = x.code, SpotPrice = underlyingDetail.Price, Notional = x.notional });
});
}
var variety = DataCacheProvider.GetVarietyDataSource().GetData(underlying.UnderlyingTypeId);
return Json(new object[] { details, variety });
}
public JsonResult AjaxGetMultiCloseList(TradeMultiCloseQueryModel queryModel)
{
if (queryModel.PageSize == 0)
{
queryModel.PageIndex = 1;
queryModel.PageSize = 10000;
}
queryModel.AssetIdList = AssetUnitModel.IntersectAssetUnits(queryModel.AssetIdGroupList, queryModel.AssetIdList).ToList();
queryModel.UserAssets = CurUser.GetAssetUnitIds();
queryModel.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
var datas = new SwapMultiCloseService(CurUser).GetPagedDatas(queryModel);
return JsonForJqGrid(datas);
}
/// <summary>
/// 场外成交记录-导出奇异要素
/// </summary>
public ActionResult UnwindMultiFactorsExport(TradeMultiCloseQueryModel queryModel)
{
queryModel.PageIndex = 1;
queryModel.PageSize = 10000;
queryModel.UserAssets = CurUser.GetAssetUnitIds();
queryModel.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
var bytes = new SwapMultiCloseService(CurUser).ExportAllFieldsToExcel(queryModel);
return File(bytes, xlsxMimeType, $"互换了结记录全要素_{DateTime.Now:yyyyMMddHHmmssffff}.xlsx");
}
public ActionResult TradeEdit(string enid, int parentTradeId = 0, bool isUseApproval = false)
{
ViewBag.ParentTradeId = parentTradeId;
ViewBag.isUseApproval = isUseApproval;
using (var tagService = new TagService(CurUser))
{
ViewBag.TagList = tagService.GetTagListByType(TagTypeEnum.Trade);
}
trade r = null;
var isAdd = string.IsNullOrEmpty(enid) || enid == "0";
if (isAdd)
{
if (!CurUser.交易管理_交易新增)
{
throw new Exception("没有新增权限");
}
r = new trade()
{
TradeType = "收益互换",
UnderlyingInstrumentType = "Stock",
StartDate = valuedateBLL.ValueDate,
TradeDate = valuedateBLL.ValueDate,
TraderId = CurUser.UserId,
TraderName = CurUser.UserName,
MarginTemplateName = "系统默认",
OpponentRole = "乙方",
trade_swap = new trade_swap()
{
IsPayFloatingProfit = true,
IsGetFloatingProfit = false,
GetTradePrice = 0,
PayTradePrice = 0,
GetSingleFee = 0,
PaySingleFee = 0,
PayLongShort = "多头",
SwapType = "普通",
AnnualDays = 365,
RateCalcMode = "11"
}
};
if (parentTradeId > 0)
{
var parentTrade = yldb.trade.Find(parentTradeId);
var trade_swap = yldb.trade_swap.FirstOrDefault(x => x.TradeId == parentTradeId);
if (parentTrade != null)
{
r.ClientId = parentTrade.ClientId;
r.ClientName = parentTrade.ClientName;
r.AssetId = parentTrade.AssetId;
r.AssetBookName = parentTrade.AssetBookName;
r.ExerciseDate = parentTrade.ExerciseDate;
}
if (trade_swap != null)
{
r.trade_swap.IsGetFloatingProfit = trade_swap.IsGetFloatingProfit;
r.trade_swap.IsPayFloatingProfit = trade_swap.IsPayFloatingProfit;
r.trade_swap.AnnualDays = trade_swap.AnnualDays;
r.trade_swap.AnnualVarIncome = trade_swap.AnnualVarIncome;
r.trade_swap.RateCalcMode = trade_swap.RateCalcMode;
}
}
return View(r);
}
var intid = DecryptInt(enid);
r = yldb.trade.Find(intid);
r.SettlementDate = r.SettlementDate ?? r.ExerciseDate;
if (r == null)
{
throw new ServiceException("找不到交易数据");
}
if (ConsTrade.审批中 != r.TradeStatus)
{
if (!CurUser.交易管理_交易编辑 && !(ConsTrade.已拒绝 == r.TradeStatus && r.TraderId == CurUser.UserId))
{
throw new Exception("没有编辑权限");
}
}
r.trade_swap = yldb.trade_swap.FirstOrDefault(t => t.TradeId == r.id);
var customizedResultsGet = QdpHelper.ParseAutocallCustomizedInfo(r.trade_swap.GetSwapTimeAndRate);
if (customizedResultsGet.Item2 != null)
{
var getSwapRates = customizedResultsGet.Item2.Distinct();
if (getSwapRates != null && getSwapRates.Count() == 1)
{
r.trade_swap.GetSwapRate = getSwapRates.First();
}
else
{
r.trade_swap.GetSwapRate = customizedResultsGet.Item2.Last();//观察日利率不一致情况,给默认展示到期日利率
}
}
var customizedResultsPay = QdpHelper.ParseAutocallCustomizedInfo(r.trade_swap.PaySwapTimeAndRate);
if (customizedResultsPay.Item2 != null)
{
var paySwapRates = customizedResultsPay.Item2.Distinct();
if (paySwapRates != null && paySwapRates.Count() == 1)
{
r.trade_swap.PaySwapRate = paySwapRates.First();
}
else
{
r.trade_swap.PaySwapRate = customizedResultsPay.Item2.Last();////观察日利率不一致情况,给默认展示到期日利率
}
}
r.get_trade_swap_details = yldb.trade_swap_detail.Where(x => x.TradeId == r.id && x.IsForGet && x.ValidState != "InValid").ToList();
r.pay_trade_swap_details = yldb.trade_swap_detail.Where(x => x.TradeId == r.id && !x.IsForGet && x.ValidState != "InValid").ToList();
r.SalesCommission = new SalesCommissionDataService(CurUser).GetTradeCommissionInfo(r.id);
if (PS.Config.ErpElement.SalesCommissionCalculation == "公式1")
{//计提法只支持百分比;
if (r.SalesCommission.Commission.Normalize() == 0)
{
r.SalesCommission.Commission = 1;
r.SalesCommission.CommissionFixed = false;
}
else
{
r.SalesCommission.Commission = r.SalesCommission.Commission * r.SalesCommission.SalesIds.Count();
}
}
r.MetaDic = new TradeMetaService(CurUser).GetTradeMeta(r.id);
if (r.MetaDic != null && r.MetaDic.ContainsKey("ExchangeRate"))
{
double exchangeRate = 0;
if (double.TryParse(r.MetaDic["ExchangeRate"], out exchangeRate))
{
r.ExchangeRate = exchangeRate;
}
}
if (!string.IsNullOrEmpty(r.trade_swap.GetUnderlyingCode))
{
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(r.trade_swap.GetUnderlyingCode);
r.trade_swap.GetCountRatio = underlying != null ? underlying.CountRatio : 1;
r.trade_swap.GetContractSize = underlying != null ? underlying.ContractSize : 100;
r.trade_swap.GetLot = r.trade_swap.GetContractSize > 0 ? r.trade_swap.GetNotional / r.trade_swap.GetContractSize : 0;
}
if (!string.IsNullOrEmpty(r.trade_swap.PayUnderlyingCode))
{
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(r.trade_swap.PayUnderlyingCode);
r.trade_swap.PayCountRatio = underlying != null ? underlying.CountRatio : 1;
r.trade_swap.PayContractSize = underlying != null ? underlying.ContractSize : 100;
r.trade_swap.PayLot = r.trade_swap.PayContractSize > 0 ? r.trade_swap.PayNotional / r.trade_swap.PayContractSize : 0;
}
r.OpponentRole = r.OpponentRole == null ? "乙方" : r.OpponentRole;
using (var tagService = new TagService(CurUser))
{
ViewBag.ModelTags = tagService.GetTagByTradeId(intid);
}
return View(r);
}
[MyAuthorize("交易管理-交易搜索")]
public ActionResult tradeConfirmList(int tabIndex = (int)TradeTabIndexEnum.今日成交)
{
ViewBag.TabIndex = tabIndex;
return View();
}
[MyAuthorize("交易管理-交易搜索")]
public ActionResult tradePreEndList(int tabIndex = (int)TradeTabIndexEnum.今日成交)
{
ViewBag.TabIndex = tabIndex;
return View();
}
/// <summary>
/// 导入互换交易
/// </summary>
public JsonResult UploadSwapTrade()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!System.IO.Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeImportService(CurUser).ImportSwapTradesFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
/// <summary>
/// 导入互换交易历史数据
/// </summary>
public JsonResult UploadSwapTradeHistoryData()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!System.IO.Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeImportService(CurUser).ImportSwapTradeHistroyDataFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
/// <summary>
/// 导入了结互换交易历史数据
/// </summary>
/// <returns></returns>
public JsonResult UploadToEndSwapTradeHistoryData()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!System.IO.Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeImportService(CurUser).ImportToEndSwapTradeHistroyDataFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
/// <summary>
///
/// </summary>
/// <param name="tradeids"></param>
/// <param name="isBatch">是否批量延期结算</param>
/// <returns></returns>
[MyAuthorize("交易管理-交易延期结算")]
public ActionResult tradeDelaySettlement(string tradeids, bool isBatch = false)
{
ViewBag.tradeids = tradeids;
ViewBag.count = tradeids.Split(',').Count();
ViewBag.isBatch = isBatch;
return View();
}
[MyAuthorize("交易管理-交易延期结算")]
public JsonResult tradeDelaySettlementquery(string tradeids, int settlementvalue)
{
if (string.IsNullOrWhiteSpace(tradeids))
{
return JsonError("交易id不能为空");
}
new Modules.TradeModule.DealModule.TradeDelaySettlementService(CurUser).ExecuteDelaySettlements(tradeids, settlementvalue, out string msg);
return JsonSuccess(msg);
}
/// <summary>
/// 导入了结互换交易
/// </summary>
public JsonResult UploadToEndSwapTrade()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!System.IO.Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeImportService(CurUser).ImportToEndSwapTradesFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
/// <summary>
/// 当日成交查询。
/// 查询在当前交易日成交,或在当前交易日被修改过状态的交易
/// </summary>
[HttpPost]
public JsonResult tradeOnValueDateQuery(TdTradeQueryModel req)
{
req.AssetIds = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.AssetIds).ToList();
req.UserAssets = CurUser.GetAssetUnitIds();
req.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
req.OtcTradeType = DBModels.Enums.OtcTradeType.EquitySwap;
var sList = new TodayTradeQueryService(CurUser).GetConfirmList(req);
var tradeids = sList.rows.Select(r => r.id).ToList();
var swapTrades = yldb.trade_swap.Where(t => tradeids.Contains(t.TradeId)).ToList();
foreach (var r in sList.rows)
{
r.trade_swap = swapTrades.FirstOrDefault(x => x.TradeId == r.id);
r.MetaDic.Add("PayUnderlyingName", (r.trade_swap != null && r.trade_swap.PayUnderlyingCode != null) ? Modules.DataCacheModule.DataCacheManager.GetUnderlyingDataSource().GetData(r.trade_swap.PayUnderlyingCode).UnderlyingName : "");
r.MetaDic.Add("GetUnderlyingName", (r.trade_swap != null && r.trade_swap.GetUnderlyingCode != null) ? Modules.DataCacheModule.DataCacheManager.GetUnderlyingDataSource().GetData(r.trade_swap.GetUnderlyingCode).UnderlyingName : "");
}
return Json(sList);
}
/// <summary>
/// 当日成交而几个tab的交易总数。
/// </summary>
[HttpPost]
public JsonResult tradeCountsOnValueDateQuery()
{
var userAssets = CurUser.GetAssetUnitIds();
var userClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
var sum = new TodayTradeQueryService(CurUser).GetTdTradesCountSum(userAssets, userClients, DBModels.Enums.OtcTradeType.EquitySwap);
var countDic = new Dictionary<int, int> {
{(int)TradeTabIndexEnum.今日到期,sum.TdExerciseCount },
{(int)TradeTabIndexEnum.今日终止,sum.TdEarlyStoppedCount },
{(int)TradeTabIndexEnum.今日成交,sum.TdCreatedCount }
};
return Json(countDic);
}
[MyAuthorize("风险控制-日终持仓风险_互换")]
public ViewResult EodPositionRisks()
{
ViewBag.lastDate_eod = EodOperationBase.GetLastSettlementDate(valuedateBLL.ValueDate);
ViewBag.lastDate_settle = EodOperationBase.GetLastSettlementDate_Settle();
return View();
}
[MyAuthorize("风险控制-日终持仓风险_互换")]
public JsonResult EodPositionRisksQuery(EodPositionRisksReq req)
{
req.BookIds = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.BookIds).ToList();
req.UserAssets = CurUser.GetAssetUnitIds();
req.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
if (CurUser.交易管理_查看所有交易) { req.UserClients.Clear(); }
req.TradeTypes = new List<string>() { "收益互换" };
var result = new EodPositionRisksQueryService(CurUser).SearchList(req, true);
var tradeids = result.rows.Select(x => x.trade?.id ?? 0).ToHashSet();
var parentTradeIds = result.rows.Select(x => x.trade?.ParentTradeId).ToHashSet();
var tradeSwaps = yldb.trade_swap.Where(x => tradeids.Contains(x.TradeId)).ToDictionary(n => n.TradeId);
var parentTrades = yldb.trade.Where(x => parentTradeIds.Contains(x.id)).ToDictionary(n => n.id);
foreach (var row in result.rows)
{
if (row.trade == null)
{
continue;
}
if (tradeSwaps.TryGetValue(row.trade.id, out var swap))
{
row.trade.trade_swap = swap;
}
if (parentTrades.TryGetValue(row.trade.ParentTradeId, out var parentTrade))
{
row.ContractCode = parentTrade.TradeNumber;
}
row.trade.MetaDic["GetUnderlyingName"] = string.IsNullOrWhiteSpace(row.trade.trade_swap.GetUnderlyingCode) ? "" : DataCacheProvider.GetUnderlyingDataSource().GetData(row.trade.trade_swap.GetUnderlyingCode)?.UnderlyingName;
row.trade.MetaDic["PayUnderlyingName"] = string.IsNullOrWhiteSpace(row.trade.trade_swap.PayUnderlyingCode) ? "" : DataCacheProvider.GetUnderlyingDataSource().GetData(row.trade.trade_swap.PayUnderlyingCode)?.UnderlyingName;
}
result.rows = result.rows.Where(a => a.trade != null).ToList();
return Json(result);
}
/// <summary>
/// 日终持仓风险导出
/// </summary>
public ActionResult DownloadEodPositionRisks(EodPositionRisksReq req)
{
try
{
req.BookIds = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.BookIds).ToList();
req.UserAssets = CurUser.GetAssetUnitIds();
req.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
if (CurUser.交易管理_查看所有交易) { req.UserClients.Clear(); }
req.TradeTypes = new List<string>() { "收益互换" };
var bytes = new EodPositionRisksQueryService(CurUser).ExportEodPositionRisksToExcel_Swap(req);
return File(bytes, xlsxMimeType, $"日终-{req.ValueDate:yyyy-MM-dd}.xlsx");
}
catch (Exception e)
{
return ShowError("导出失败" + e.Message);
}
}
public JsonResult BatchDownloadEodPositionRisks(EodPositionRisksReq req)
{
if (!new EodPositionRisksQueryService(CurUser).BatchDownloadEodPositionRisks_Swap(req))
{
return JsonError("线程正在被占用");
}
return JsonSuccess("开始生成文件");
}
public ActionResult SwapTradeUpload()
{
return View();
}
public ActionResult tradeUpload()
{
return View();
}
public ActionResult tradeFlowGroupUpload()
{
return View();
}
public ActionResult tradeFlowHistoryUpload()
{
return View();
}
public ActionResult clientVarietyConfigUpload()
{
return View();
}
/// <summary>
/// 导入互换流水
/// </summary>
public ActionResult UploadSwapTradeFlow()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeFlowImportService(CurUser).ImportSwapTradeFlowFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
/// <summary>
/// 导入多空互换流水
/// </summary>
public ActionResult UploadSwapTradeFlowGroup()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeFlowImportService(CurUser).ImportSwapTradeFlowGroupFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
public ActionResult UploadTradeFlowHistory()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeFlowImportService(CurUser).ImportTradeFlowHistoryFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
public ActionResult UploadClientVarietyConfig()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeImportService(CurUser).UploadClientVarietyConfig(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
public ActionResult tradeFlowEdit(string enid)
{
if (string.IsNullOrEmpty(enid))
{
return View(new trade_swap_flow());
}
var intid = DecryptInt(enid);
var tradeFlow = yldb.trade_swap_flow.Find(intid);
if (tradeFlow.UnAnnualRate != null)
{
tradeFlow.UnAnnualRate *= 100;
}
return View(tradeFlow);
}
public ActionResult clientVarietyConfigEdit(string enid)
{
if (string.IsNullOrEmpty(enid))
{
return View(new client_variety_config() { ValueDate = valuedateBLL.ValueDate });
}
var intid = DecryptInt(enid);
var clientVarietyConfig = yldb.client_variety_config.Find(intid);
return View(clientVarietyConfig);
}
[HttpPost]
public JsonResult deleteClientVarietyConfig(string enid)
{
var intid = DecryptInt(enid);
var r = yldb.client_variety_config.Find(intid);
if (r == null)
{
return JsonError("该数据已不存在");
}
yldb.client_variety_config.Remove(r);
yldb.SaveChanges();
return JsonSuccess("删除成功");
}
[HttpPost]
public JsonResult tradeFlowEditJson(trade_swap_flow req)
{
if (req == null)
{
return JsonError("数据不能为空");
}
try
{
var r = new TradeSwapService(CurUser).AddOrUpdateTradeFlowOnly(req);
return JsonSuccess("更新成功", r);
}
catch (Exception e)
{
LogFactory.GetLogger("交易保存").Error(e);
return JsonError("保存失败:" + e.GetBaseException().Message, e.ToJson());
}
}
public JsonResult deleteTradeFlow(string enid)
{
try
{
var intid = DecryptInt(enid);
new TradeSwapService(CurUser).DeleteTradeFlowOnly(intid);
return JsonSuccess("删除成功");
}
catch (Exception e)
{
LogFactory.GetLogger("交易保存").Error(e);
return JsonError("删除失败:" + e.GetBaseException().Message, e.ToJson());
}
}
public JsonResult composeTrade(List<int> ids)
{
new TradeSwapService(CurUser).ComposeTrade(ids);
return JsonSuccess("合成成功");
}
public JsonResult composeTodayTradeFlow(string tradeNumber)
{
new EodHandleSwapFlowService(CurUser).ComposeGroupTrade(tradeNumber);
if (string.IsNullOrWhiteSpace(tradeNumber))
{
new TradeSwapService(CurUser).FIFOTradeFlow();
}
return JsonSuccess("合成成功");
}
public JsonResult checkTradeFlow(string tradeNumber)
{
new SwapTradeFlowCheckService(CurUser).CheckSwapTradeFlow(tradeNumber);
return JsonSuccess("检测完成");
}
public JsonResult checkTradeGroup(string tradeNumber)
{
var result = new SwapTradeFlowCheckService(CurUser).CheckSwapTradeGroup(tradeNumber);
return Json(result);
}
[HttpPost]
public JsonResult clientVarietyConfigEditJson(client_variety_config req)
{
if (req == null)
{
return JsonError("数据不能为空");
}
try
{
var r = new TradeSwapService(CurUser).SaveClientVarietyConfig(req);
return JsonSuccess("更新成功", r);
}
catch (Exception e)
{
LogFactory.GetLogger("交易保存").Error(e);
return JsonError("保存失败:" + e.GetBaseException().Message, e.ToJson());
}
}
public object ExportTradeFlowInfo()
{
var bytes = new SettlementReportForZJService(CurUser).exportFlowInfo();
return File(bytes, xlsxMimeType, $"南向流水全量数据-{DateTime.Now:yyyy-MM-dd}.xlsx");
}
public object ExportTradeCashInfo()
{
var bytes = new SettlementReportForZJService(CurUser).exportCashInfo();
return File(bytes, xlsxMimeType, $"南向资金全量数据-{DateTime.Now:yyyy-MM-dd}.xlsx");
}
public object ExportTradeOpenInfo()
{
var bytes = new SettlementReportForZJService(CurUser).exportOpenFlow();
return File(bytes, xlsxMimeType, $"开仓信息.xlsx");
}
///// <summary>
///// 场外成交记录-导出奇异要素
///// </summary>
//public object DownloadTradeQueryMultiFactors(TradeReq req, string VolType)
//{
// req.LoginUserId = CurUser.UserId;
// req.AssetIdList = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.AssetIdList).ToList();
// var bytes = new OtcTradeListExportService(CurUser).ExportOptionTradeListToExcel(req, new TradeQueryRequest
// {
// ShowAllTrades = ShowAllTrades,
// UserAssetUnits = ShowAllTrades ? null : GetUserAssetunitIds(),
// VolType = VolType
// });
// return File(bytes, xlsxMimeType, $"场外期权成交记录-{DateTime.Now:yyyy-MM-dd}.xlsx");
//}
/// <summary>
/// 场外成交记录-导出奇异要素
/// </summary>
public ActionResult UnwindSwapTradeExport(TradeMultiCloseQueryModel queryModel)
{
var userAsset = GetUserAssetunitIds();
var bytes = new SwapTradeListExportService(CurUser).ExportAllFieldsToExcel(queryModel, userAsset, ShowAllTrades);
return File(bytes, xlsxMimeType, $"互换交易平仓记录.xlsx");
}
#region 交易流水 -- 国君
[MyAuthorize("交易管理-交易流水查看")]
public ActionResult TradeFlowListMore()
{
return View();
}
[MyAuthorize("交易管理-交易流水查看")]
[HttpPost]
public JsonResult TradeFlowMoreQuery(TradeFlowMoreReq req)
{
var tss = new TradeSwapService(CurUser);
var sList = tss.SearchFlowMoreList(req);
return Json(sList);
}
/// <summary>
/// 导入互换交易
/// </summary>
[MyAuthorize("交易管理-交易流水修改")]
public ActionResult UploadSwapTradeFlowMore()
{
if (Request.Form.Files.Count == 0)
{
return JsonError("上传文件不存在");
}
var file = Request.Form.Files[0];
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
return JsonError("请上传Excel(.xlsx)格式文件");
}
using var stream = file.OpenReadStream();
new SwapTradeFlowMoreImportService(CurUser).ImportSwapTradeFlowFromExcel(stream, out var TotalNum, out var SuccessNum);
return Json(new
{
success = true,
totalNum = TotalNum,
successNum = SuccessNum,
});
}
[MyAuthorize("交易管理-交易流水修改")]
public ActionResult tradeFlowMoreEdit(string enid)
{
if (string.IsNullOrEmpty(enid))
{
return JsonError("交易流水不存在");
}
var intid = DecryptInt(enid);
var tradeFlow = yldb.trade_swap_flow_more.Find(intid);
return View(tradeFlow);
}
[MyAuthorize("交易管理-交易流水修改")]
[HttpPost]
public JsonResult tradeFlowMoreEditJson(trade_swap_flow_more req)
{
if (req == null)
{
return JsonError("数据不能为空");
}
try
{
var r = new TradeSwapService(CurUser).SaveTradeFlowMore(req);
return JsonSuccess("更新成功", r);
}
catch (Exception e)
{
LogFactory.GetLogger("交易保存").Error(e);
return JsonError("保存失败:" + e.GetBaseException().Message, e.ToJson());
}
}
[MyAuthorize("交易管理-交易流水修改")]
[HttpPost]
public JsonResult tradeFlowMoreDele(string enid)
{
if (string.IsNullOrEmpty(enid))
{
return JsonError("交易流水不存在");
}
var intid = DecryptInt(enid);
var tradeFlow = yldb.trade_swap_flow_more.Find(intid);
if (tradeFlow.IsCompose)
{
return JsonSuccess("完成合成后禁止删除");
}
tradeFlow.IsDelete = true;
yldb.SaveChanges();
return JsonSuccess("删除成功");
}
public JsonResult FlowMoreComposeTrade()
{
if (!yldb.trade_swap_flow_more.Where(x => !x.IsCompose && !x.IsDelete).Any())
{
throw new ServiceException("不存在未合成的交易流水");
}
new TradeSwapService(CurUser).FlowMoreComposeTrade();
return JsonSuccess("合成成功");
}
[MyAuthorize("交易管理-交易流水修改")]
public ActionResult FlowMoreModifyRate(string ids)
{
var idsArr = DataConvert.ConvertCommaValuesToInt32Array(ids);
if (idsArr is null || !idsArr.Any(n => n > 0))
{
throw new ArgumentException("ids 参数无效", nameof(ids));
}
var tradeNumbers = yldb.trade_swap_flow_more.Where(x => idsArr.Contains(x.id)).Select(x => x.TradeNumber).ToHashSet().ToList();
ViewBag.ids = ids;
ViewBag.count = idsArr.Count();
ViewBag.tradeNumbers = String.Join(",", tradeNumbers);
return View();
}
[MyAuthorize("交易管理-交易流水修改")]
public JsonResult QueryFlowMoreModifyRate(string ids, double CurrencyRate)
{
var idsArr = DataConvert.ConvertCommaValuesToInt32Array(ids);
new SwapTradeFlowMoreImportService(CurUser).UpdateCurrencyRate(idsArr, CurrencyRate);
return JsonSuccess("修改成功");
}
#endregion
[HttpPost]
public JsonResult GetInitMarginRate(int ClientId, string Type, string UnderlyingCode, string tradeDate)
{
if (PS.Config.Company == CompanyEnum.华安)
{
var udm = DataCacheProvider.GetUnderlyingDataSource().GetData(UnderlyingCode);
double? InitMarginRate = 0;
if (udm != null)
{
if (udm.CommodityCode == "组合标的")
{
SyntheticPriceModel synthetic = new SyntheticUnderlyingPriceService(CurUser).GetPriceModel(UnderlyingCode);
var underlyingCodes = synthetic.SuList.Select(l => l.UnderlyingCode);
double?[] arr = new double?[underlyingCodes.Count()];
int i = 0;
foreach (var item in underlyingCodes)
{
arr[i] = DataCacheProvider.GetUnderlyingDataSource().GetData(item).MarginRate;
i++;
}
InitMarginRate = arr.Max();
}
else
{
InitMarginRate = udm.MarginRate ?? DataCacheProvider.GetVarietyDataSource().GetData(UnderlyingCode).Margin ?? 0;
}
}
return JsonSuccess("", InitMarginRate);
}
var query = yldb.client_marginrate.Where(t => (t.ClientId == ClientId || t.ClientId == 0) && t.Type.Equals(Type == "普通" ? ClientMarginTypeEnum.品种.ToString() : Type));
if ("普通".Equals(Type))
{
var underlying = DataCacheProvider.GetUnderlyingDataSource().GetData(UnderlyingCode);
query = query.Where(t => t.VarietyId == underlying.UnderlyingTypeId);
}
var nowDate = tradeDate == null ? valuedateBLL.ValueDate : DateTime.Parse(tradeDate);
var clientMarginrateList = query.Where(t => t.ValueDate <= nowDate).OrderByDescending(t => t.ValueDate).ToList();
if (clientMarginrateList.Any(t => t.ClientId == ClientId))
{
return JsonSuccess("", clientMarginrateList.Where(t => t.ClientId == ClientId).FirstOrDefault().InitMarginRate);
}
else if (clientMarginrateList.Any(t => t.ClientId == 0))
{
return JsonSuccess("", clientMarginrateList.Where(t => t.ClientId == 0).FirstOrDefault().InitMarginRate);
}
return JsonSuccess("", 0);
}
}
}