private bool DoAdd() { try { var investingMoney = Math.Abs(Convert.ToDecimal(txtValue.Text.Trim())); var userId = Convert.ToInt32(ddlInvestor.SelectedValue); var user = context.dt_users.Single(u => u.id == userId); if (string.IsNullOrWhiteSpace(user.pay_password)) { JscriptMsg("该用户没有设置交易密码,无法投资", "", "Error"); return(false); } if (!string.Equals(user.pay_password, Utils.MD5(txtTransactPassword.Text))) { JscriptMsg("交易密码错误", "", "Error"); return(false); } TransactionFacade.Invest(userId, projectId, investingMoney); AddAdminLog(DTEnums.ActionEnum.Add.ToString(), ddlInvestor.SelectedItem.Text + " 被添加投资信息: " + investingMoney); //记录日志 return(true); } catch (Exception ex) { JscriptMsg(ex.Message, "", "Error"); return(false); } }
private static void DoCalcProfitingMoney(int projectId, DateTime makeLoanTime) { var context = new Agp2pDataContext(); // 找出未支付的奖励 var projectAtrs = context.li_activity_transactions.Where(atr => atr.activity_type == (byte)Agp2pEnums.ActivityTransactionActivityTypeEnum.InterestRateTicket && atr.status == (byte)Agp2pEnums.ActivityTransactionStatusEnum.Confirm && atr.type == (byte)Agp2pEnums.ActivityTransactionTypeEnum.Gain && atr.transact_time == null && (atr.details.Contains("\"ProjectId\":" + projectId + ",") || atr.details.Contains("\"ProjectId\":" + projectId + "}"))) .ToLookup(atr => atr.dt_users); projectAtrs.ForEach(p => { var wallet = p.Key.li_wallets; p.ForEach(atr => { // 满标时再计算待收益金额 wallet.profiting_money += atr.value; wallet.last_update_time = makeLoanTime; // 修改钱包历史 var his = TransactionFacade.CloneFromWallet(wallet, Agp2pEnums.WalletHistoryTypeEnum.Gaining); his.li_activity_transactions = atr; context.li_wallet_histories.InsertOnSubmit(his); }); }); if (projectAtrs.Any()) { context.SubmitChanges(); } }
internal void InitializeTransaction(IDataReader dr, Dictionary <Guid, Transaction> trans) { try { Guid accountId = (Guid)dr["AccountID"]; Account account = _tradingSetting.GetAccount(accountId); if (account == null) { Logger.WarnFormat("account = {0} not exist but exist transaction", accountId); return; } var orderType = (OrderType)(int)dr["OrderTypeID"]; var instrumentCategory = (InstrumentCategory)dr["InstrumentCategory"]; TransactionPhase phase = (TransactionPhase)(byte)dr["Phase"]; if (phase == TransactionPhase.Canceled) { return; } var factory = TransactionFacade.CreateAddTranCommandFactory(orderType, instrumentCategory); var command = factory.Create(account, new DBReader(dr), OperationType.None); command.Execute(); var tran = command.Result; trans.Add(tran.Id, tran); } catch (Exception ex) { Logger.Error(ex); } }
private static Transaction MultipleClose(Account account, Guid[] orderIds) { Order firstOrder = account.GetOrder(orderIds[0]); Transaction tran = TransactionFacade.CreateMultipleCloseTran(firstOrder.Owner.SettingInstrument().Category, account, firstOrder.Instrument().Id, firstOrder.Owner.ContractSize(null), account.Customer.Id); bool isOpenByBuy = false; List <OpenOrderInfo> openOrders = new List <OpenOrderInfo>(); foreach (Guid eachOrderId in orderIds) { Order order = account.GetOrder(eachOrderId); if (openOrders.Count == 0) { isOpenByBuy = order.IsBuy; openOrders.Add(new OpenOrderInfo(order.Id, order.LotBalance)); } else if (order.IsBuy == isOpenByBuy) { openOrders.Add(new OpenOrderInfo(order.Id, order.LotBalance)); } else { tran.CloseOrder(account, order, openOrders, isOpenByBuy); } } tran.ExecuteDirectly(Engine.ExecuteContext.CreateExecuteDirectly(account.Id, tran.Id, Engine.ExecuteStatus.Filled)); return(tran); }
private void RetrieveInstances(TransactionFacade facade) { if (CurrentUserContext.IsAdmin || CurrentUserContext.IsEmployee) { CurrentInstances = facade.RetrieveAllTransaction(new TransactionConverter()); } }
protected void ucIDetail_ChildListInstanceRowSaving(object sender, InstanceRowSavingEventArgs e) { using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey)) { switch ((InstanceTypes)Enum.Parse(typeof(InstanceTypes), e.InstanceType)) { case InstanceTypes.TransactionItem: TransactionFacade facade = new TransactionFacade(uow); TransactionItemDto TransactionItemDto = e.Instance as TransactionItemDto; // Save data IFacadeUpdateResult <TransactionData> result = facade.SaveTransactionItem(CurrentInstance.Id, TransactionItemDto); e.IsSuccessful = result.IsSuccessful; if (result.IsSuccessful) { // Refresh TransactionDto savedCurrentInstance = result.ToDto(new TransactionConverter()); CurrentInstance.TransactionItems = savedCurrentInstance.TransactionItems; } else { // Deal with Update result ProcUpdateResult(result.ValidationResult, result.Exception); } break; } } }
public static void CheckStaticProjectWithdrawOvertime(TimerMsg.Type timerType, bool onTime) { if (timerType != TimerMsg.Type.AutoRepayTimer) { return; } var context = new Agp2pDataContext(); // 申请时间超过 2 日 / 到达还款日,则取消债权转让申请 var withdrawOvertimeClaims = context.li_claims .Where(c => c.status == (int)Agp2pEnums.ClaimStatusEnum.NeedTransfer && c.projectId == c.profitingProjectId && !c.Children.Any()) .AsEnumerable().Where(c => { var nextRepayDate = c.li_projects.li_repayment_tasks.FirstOrDefault(ta => ta.IsUnpaid())?.should_repay_time.Date; if (nextRepayDate != null && nextRepayDate.Value <= DateTime.Today) { return(true); } return(c.createTime < DateTime.Now.AddDays(-2)); }).ToList(); if (!withdrawOvertimeClaims.Any()) { return; } withdrawOvertimeClaims.ForEach(c => TransactionFacade.StaticClaimWithdrawCancel(context, c.id, false)); context.AppendAdminLog("StaticWithdraw", "取消超时的定期债权转让申请:" + withdrawOvertimeClaims.Count); context.SubmitChanges(); }
private static void HandleProjectRepayCompletedMsg(int projectId, DateTime projectCompleteTime) { // 找出投资记录对应的活动奖励记录 var context = new Agp2pDataContext(); var invitees = context.li_invitations.Where(i => i.li_project_transactions.project == projectId).Select(i => i.dt_users1).Distinct(); var atr = invitees.Select(i => i.li_activity_transactions.Single(a => a.activity_type == (int)Agp2pEnums.ActivityTransactionActivityTypeEnum.RefereeFirstTimeProfitBonus)) .ToList(); // 查出邀请人的奖励活动交易记录 if (!atr.Any()) { return; } atr.ForEach(tr => { tr.transact_time = projectCompleteTime; tr.status = (byte)Agp2pEnums.ActivityTransactionStatusEnum.Confirm; var wallet = tr.dt_users.li_wallets; wallet.idle_money += tr.value; wallet.total_profit += tr.value; wallet.last_update_time = projectCompleteTime; var his = TransactionFacade.CloneFromWallet(wallet, Agp2pEnums.WalletHistoryTypeEnum.GainConfirm); his.li_activity_transactions = tr; context.li_wallet_histories.InsertOnSubmit(his); }); context.SubmitChanges(); }
internal static Transaction CreateTransaction(this Account account, Order originOrder, decimal lot) { var factory = TransactionFacade.CreateAddTranCommandFactory(originOrder.Owner.OrderType, originOrder.Owner.InstrumentCategory); var command = factory.CreateLmtQuantiryOnMaxLotChangeTransaction(account, originOrder, lot); command.Execute(); return(command.Result); }
internal static void InvestProjectWithTicket(string userName, string projectName, decimal amount, int ticketId) { var context = new Agp2pDataContext(); var investor = context.dt_users.Single(u => u.user_name == userName); var project = context.li_projects.Single(p => p.title == projectName); TransactionFacade.Invest(investor.id, project.id, amount, "", ticketId); }
private void RetrieveData() { using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey)) { TransactionFacade facade = new TransactionFacade(uow); RetrieveInstances(facade); } }
private Transaction CreateCloseTransaction(Order order, Price closePrice, OrderType orderType) { var factory = TransactionFacade.CreateAddTranCommandFactory(orderType, order.Owner.InstrumentCategory); var command = factory.CreateByAutoClose(order.Owner.Owner, order, closePrice, orderType); command.Execute(); return(command.Result); }
public static void InvestProject(string userName, string projectName, int amount) { var context = new Agp2pDataContext(); var investor = context.dt_users.Single(u => u.user_name == userName); var project = context.li_projects.Single(p => p.title == projectName); TransactionFacade.Invest(investor.id, project.id, amount); }
public static void StaticProjectWithdraw(string projectName, string userName, decimal amount, decimal keepInterestPercent = 1) { var context = new Agp2pDataContext(); var project = context.li_projects.Single(p => p.title == projectName); var user = context.dt_users.Single(u => u.user_name == userName); var preWithdrawClaim = project.li_claims.Where(c => c.userId == user.id && c.principal == amount).AsEnumerable().Single(c => c.IsProfiting()); TransactionFacade.StaticProjectWithdraw(context, preWithdrawClaim.id, keepInterestPercent); }
/// <summary> /// 新手标第一期逻辑(停用) /// </summary> /// <param name="projectTransactionId"></param> public static void CheckNewbieInvest(int projectTransactionId) { var context = new Agp2pDataContext(); var ptr = context.li_project_transactions.Single(tr => tr.id == projectTransactionId); var project = ptr.li_projects; if (!project.IsNewbieProject1()) { return; } if (project.repayment_type != (int)Agp2pEnums.ProjectRepaymentTypeEnum.DaoQi) { throw new InvalidOperationException("新手标只考虑了到期还款付息的情况"); } if (project.li_repayment_tasks.Any(r => r.only_repay_to == ptr.investor)) { throw new InvalidOperationException("已经创建过此投资者的回款计划"); } // 创建针对单个用户的还款计划 var finalProfitRate = 0.1m;// project.GetFinalProfitRate(ptr.create_time); // 暂时写死利率为 1/10,即投资 100 元有 10 元 var ta = new li_repayment_tasks { project = project.id, repay_interest = Math.Round(finalProfitRate * ptr.principal, 2), repay_principal = ptr.principal, status = (byte)Agp2pEnums.RepaymentStatusEnum.Unpaid, term = 1, should_repay_time = project.CalcRepayTimeByTerm(1, ptr.create_time), only_repay_to = ptr.investor }; context.li_repayment_tasks.InsertOnSubmit(ta); // 修改代收利息,添加钱包历史 var wallet = ptr.dt_users.li_wallets; wallet.profiting_money += ta.repay_interest; wallet.last_update_time = ptr.create_time; var history = TransactionFacade.CloneFromWallet(wallet, Agp2pEnums.WalletHistoryTypeEnum.InvestSuccess); history.li_project_transactions = ptr; context.li_wallet_histories.InsertOnSubmit(history); // 如果体验标完成了,则设置为完成 if (project.financing_amount == project.investment_amount) { project.status = (int)Agp2pEnums.ProjectStatusEnum.RepayCompleteIntime; project.invest_complete_time = ptr.create_time; project.complete_time = ptr.create_time; } context.SubmitChanges(); }
/// <summary> /// 查询交易明细 /// </summary> /// <param name="type"></param> /// <param name="page"></param> /// <param name="startTick"></param> /// <param name="endTick"></param> /// <returns></returns> protected static List <object> QueryTransactionHistory(int userId, Agp2pEnums.TransactionDetailsDropDownListEnum type, int pageIndex, string startTime, string endTime, short pageSize, out int count) { var context = new Agp2pDataContext(); var query = context.li_wallet_histories.Where(h => h.user_id == userId); query = query.Where(w => w.action_type != (int)Agp2pEnums.WalletHistoryTypeEnum.InvestSuccess && w.action_type != (int)Agp2pEnums.WalletHistoryTypeEnum.ClaimTransferredInSuccess && w.action_type != (int)Agp2pEnums.WalletHistoryTypeEnum.Charging && w.action_type != (int)Agp2pEnums.WalletHistoryTypeEnum.ChargeCancel); // 屏蔽项目满标的历史,没必要展示 if (MyTradeTypeMapHistoryEnum.Keys.Contains(type)) { query = query.Where(w => MyTradeTypeMapHistoryEnum[type].Cast <int>().Contains(w.action_type)); } if (!string.IsNullOrWhiteSpace(startTime)) { query = query.Where(h => Convert.ToDateTime(startTime) <= h.create_time); } if (!string.IsNullOrWhiteSpace(endTime)) { query = query.Where(h => h.create_time <= Convert.ToDateTime(endTime)); } count = query.Count(); var history = query.OrderByDescending(h => h.id).Skip(pageSize * pageIndex).Take(pageSize).AsEnumerable().Select(h => (object)new { h.id, type = Utils.GetAgp2pEnumDes((Agp2pEnums.WalletHistoryTypeEnum)h.action_type), income = QueryTransactionIncome(h), outcome = QueryTransactionOutcome(h), idleMoney = h.idle_money.ToString("n"), createTime = h.create_time.ToString("yy/MM/dd HH:mm"), remark = QueryRemark(context, h) }).ToList(); if (history.Count != 0) { count += 1; // 总计 if (count <= pageIndex * pageSize + pageSize) // 最后一页 { var allHis = query.ToList(); var income = allHis.Aggregate(0m, (sum, h) => sum + TransactionFacade.QueryTransactionIncome(h, (a, b) => a.GetValueOrDefault() + b.GetValueOrDefault())); var outcome = allHis.Aggregate(0m, (sum, h) => sum + h.QueryTransactionOutcome().GetValueOrDefault()); history.Add(new { id = 0, type = "总计", income = (0 <= income - outcome) ? (income - outcome).ToString("f2") : "", outcome = (0 < outcome - income) ? (outcome - income).ToString("f2") : "", }); } } return(history); }
private void RetrieveData() { using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey)) { TransactionFacade facade = new TransactionFacade(uow); TransactionDto instance = facade.RetrieveOrNewTransaction(InstanceId, new TransactionConverter()); CurrentInstance = instance; ucIEdit.CurrentInstance = instance; } }
protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { var wh = (li_wallet_histories)e.Item.DataItem; decimal Tin = TransactionFacade.QueryTransactionIncome(wh, (receivedPrincipal, profited) => receivedPrincipal.GetValueOrDefault(0) + profited.GetValueOrDefault(0)); decimal Tout = TransactionFacade.QueryTransactionOutcome(wh).GetValueOrDefault(0); TransactionIncome += Tin; TransactionOutcome += Tout; } }
public static void HandleTimerMsg(TimerMsg.Type timerName, bool startUp) { if (timerName != TimerMsg.Type.AutoRepayTimer) { return; } var repayTime = DateTime.Now; var context = new Agp2pDataContext(); // 找出过期的券并标记为过期 context.li_activity_transactions.Where(a => a.activity_type == (int)Agp2pEnums.ActivityTransactionActivityTypeEnum.TrialTicket && a.status == (int)Agp2pEnums.ActivityTransactionStatusEnum.Acting) .AsEnumerable() .ForEach(atr => new TrialTicket(atr).SetCancelIfExpired()); // 找出使用了但是未放款的券 var todayInDetails = repayTime.ToString("yyyy-MM-dd"); var unpaidTickets = context.li_activity_transactions.Where( a => a.activity_type == (int)Agp2pEnums.ActivityTransactionActivityTypeEnum.TrialTicket && a.status == (int)Agp2pEnums.ActivityTransactionStatusEnum.Confirm && a.details.Contains(todayInDetails)) // 查找放款日是今日 .Where(a => a.transact_time == null) .ToList(); // 添加活动备注,减去钱包待收利息,创建钱包历史 unpaidTickets.ForEach(atr => { atr.remarks = "体验标收益"; atr.transact_time = repayTime; var wallet = atr.dt_users.li_wallets; wallet.idle_money += atr.value; wallet.profiting_money -= atr.value; wallet.total_profit += atr.value; wallet.last_update_time = repayTime; var his = TransactionFacade.CloneFromWallet(wallet, Agp2pEnums.WalletHistoryTypeEnum.GainConfirm); his.li_activity_transactions = atr; context.li_wallet_histories.InsertOnSubmit(his); }); if (unpaidTickets.Any()) { context.AppendAdminLog(DTEnums.ActionEnum.Edit.ToString(), "体验券自动放款:" + unpaidTickets.Count); } context.SubmitChanges(); }
protected void btnExportExcel_Click(object sender, EventArgs e) { ChkAdminLevel("statistics_wallets_histories", DTEnums.ActionEnum.DownLoad.ToString()); //检查权限 var query = QueryWalletHistories(); var userName = getUserName(); if (rblType.SelectedValue == "0") { var data = query.OrderByDescending(h => h.id) .Skip(pageSize * (page - 1)) .Take(pageSize).AsEnumerable().Select(h => new { user = h.dt_users == null ? "" : h.dt_users.user_name, name = h.dt_users == null ? "" : h.dt_users.real_name, actionType = Utils.GetAgp2pEnumDes((Agp2pEnums.WalletHistoryTypeEnum)h.action_type), income = TransactionFacade.QueryTransactionIncome <decimal?>(h), outcome = TransactionFacade.QueryTransactionOutcome(h), h.idle_money, h.investing_money, h.total_investment, h.profiting_money, h.total_profit, h.create_time, remark = QueryTransactionRemark(h, his => his.li_project_transactions.li_projects.title) }); var titles = new[] { "用户", "姓名", "操作类型", "收入金额", "支出金额", "可用余额", "在投金额", "累计投资", "待收利润", "已收利润", "交易时间", "备注" }; if (!string.IsNullOrWhiteSpace(userName)) { Utils.ExportXls(userName + "的资金明细", titles, data, Response); } else { Utils.ExportXls("会员资金明细", titles, data, Response); } } else { var data = QueryGroupData(query).Select(h => new { h.GroupName, h.ReCharge, h.WithDraw, h.Invest, h.Principal, h.Interest }); var titles = new[] { "会员组", "充值金额", "提现金额", "投资金额", "返还本金", "返还利息" }; Utils.ExportXls("会员资金明细汇总", titles, data, Response); } }
private static void DoPayBonusInterest(int projectId, DateTime projectCompleteTime) { var context = new Agp2pDataContext(); // 找出未支付的奖励 var projectAtrs = context.li_activity_transactions.Where(atr => atr.activity_type == (byte)Agp2pEnums.ActivityTransactionActivityTypeEnum.InterestRateTicket && atr.status == (byte)Agp2pEnums.ActivityTransactionStatusEnum.Confirm && atr.type == (byte)Agp2pEnums.ActivityTransactionTypeEnum.Gain && atr.transact_time == null && (atr.details.Contains("\"ProjectId\":" + projectId + ",") || atr.details.Contains("\"ProjectId\":" + projectId + "}"))) .ToLookup(atr => atr.dt_users); // 支付奖励并减去代收金额 projectAtrs.ForEach(userTickets => { var wallet = userTickets.Key.li_wallets; userTickets.ForEach(atr => { //丰付获取收益 var msg = new HongbaoPayReqMsg(atr.user_id, atr.value); MessageBus.Main.Publish(msg); var msgResp = BaseRespMsg.NewInstance <HongbaoPayRespMsg>(msg.SynResult); MessageBus.Main.Publish(msgResp); if (msgResp.HasHandle) { atr.remarks = "加息券收益"; atr.transact_time = projectCompleteTime; wallet.profiting_money -= atr.value; wallet.idle_money += atr.value; wallet.total_profit += atr.value; wallet.last_update_time = projectCompleteTime; var his = TransactionFacade.CloneFromWallet(wallet, Agp2pEnums.WalletHistoryTypeEnum.GainConfirm); his.li_activity_transactions = atr; context.li_wallet_histories.InsertOnSubmit(his); } }); }); if (projectAtrs.Any()) { context.AppendAdminLog(DTEnums.ActionEnum.Edit.ToString(), "加息券自动放款用户数:" + projectAtrs.Count); } context.SubmitChanges(); }
protected void btnBecomeTransferable_OnClick(object sender, EventArgs e) { var transferAmount = Request["__EVENTARGUMENT"]; int claimId = Convert.ToInt32(((LinkButton)sender).CommandArgument); var claim = LqContext.li_claims.Single(c => c.id == claimId); var remark = string.Format("将项目【{0}】的债权 {1} 设置为可转让", claim.li_projects.title, claimId); LqContext.AppendAdminLog(DTEnums.ActionEnum.Edit.ToString(), remark, false); TransactionFacade.StaticProjectWithdraw(LqContext, claimId, 1 - Convert.ToDecimal(transferAmount) / 100); ShowClaimsInfo(claim.li_projects); JscriptMsg(remark, ""); }
public static void BuyClaim(string projectName, string userName, decimal amount) { var context = new Agp2pDataContext(); var project = context.li_projects.Single(p => p.title == projectName); var user = context.dt_users.Single(u => u.user_name == userName); var preBuyClaim = project.li_claims.Where( c => c.status == (int)Agp2pEnums.ClaimStatusEnum.NeedTransfer && c.IsLeafClaim()).OrderBy(c => Math.Abs(c.principal - amount)).First(); TransactionFacade.BuyClaim(context, preBuyClaim.id, user.id, amount); context.SubmitChanges(); }
/// <summary> /// 项目放款 /// </summary> /// <param name="msg"></param> private static void MakeLoan(MakeLoanRespMsg msg) { try { //检查请求处理结果 if (msg.CheckResult()) { //检查签名 if (msg.CheckSignature()) { Agp2pDataContext context = new Agp2pDataContext(); //查找对应的项目 var pro = context.li_projects.SingleOrDefault(p => p.id == msg.ProjectCode); if (pro != null) { //异步返回才放款,内网测试使用同步 #if DEBUG if (msg.Sync) { #endif #if !DEBUG if (!msg.Sync) { #endif //定期项目进入开始还款,活期项目直接向借款人放款 if (pro.IsHuoqiProject()) { TransactionFacade.MakeLoan(context, DateTime.Now, pro, pro.li_risks.li_loaners.user_id); } else { context.StartRepayment(pro.id); } } msg.HasHandle = true; } else { msg.Remarks = "没有找到平台项目,项目编号为:" + msg.ProjectCode; } } } } catch (Exception ex) { msg.Remarks = "内部错误:" + ex.Message; } }
internal Dictionary <Guid, Transaction> Parse(DataSet ds, out Dictionary <Guid, Order> orderDict) { var trans = new Dictionary <Guid, Transaction>(CAPACITY); SettingInitializer.InitializeWithException(ds, "Transaction", dr => { Guid accountId = (Guid)dr["AccountID"]; Account account = _tradingSetting.GetAccount(accountId); if (account == null) { Logger.WarnFormat("account = {0} not exist but exist transaction", accountId); return; } var orderType = (OrderType)(int)dr["OrderTypeID"]; var instrumentCategory = (InstrumentCategory)dr["InstrumentCategory"]; TransactionPhase phase = (TransactionPhase)(byte)dr["Phase"]; if (phase == TransactionPhase.Canceled) { return; } var factory = TransactionFacade.CreateAddTranCommandFactory(orderType, instrumentCategory); var command = factory.Create(account, new DBRow(dr), OperationType.AsNewRecord); command.Execute(); var tran = command.Result; trans.Add(tran.Id, tran); }); var orders = this.ParseOrders(ds, trans); orderDict = orders; SettingInitializer.InitializeWithException(ds, "OrderRelation", dr => { var closeOrderId = (Guid)dr["CloseOrderID"]; if (!orders.ContainsKey(closeOrderId)) { return; } Order closeOrder = orders[closeOrderId]; if (closeOrder != null) { var factory = OrderRelationFacade.Default.GetAddOrderRelationFactory(closeOrder); var command = factory.Create(closeOrder, new DBRow(dr)); command.Execute(); } }); return(trans); }
private Transaction CutCommon(Dictionary <Guid, decimal> closedLotPerOpenOrderDict, Instrument instrument, bool cutAsBuy, decimal lotBalanceSum, Price setPrice) { DateTime baseTime = Market.MarketManager.Now; var account = instrument.Owner; var factory = TransactionFacade.CreateAddTranCommandFactory(OrderType.Risk, instrument.Setting.Category); var command = factory.CreateCutTransaction(account, instrument, lotBalanceSum, setPrice, cutAsBuy); command.Execute(); Transaction tran = command.Result; if (tran.InstrumentCategory == InstrumentCategory.Physical || _account.Setting().RiskLevelAction == RiskLevelAction.CloseNetPosition || _account.Setting().RiskLevelAction == RiskLevelAction.CloseAll) { tran.FirstOrder.SplitOrder(closedLotPerOpenOrderDict, true); } return(tran); }
private static Transaction CreateOpenTranAndOrder(this Account account, Order openOrder, DeliveryRequestOrderRelation relation, DeliveryRequest deliveryRequest) { Transaction transaction = TransactionFacade.CreateCancelDeliveryWithShortSellTran(account, deliveryRequest.InstrumentId, openOrder.Owner.ContractSize(null)); CancelDeliveryWithShortSellOrderParam param = new CancelDeliveryWithShortSellOrderParam { IsBuy = true, IsOpen = true, SetPrice = openOrder.SetPrice, ExecutePrice = openOrder.ExecutePrice, Lot = relation.DeliveryLot, LotBalance = relation.DeliveryLot, PhysicalRequestId = deliveryRequest.Id, TradeOption = openOrder.TradeOption }; Order order = OrderFacade.Default.CreateCancelDeliveryWithShortSellOrder(transaction, param); return(transaction); }
private List <li_project_transactions> getRepayTransactions(li_repayment_tasks repayment) { var pro = repayment.li_projects; List <li_project_transactions> profiting; if (repayment.status >= (int)Agp2pEnums.RepaymentStatusEnum.ManualPaid) { // 查询所有收益记录 profiting = pro.li_project_transactions.Where( t => t.create_time == repayment.repay_at && t.type != (int)Agp2pEnums.ProjectTransactionTypeEnum.Invest && t.status == (int)Agp2pEnums.ProjectTransactionStatusEnum.Success).ToList(); } else { profiting = TransactionFacade.GenerateRepayTransactions(repayment, repayment.should_repay_time); // 临时预计收益 } return(profiting); }
private static void HandleDelayInvest(int projectTransactionId, DateTime investTime) { var context = new Agp2pDataContext(); var agent = context.dt_users.FirstOrDefault(u => u.dt_user_groups.title == AutoRepay.AgentGroup); try { if (agent == null) { throw new InvalidOperationException("没有找到中间人组,不能发送提醒短信"); } if (string.IsNullOrWhiteSpace(agent.mobile)) { throw new InvalidOperationException("中间人没有设置手机,不能发送提醒短信"); } var ptr = context.li_project_transactions.Single(ptr0 => ptr0.id == projectTransactionId); var huoqiBuyableClaimsAmount = TransactionFacade.QueryHuoqiBuyableClaimsAmount(context, ptr.li_projects, agent.id); var delayInvested = ptr.li_projects.li_project_transactions.Where( tr => tr.type == (int)Agp2pEnums.ProjectTransactionTypeEnum.Invest && tr.status == (int)Agp2pEnums.ProjectTransactionStatusEnum.Pending) .Aggregate(0m, (sum, tr) => sum + tr.principal); var msgContent = $"用户总共投资了活期项目 {ptr.li_projects.title} {delayInvested.ToString("c")},但活期债权本金总额({huoqiBuyableClaimsAmount.ToString("c")})不足,请尽快处理"; var errorMsg = string.Empty; if (!SMSHelper.SendTemplateSms(agent.mobile, msgContent, out errorMsg)) { context.AppendAdminLogAndSave("Agent", "发送提醒中间人买入债权短信失败:" + errorMsg); } else { context.AppendAdminLogAndSave("Agent", "发送提醒中间人买入债权短信成功:" + msgContent); } } catch (Exception ex) { context.AppendAdminLogAndSave("Agent", "发送提醒中间人买入债权短信失败:" + ex.GetSimpleCrashInfo()); } }
protected void btnBuy_OnClick(object sender, EventArgs e) { var buyAmount = Request["__EVENTARGUMENT"]; int claimId = Convert.ToInt32(((LinkButton)sender).CommandArgument); selectedAgent = Convert.ToInt32(ddlAgent.SelectedValue); try { TransactionFacade.BuyClaim(context, claimId, selectedAgent, Convert.ToDecimal(buyAmount)); context = new Agp2pDataContext(); RptBind(); JscriptMsg("买入债权成功", "", "Success"); } catch (Exception ex) { JscriptMsg("买入债权失败:" + ex.Message, "", "Success"); } }