/// <summary> /// Initialize security factory, used for creating new securities /// </summary> /// <param name="brokermodel"></param> /// <param name="conversion"></param> /// <param name="exchangeModels"></param> /// <param name="accountcurrency"></param> public SecurityFactory(BrokerModel brokermodel, Currency conversion, CurrencyType accountcurrency, params ExchangeModel[] exchangeModels) { _brokerModel = brokermodel; _currency = conversion; _exchangeModels = exchangeModels; _accountcurrency = accountcurrency; }
/// <summary> /// Initializes a new instance of the <see cref="Portfolio"/> class. /// </summary> /// <param name="clock">The clock.</param> /// <param name="actionscheduler">The actionscheduler.</param> /// <param name="brokerconnection">The brokerconnection.</param> /// <param name="brokermodel">The brokermodel.</param> /// <param name="currency">The currency.</param> /// <param name="eventrunner">The eventrunner.</param> /// <param name="exceptionhandler">The exceptionhandler.</param> /// <param name="orderTicketHandler">The order ticket handler.</param> /// <param name="brokeraccount">The brokeraccount.</param> /// <param name="cashmanager">The cashmanager.</param> /// <param name="runmode">The runmode.</param> /// <param name="datafeed">The datafeed.</param> /// <param name="benchmark">The benchmark.</param> /// <param name="id">The identifier.</param> public Portfolio(WorldClock clock, ActionsScheduler actionscheduler, BrokerConnection brokerconnection, BrokerModel brokermodel, Currency currency, EventRunner eventrunner, ExceptionHandler exceptionhandler, OrderTicketHandler orderTicketHandler, BrokerAccount brokeraccount, CashManager cashmanager, RunMode runmode, DataFeed datafeed, Benchmark benchmark, string id = "") { //Set references ActionsScheduler = actionscheduler; BrokerAccount = brokeraccount; BrokerConnection = brokerconnection; BrokerModel = brokermodel; Clock = clock; Currency = currency; EventRunner = eventrunner; ExceptionHandler = exceptionhandler; CashManager = cashmanager; OrderTicketHandler = orderTicketHandler; _porfolioBenchmark = benchmark; //Set initial items Id = id; IsBacktesting = runmode == RunMode.Backtester; OrderFactory = new OrderFactory(this, BrokerModel); OrderTracker = new OrderTracker(this); Subscription = new DataSubscriptionManager(datafeed, CashManager); Results = new Result(0, _porfolioBenchmark); //Portfolio benchmark is not used benchmark.OnCalc(x => 0); }
public HttpResponseMessage GetBrokerByAgent(string id) { if (string.IsNullOrEmpty(id) || !PageHelper.ValidateNumber(id)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据验证错误!"))); } var brokerlist = _brokerService.GetBrokerById(Convert.ToInt32(id)); var model = new BrokerModel { Headphoto = brokerlist.Headphoto, Nickname = brokerlist.Nickname, Brokername = brokerlist.Brokername, Realname = brokerlist.Realname, Sexy = brokerlist.Sexy, Totalpoints = brokerlist.Totalpoints, Amount = brokerlist.Amount, Phone = brokerlist.Phone, Qq = brokerlist.Qq, Email = brokerlist.Email, Sfz = brokerlist.Sfz, Regtime1 = brokerlist.Regtime.ToShortDateString(), Usertype1 = brokerlist.Usertype.ToString(), State = brokerlist.State, PartnersName = brokerlist.WeiXinNumber, Address = brokerlist.Address }; return(PageHelper.toJson(new { List = model })); }
/// <summary> /// fill assuming high liquidity - fill stops and limits at their stop price rather than at /// bid, ask, or trade. primarily for use when only daily data is available. /// </summary> /// <param name="k"></param> /// <param name="c"></param> /// <param name="bidask"></param> /// <param name="fillOpg"></param> /// <param name="fillHighLiquidityEod"></param> /// <returns></returns> public StatusType Fill(Tick k, BrokerModel c, bool bidask, bool fillOpg, bool fillHighLiquidityEod) { if (!fillHighLiquidityEod || (Type != OrderType.Stop && Type != OrderType.Limit)) { return(Fill(k, c, bidask, fillOpg)); } if (k.Symbol != Symbol) { return(StatusType.UNKNOWN_SYMBOL); } if (!fillOpg && (ValidInstruct == OrderInstructionType.OPG)) { return(StatusType.INVALID_TRADE_PARAMETERS); } // determine size and activation price using bid-ask or trade method int s; decimal p; if (bidask) { bool ok = Direction == Direction.Long ? k.HasAsk : k.HasBid; if (!ok) { return(StatusType.OFF_QUOTES); } s = Direction == Direction.Long ? k.AskSize : k.BidSize; p = Direction == Direction.Long ? k.Ask : k.Bid; } else { if (!k.IsTrade) { return(StatusType.INVALID_TRADE_PARAMETERS); } s = k.Size; p = k.Trade; } // record the fill Xsize = (s >= UnsignedSize ? UnsignedSize : s) * (Direction == Direction.Long ? 1 : -1); Xtime = k.Time; Xdate = k.Date; if ((Type == OrderType.Limit && Direction == Direction.Long && (p <= LimitPrice)) || // buy limit (Type == OrderType.Limit && Direction == Direction.Short && (p >= LimitPrice))) // sell limit { Xprice = LimitPrice; return(StatusType.ORDER_FILLED); } if ((Type == OrderType.Stop && Direction == Direction.Long && (p >= StopPrice)) || // buy stop (Type == OrderType.Stop && Direction == Direction.Short && (p <= StopPrice))) // sell stop { Xprice = StopPrice; return(StatusType.ORDER_FILLED); } return(StatusType.OK); }
/// <summary> /// fill against bid and ask rather than trade /// </summary> /// <param name="k"></param> /// <param name="c"></param> /// <param name="bidask"></param> /// <param name="fillOpg"></param> /// <returns></returns> public StatusType Fill(Tick k, BrokerModel c, bool bidask, bool fillOpg) { if (!bidask) { return(Fill(k, c, fillOpg)); } // buyer has to match with seller and vice verca bool ok = Direction == Direction.Long ? k.HasAsk : k.HasBid; if (!ok) { return(StatusType.OFF_QUOTES); } //Get price and spread from tick and transaction costs decimal p = Direction == Direction.Long ? k.Ask : k.Bid; p = ImpactPriceSpread(p, c.GetSpread(this)); int s = Direction == Direction.Long ? k.AskSize : k.BidSize; if (k.Symbol != Symbol) { return(StatusType.OK); } if (!fillOpg && (ValidInstruct == OrderInstructionType.OPG)) { return(StatusType.INVALID_TRADE_PARAMETERS); } if (Created.AddMilliseconds(c.GetLatencyInMilliseconds(this)) > k.TickDateTime) { return(StatusType.OK); } if ((Type == OrderType.Limit && Direction == Direction.Long && (p <= LimitPrice)) || // buy limit (Type == OrderType.Limit && Direction == Direction.Short && (p >= LimitPrice)) || // sell limit (Type == OrderType.Stop && Direction == Direction.Long && (p >= StopPrice)) || // buy stop (Type == OrderType.Stop && Direction == Direction.Short && (p <= StopPrice)) || // sell stop (Type == OrderType.StopLimit && Direction == Direction.Long && (p >= StopPrice) && (p <= LimitPrice)) || // buy stop limit (Type == OrderType.StopLimit && Direction == Direction.Short && (p <= StopPrice) && (p >= LimitPrice)) || // sell stop limit Type == OrderType.Market) { //Get trade price (factoring in slippage) Xprice = ImpactPriceSlippage(p, c.GetSlippage(this)); //Set commissions Commission = c.GetCommission(this); Xsize = Math.Abs(Xsize); Xsize = (s >= UnsignedSize ? UnsignedSize : s) * (Direction == Direction.Long ? 1 : -1); Xtime = k.Time; Xdate = k.Date; return(StatusType.ORDER_FILLED); } return(StatusType.OK); }
// POST: api/Broker public IHttpActionResult Post([FromBody] BrokerModel broker) { try { _service.Add(broker); return(Ok(broker)); } catch (Exception e) { return(Content(HttpStatusCode.InternalServerError, "Error Adding Entry. Try again later" + e.Message)); } }
public HttpResponseMessage GetBrokerByUserId(string userId) { int IsInvite = 1; //是否使用邀请码(0使用 1未使用) if (string.IsNullOrEmpty(userId) || !PageHelper.ValidateNumber(userId)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据验证错误!"))); } var model = _brokerService.GetBrokerByUserId(Convert.ToInt32(userId)); if (model == null) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "该用户不存在!"))); } #region 判断经纪人是否使用过邀请码 或者参与过活动 InviteCodeSearchCondition icodeseCon = new InviteCodeSearchCondition { NumUser = model.Id }; var a = _inviteCodeService.GetInviteCodeByCount(icodeseCon); EventOrderSearchCondition eveCon = new EventOrderSearchCondition { Brokers = model }; var b = _eventOrderService.GetEventOrderCount(eveCon); if (a > 0 || b > 0) { IsInvite = 0; //判断有无使用过邀请码 或者参与过活动 或该活动下架 } #endregion var brokerInfo = new BrokerModel { Id = model.Id, Brokername = model.Brokername, Realname = model.Realname, Nickname = model.Nickname, Sexy = model.Sexy, Sfz = model.Sfz, Email = model.Email, Phone = model.Phone, Headphoto = model.Headphoto, WeiXinNumber = model.WeiXinNumber, IsInvite = IsInvite }; return(PageHelper.toJson(brokerInfo)); }
/// <summary> /// Perform any cost calculations /// </summary> /// <param name="t"></param> private void BrokerCostCalculation(Tick t) { //Check for timing if (t.TickDateTime < _nextcostcalc) { return; } //Check swap pricing foreach (var trade in Default.Positions.SelectMany(x => x.Trades)) { ((TradeImpl)trade).Swap += BrokerModel.CalculateMarginInterest(trade); } //Set next calculation date and time _nextcostcalc = t.TickDateTime.Date.AddDays(1); }
public StatusType Fill(Tick t, BrokerModel c, bool fillOpg) { if (!t.IsTrade) { return(StatusType.OK); } if (t.Symbol != Symbol) { return(StatusType.OK); } if (!fillOpg && (ValidInstruct == OrderInstructionType.OPG)) { return(StatusType.INVALID_TRADE_PARAMETERS); } //Set price P and add negatively impacting spread decimal p = ImpactPriceSpread(t.Trade, c.GetSpread(this)); if ((Type == OrderType.Limit && Direction == Direction.Long && (p <= LimitPrice)) || // buy limit (Type == OrderType.Limit && Direction == Direction.Short && (p >= LimitPrice)) || // sell limit (Type == OrderType.Stop && Direction == Direction.Long && (p >= StopPrice)) || // buy stop (Type == OrderType.Stop && Direction == Direction.Short && (p <= StopPrice)) || // sell stop (Type == OrderType.StopLimit && Direction == Direction.Long && (p >= StopPrice) && (p <= LimitPrice)) || // buy stop limit (Type == OrderType.StopLimit && Direction == Direction.Short && (p <= StopPrice) && (p >= LimitPrice)) || // sell stop limit Type == OrderType.Market) { //Get trade price (factoring in slippage) Xprice = ImpactPriceSlippage(p, c.GetSlippage(this)); //Set commissions Commission = c.GetCommission(this); //Add execution details Xsize = t.Size >= UnsignedSize ? UnsignedSize : t.Size; Xsize = Math.Abs(Xsize); Xsize *= Direction == Direction.Long ? 1 : -1; Xtime = t.Time; Xdate = t.Date; return(StatusType.ORDER_FILLED); } return(StatusType.OK); }
static void Main(string[] args) { //Intailize the Broker Settings BrokerModel _Broker = new BrokerModel(); _Broker.Url = "tailor.cloudmqtt.com"; _Broker.Username = "******"; _Broker.Password = "******"; _Broker.Port = 11300; _Broker.SSLPort = 21300; _Broker.WebSocketPort = 31300; //Connect to Server MQTT mQTT = new MQTT(); mQTT.Initailize(_Broker); mQTT.Connect(); while (true) { if (mQTT.Connected) { //publish string mQTT.Publish("StringValue", "5"); //publish json Object Sensor Sensor = new Sensor(); var result = Sensor.CreateSensor(); string Jsonresult = JsonConvert.SerializeObject(result); mQTT.Publish("SensorObject", Jsonresult); //publish json List of Objectss var resultList = Sensor.CreateSensorList(); string JsonresultList = JsonConvert.SerializeObject(resultList); mQTT.Publish("SensorList", JsonresultList); } Thread.Sleep(10000); } }
static void Main(string[] args) { //Intailize the Broker Settings BrokerModel _Broker = new BrokerModel(); _Broker.Url = "tailor.cloudmqtt.com"; _Broker.Username = "******"; _Broker.Password = "******"; _Broker.Port = 11300; _Broker.SSLPort = 21300; _Broker.WebSocketPort = 31300; //Connect to Server MQTT mQTT = new MQTT(); mQTT.Initailize(_Broker); mQTT.Connect(); mQTT.SubscribeEventHandler(client_MqttMsgPublishReceived); mQTT.Subscribe("StringValue"); mQTT.Subscribe("SensorObject"); mQTT.Subscribe("SensorList"); }
public HttpResponseMessage AddAdmin([FromBody] BrokerModel brokerModel) { var model = new BrokerEntity { Id = brokerModel.Id, }; if (brokerModel.Type == "add") { try { if (_brokerService.Create(model) != null) { return(PageHelper.toJson(PageHelper.ReturnValue(true, "添加成功"))); } } catch (Exception) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "添加失败"))); } } if (brokerModel.Type == "edit") { try { if (_brokerService.Update(_brokerService.GetBrokerById(model.Id)) != null) { return(PageHelper.toJson(PageHelper.ReturnValue(true, "修改成功"))); } } catch (Exception) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "修改失败"))); } } return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据验证失败"))); }
public HttpResponseMessage GetBroker(string id) { if (string.IsNullOrEmpty(id) || !PageHelper.ValidateNumber(id)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据验证错误!"))); } var brokerlist = _brokerService.GetBrokerById(Convert.ToInt32(id)); var dd = new BrokerModel { Address = brokerlist.Address, Adduser = brokerlist.Adduser, Brokername = brokerlist.Brokername, Phone = brokerlist.Phone, Realname = brokerlist.Realname, Nickname = brokerlist.Nickname, Sexy = brokerlist.Sexy, Sfz = brokerlist.Sfz, Email = brokerlist.Email, Headphoto = brokerlist.Headphoto, rgtime = brokerlist.Regtime.ToShortDateString() }; return(PageHelper.toJson(new { List = dd })); }
public HttpResponseMessage AddBroker([FromBody] BrokerModel brokerModel) { if (string.IsNullOrEmpty(brokerModel.UserName)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "用户名不能为空"))); } if (string.IsNullOrEmpty(brokerModel.Password)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "密码不能为空"))); } if (string.IsNullOrEmpty(brokerModel.Phone)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "手机号不能为空"))); } // 创建推荐用户 var condition = new BrokerSearchCondition { OrderBy = EnumBrokerSearchOrderBy.OrderById, Phone = brokerModel.Phone }; //判断user表和Broker表中是否存在用户名 int user2 = _brokerService.GetBrokerCount(condition); if (user2 != 0) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "用户名已经存在"))); } //检测规则表中是否存在权限,不存在则添加 var role = "broker"; switch (brokerModel.UserType) { case EnumUserType.经纪人: role = "broker"; break; case EnumUserType.商家: role = "merchant"; break; case EnumUserType.场秘: role = "secretary"; break; case EnumUserType.带客人员: role = "waiter"; break; case EnumUserType.普通用户: role = "user"; break; case EnumUserType.管理员: role = "admin"; break; case EnumUserType.财务: role = "accountant"; break; } var brokerRole = _roleService.GetRoleByName(role); //User权限缺少时自动添加 if (brokerRole == null) { brokerRole = new Role { RoleName = role, RolePermissions = null, Status = RoleStatus.Normal, Description = "后台添加新权限类别:" + role }; } var newUser = new UserBase { UserName = brokerModel.UserName, Password = brokerModel.Password, RegTime = DateTime.Now, NormalizedName = brokerModel.UserName.ToLower(), //注册用户添加权限 UserRoles = new List <UserRole>() { new UserRole() { Role = brokerRole } }, Status = 0 }; PasswordHelper.SetPasswordHashed(newUser, brokerModel.Password); var model = new BrokerEntity(); model.UserId = _userService.InsertUser(newUser).Id; model.Brokername = brokerModel.UserName; model.Phone = brokerModel.Phone; model.Totalpoints = 0; model.Amount = 0; model.Usertype = brokerModel.UserType; model.Regtime = DateTime.Now; model.State = 1; model.Adduser = 0; model.Addtime = DateTime.Now; model.Upuser = 0; model.Uptime = DateTime.Now; //判断初始等级是否存在,否则创建 var level = _levelService.GetLevelsByCondition(new LevelSearchCondition { Name = "默认等级" }).FirstOrDefault(); if (level == null) { var levelModel = new LevelEntity { Name = "默认等级", Describe = "系统默认初始创建", Url = "", Uptime = DateTime.Now, Addtime = DateTime.Now, }; _levelService.Create(levelModel); } model.Level = level; _brokerService.Create(model); return(PageHelper.toJson(PageHelper.ReturnValue(true, "注册成功"))); }
public HttpResponseMessage GetAdmin([FromBody] BrokerModel brokerModel) { return(PageHelper.toJson(_brokerService.GetBrokerById(brokerModel.Id))); }
/// <summary> /// fill against bid and ask rather than trade /// </summary> /// <param name="k"></param> /// <param name="c"></param> /// <param name="opg"></param> /// <returns></returns> public StatusType FillBidAsk(Tick k, BrokerModel c, bool opg) { return(Fill(k, c, true, opg)); }
/// <summary> /// fill against bid and ask rather than trade /// </summary> /// <param name="k"></param> /// <param name="c"></param> /// <returns></returns> public StatusType FillBidAsk(Tick k, BrokerModel c) { return(Fill(k, c, true, false)); }
/// <summary> /// Immediate fill logic, fill the order /// can be reused on other fill models for filling and checking /// </summary> /// <param name="broker"></param> /// <param name="datapoint"></param> /// <param name="pendingorder"></param> /// <param name="highliquidfill"></param> /// <returns></returns> protected Fill ImmediateFill(BrokerModel broker, DataPoint datapoint, PendingOrder pendingorder, bool highliquidfill) { //Get order Order order = pendingorder.Order; Security security = pendingorder.Security; //Check market conditions if (order.State == OrderState.Cancelled || order.State == OrderState.Error) { return(Fill.Cancelled(order.InternalId)); //Order has already been cancelled or has an error } else if (order.State == OrderState.Invalid) { return(Fill.Invalid(order.InternalId, "Invalid Order received")); //Order has already been made invalid } else if (order.State != OrderState.Submitted) { return(Fill.Error(order.InternalId, $"Unexpected order state {order.State}")); //Something else has gone wrong } else if (!IsExchangeOpen(pendingorder.Security, datapoint)) { return(Fill.NoFill()); //Exchange is not opened for trading } else if (IsOrderExpired(order, datapoint)) { return(Fill.Cancelled(order.InternalId, "Order expired")); //Check if order has been expired } //Check latency for processing this order try { if (pendingorder.CreatedUtc.Add(broker.GetLatencyModel(security).GetLatency(order)) > datapoint.Occured) { return(Fill.NoFill()); //We are not suppose to see this order yet, due to added latency } } catch (Exception exc) { _log.Error(exc, $"Could not execute broker latency model function for get latency."); throw; } //Check possible fill price var prices = datapoint.OrderPrice(order.Security, order.Direction); decimal fillprice = prices.Current; //Check order type and logic if (order is LimitOrder limitorder) { //Check if limit order price is triggered if (!limitorder.IsTriggered(prices, out fillprice)) { return(Fill.NoFill()); } } else if (order is StopLimitOrder stoplimitorder) { //Check if stop limit order price is triggered if (!stoplimitorder.IsTriggered(prices, out fillprice)) { return(Fill.NoFill()); } } else if (order is StopMarketOrder stopmarketorder) { //Check if stop order price is triggered if (!stopmarketorder.IsTriggered(prices, out fillprice)) { return(Fill.NoFill()); } } else if (order is MarketOnCloseOrder marketoncloseorder) { //Check if market on close order is triggered if (!marketoncloseorder.IsTriggered()) { return(Fill.NoFill()); } } else if (order is MarketOnOpenOrder marketonopenorder) { //Check if market on open order is triggered if (!marketonopenorder.IsTriggered()) { return(Fill.NoFill()); } } //Check slippage model try { fillprice += broker.GetSlippageModel(security).GetSlippage(order); } catch (Exception exc) { _log.Error(exc, $"Could not execute broker slippage model function for get slippage."); throw; } //Check additional spread try { fillprice += broker.GetSpreadModel(security).GetAdditionalSpread(order); } catch (Exception exc) { _log.Error(exc, $"Could not execute broker spread model function for get additional spread."); throw; } //Check fill amount (based on liquidity) if (!highliquidfill) { //Check fill size possible, according to tick var filled = datapoint.OrderSize(order.Direction); //Needed to fill (in case we partially already filled some of the order) decimal neededfill = order.UnsignedQuantity - pendingorder.OrderFilledQuantity; //Check for partial fills (will not include fees) if (filled < neededfill) { return(Fill.PartialFill(order, pendingorder.Security.Exchange.Name, fillprice, 0m, filled)); } else { //Process needed fill (will include fees) try { return(Fill.FullFill(order, pendingorder.Security.Exchange.Name, fillprice, Math.Abs(broker.GetFeeModel(pendingorder.Security).GetCommissionAndFees(pendingorder)), neededfill)); } catch (Exception exc) { _log.Error(exc, $"Could not process full fill, due to broker feemodel implementation."); throw; } } } else { //Process full fill (will include fees) try { return(Fill.FullFill(order, pendingorder.Security.Exchange.Name, fillprice, Math.Abs(broker.GetFeeModel(pendingorder.Security).GetCommissionAndFees(pendingorder)), order.UnsignedQuantity)); } catch (Exception exc) { _log.Error(exc, $"Could not process full fill, due to broker feemodel implementation."); throw; } } }
/// <summary> /// Fill order, if possible /// </summary> /// <param name="broker">Associated broker model</param> /// <param name="datapoint">Currently received data point</param> /// <param name="pendingorder">Pending order to check for filling</param> /// <param name="highliquidfill">If true, size of ticks are not taken in to account</param> /// <returns></returns> public virtual Fill FillOrder(BrokerModel broker, DataPoint datapoint, PendingOrder pendingorder, bool highliquidfill) => ImmediateFill(broker, datapoint, pendingorder, highliquidfill);
public HttpResponseMessage AddBroker([FromBody] BrokerModel brokerModel) { var validMsg = ""; if (!brokerModel.ValidateModel(out validMsg)) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据验证错误,请重新输入"))); } #region 验证码判断 解密 var strDes = EncrypHelper.Decrypt(brokerModel.Hidm, "Hos2xNLrgfaYFY2MKuFf3g==");//解密 string[] str = strDes.Split('$'); if (str.Count() < 2) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "验证码错误,请重新发送!"))); } string source = str[0]; //获取验证码和手机号 DateTime date = Convert.ToDateTime(str[1]); //获取发送验证码的时间 DateTime dateNow = Convert.ToDateTime(DateTime.Now.ToLongTimeString()); //获取当前时间 TimeSpan ts = dateNow.Subtract(date); double secMinu = ts.TotalMinutes; //得到发送时间与现在时间的时间间隔分钟数 if (secMinu > 3) //发送时间与接受时间是否大于3分钟 { return(PageHelper.toJson(PageHelper.ReturnValue(false, "你已超过时间验证,请重新发送验证码!"))); } else { // source.Split('#')[0] 验证码 // source.Split('#')[1] 手机号 if (brokerModel.Phone != source.Split('#')[1])//判断手机号是否一致 { return(PageHelper.toJson(PageHelper.ReturnValue(false, "验证码错误,请重新发送!"))); } if (brokerModel.MobileYzm != source.Split('#')[0])//判断验证码是否一致 { return(PageHelper.toJson(PageHelper.ReturnValue(false, "验证码错误,请重新发送!"))); } } #endregion #region 判断两次密码是否一致 if (brokerModel.Password != brokerModel.SecondPassword) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "手机号不能为空"))); } #endregion #region 判断邀请码是否存在真实 (brokerInfoController 中GetBrokerByInvitationCode方法也同一判断) MessageDetailEntity messageDetail = null; if (!string.IsNullOrEmpty(brokerModel.inviteCode)) { MessageDetailSearchCondition messageSearchcondition = new MessageDetailSearchCondition { InvitationCode = brokerModel.inviteCode, Title = "推荐经纪人" }; messageDetail = _MessageService.GetMessageDetailsByCondition(messageSearchcondition).FirstOrDefault();//判断邀请码是否存在 if (messageDetail == null) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "邀请码错误!"))); } } #endregion #region UC用户创建 杨定鹏 2015年5月28日14:52:48 var user = _userService.GetUserByName(brokerModel.UserName); if (user != null) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "用户名已经存在"))); } var condition = new BrokerSearchCondition { OrderBy = EnumBrokerSearchOrderBy.OrderById, State = 1, Phone = brokerModel.Phone }; //判断user表和Broker表中是否存在用户名 int user2 = _brokerService.GetBrokerCount(condition); if (user2 != 0) { return(PageHelper.toJson(PageHelper.ReturnValue(false, "手机号已经存在"))); } var brokerRole = _roleService.GetRoleByName("user"); //User权限缺少时自动添加 if (brokerRole == null) { brokerRole = new Role { RoleName = "user", RolePermissions = null, Status = RoleStatus.Normal, Description = "刚注册的用户默认归为普通用户user" }; } var newUser = new UserBase { UserName = brokerModel.UserName, Password = brokerModel.Password, RegTime = DateTime.Now, NormalizedName = brokerModel.UserName.ToLower(), //注册用户添加权限 UserRoles = new List <UserRole>() { new UserRole() { Role = brokerRole } }, Status = 0 }; PasswordHelper.SetPasswordHashed(newUser, brokerModel.Password); #endregion #region Broker用户创建 杨定鹏 2015年5月28日14:53:32 var model = new BrokerEntity(); model.UserId = _userService.InsertUser(newUser).Id; model.Brokername = brokerModel.Phone; model.Nickname = brokerModel.Nickname; model.Phone = brokerModel.Phone; model.Totalpoints = 0; model.Amount = 0; model.Usertype = EnumUserType.普通用户; model.Regtime = DateTime.Now; model.State = 1; model.Adduser = 0; model.Addtime = DateTime.Now; model.Upuser = 0; model.Uptime = DateTime.Now; //判断初始等级是否存在,否则创建 var level = _levelService.GetLevelsByCondition(new LevelSearchCondition { Name = "默认等级" }).FirstOrDefault(); if (level == null) { var levelModel = new LevelEntity { Name = "默认等级", Describe = "系统默认初始创建", Url = "", Uptime = DateTime.Now, Addtime = DateTime.Now, }; _levelService.Create(levelModel); } model.Level = level; var newBroker = _brokerService.Create(model); #endregion #region 推荐经纪人 if (!string.IsNullOrEmpty(brokerModel.inviteCode)) { //添加经纪人 var entity = new RecommendAgentEntity { PresenteebId = newBroker.Id, Qq = newBroker.Qq.ToString(), Agentlevel = newBroker.Agentlevel, Brokername = newBroker.Brokername, Phone = newBroker.Phone, Regtime = DateTime.Now, Broker = _brokerService.GetBrokerById(Convert.ToInt32(messageDetail.InvitationId)), Uptime = DateTime.Now, Addtime = DateTime.Now, }; _recommendagentService.Create(entity); } #endregion return(PageHelper.toJson(PageHelper.ReturnValue(true, "注册成功"))); }
public SimBroker(SimAccount account, BrokerModel tcmodel) { Default = account; BrokerModel = tcmodel; Reset(); }
/// <summary> /// Initializes a new instance of the <see cref="OrderFactory"/> class. /// </summary> /// <param name="portfolio">The handler.</param> /// <param name="brokermodel">The brokermodel.</param> public OrderFactory(IPortfolio portfolio, BrokerModel brokermodel) { _portfolio = portfolio; _brokerModel = brokermodel; }
public void Add(BrokerModel entity) { _repository.Add(entity); }
public HttpResponseMessage UpdateBroker([FromBody] BrokerModel broker) { if (broker != null && !string.IsNullOrEmpty(broker.Id.ToString()) && PageHelper.ValidateNumber(broker.Id.ToString())) { var brokerModel = _brokerService.GetBrokerById(broker.Id); brokerModel.Headphoto = broker.Headphoto; brokerModel.Nickname = broker.Nickname; brokerModel.Phone = broker.Phone; brokerModel.Sfz = broker.Sfz; brokerModel.Email = broker.Email; brokerModel.Realname = broker.Realname; brokerModel.Sexy = broker.Sexy; brokerModel.WeiXinNumber = broker.WeiXinNumber;//by yangyue 2015/7/16 #region 转职经纪人 杨定鹏 2015年6月11日17:29:58 //填写身份证,邮箱,和真实姓名后就能转职经纪人 if (!string.IsNullOrEmpty(broker.Email) && !string.IsNullOrEmpty(broker.Sfz) && !string.IsNullOrEmpty(broker.Realname)) { //权限变更 var brokerRole = _roleService.GetRoleByName("broker"); //User权限缺少时自动添加 if (brokerRole == null) { brokerRole = new Role { RoleName = "broker", RolePermissions = null, Status = RoleStatus.Normal, Description = "user用户转职为broker" }; } var user = _userService.FindUser(brokerModel.UserId); user.UserRoles.First().Role = brokerRole; //更新用户权限 if (_userService.ModifyUser(user)) { //更新broker表记录 brokerModel.Usertype = EnumUserType.经纪人; _brokerService.Update(brokerModel); //return PageHelper.toJson(PageHelper.ReturnValue(true, "数据更新成功!")); } } #endregion #region 邀请码逻辑 by yangyue 2015/7/16 var even = new EventSearchCondition //判断该活动是否开启 { EventContent = "完善经纪人资料活动", State = true }; if (_eventService.GetEventCount(even) > 0) { #region 邀请码活动 by yangyue 2015/7/16 InviteCodeSearchCondition icodeseCon = new InviteCodeSearchCondition { NumUser = brokerModel.Id, State = 1 }; //判断有无使用过邀请码 if (_inviteCodeService.GetInviteCodeByCount(icodeseCon) <= 0)//没使用过邀请码 { //邀请码不为空 if (!string.IsNullOrEmpty(broker.code)) { var levelCon = new LevelSearchCondition { Name = "白银" }; var level = _levelService.GetLevelsByCondition(levelCon).FirstOrDefault(); #region 白银逻辑 BrokerSearchCondition bsearchModel = new BrokerSearchCondition { Levels = level }; //1判断白银等级人数是否《=3000 if (_brokerService.GetBrokerCount(bsearchModel) <= 3000) { var invite = new InviteCodeSearchCondition { Number = broker.code, State = 0 }; var con = _inviteCodeService.GetInviteCodeByCondition(invite).FirstOrDefault(); //查询邀请码是否存在并且未使用 var eventcon = new EventOrderSearchCondition //判断该经济人有无参与活动 等于0是没参与 等于1是参与过 { Brokers = _brokerService.GetBrokerById(brokerModel.Id) }; var num = _eventOrderService.GetEventOrderCount(eventcon); //查询活动订单表有无该经纪人 if (con != null && num == 0) //存在 未使用 并且该经纪人未参与过活动 { //using (TransactionScope tsCope = new TransactionScope(TransactionScopeOption.RequiresNew)) //{ #region 添加到活动订单 经纪人账户表 AgentBill表 修改经纪人等级 生成3个邀请码 并发送到手机 var eve = new EventSearchCondition { EventContent = "完善经纪人资料活动" }; var coneve = _eventService.GetEventByCondition(eve).FirstOrDefault(); //添加活动订单信息 EventOrderEntity emodel = new EventOrderEntity(); emodel.AcDetail = "完整经济人资料奖励30元"; emodel.Addtime = DateTime.Now; emodel.MoneyCount = 30; emodel.Broker = brokerModel; emodel.Event = coneve; _eventOrderService.Create(emodel); //添加到经纪人账户表brokeraccount BrokeAccountEntity brokeraccountmodel = new BrokeAccountEntity(); brokeraccountmodel.MoneyDesc = "完整经济人资料奖励30元"; brokeraccountmodel.Balancenum = 30; brokeraccountmodel.Adduser = brokerModel.Id; brokeraccountmodel.Addtime = DateTime.Now; brokeraccountmodel.Upuser = brokerModel.Id; brokeraccountmodel.Uptime = DateTime.Now; brokeraccountmodel.Broker = brokerModel; brokeraccountmodel.Type = 2; brokeraccountmodel.State = 0; _brokerAccountService.Create(brokeraccountmodel); //添加记录到AgentBill表 AgentBillEntity abmmodel = new AgentBillEntity(); abmmodel.AgentId = brokerModel.Id; abmmodel.Agentname = brokerModel.Brokername; abmmodel.LandagentId = 1; abmmodel.Amount = 30; abmmodel.Isinvoice = false; abmmodel.Checkoutdate = DateTime.Now; abmmodel.Addtime = DateTime.Now; abmmodel.Updtime = DateTime.Now; abmmodel.EventOrderId = emodel.Id; _agentBillService.Create(abmmodel); // tsCope.Complete(); //} // using (TransactionScope tsCope = new TransactionScope(TransactionScopeOption.RequiresNew)) //{ //修改邀请码表信息 con.NumUser = brokerModel.Id; con.UseTime = DateTime.Now; con.State = 1; _inviteCodeService.Update(con); //更新等级 brokerModel.Level = level; brokerModel.Amount += 30; _brokerService.Update(brokerModel); // tsCope.Complete(); //} //并且生成3个邀请码发送到手机端口 并插入库中 string randmNums = string.Empty; for (int i = 0; i < 3; i++) { string rans = GenerateRandomNumber(6); randmNums += rans + ","; InviteCodeEntity inviteCode = new InviteCodeEntity(); inviteCode.CreatTime = DateTime.Now; inviteCode.Number = rans; inviteCode.UseTime = DateTime.Now; inviteCode.State = 0; inviteCode.Broker = brokerModel; _inviteCodeService.Create(inviteCode); } SMSHelper.Sending(brokerModel.Phone, "恭喜您完善个人信息,奖励您三个邀请码:" + randmNums + "赶快邀请小伙伴们,惊喜等你哟!" + "【优客惠】"); #endregion } else //不存在 或已被使用 { #region 邀请码不存在 或已被使用 就转为青铜逻辑 #region 青铜逻辑 var levelConn = new LevelSearchCondition { Name = "青铜" }; var qlevel = _levelService.GetLevelsByCondition(levelConn).FirstOrDefault(); BrokerSearchCondition qbsearchModel = new BrokerSearchCondition { Levels = qlevel }; // 1判断青铜是否《=1000 if (_brokerService.GetBrokerCount(qbsearchModel) <= 1000) { var qinvite = new InviteCodeSearchCondition { Number = broker.code, State = 0 }; var qcon = _inviteCodeService.GetInviteCodeByCondition(qinvite).FirstOrDefault(); //查询邀请码是否存在并且未使用 var eventcon1 = new EventOrderSearchCondition //判断该经济人有无参与活动 等于0是没参与 等于1是参与过 { Brokers = _brokerService.GetBrokerById(brokerModel.Id) }; var num1 = _eventOrderService.GetEventOrderCount(eventcon1); //查询活动订单表有无该经纪人 if (qcon != null && num1 == 0) { var eve = new EventSearchCondition { EventContent = "完善经纪人资料活动" }; var coneve = _eventService.GetEventByCondition(eve).FirstOrDefault(); //using (TransactionScope tsCope = new TransactionScope(TransactionScopeOption.RequiresNew)) //{ EventOrderEntity emodel = new EventOrderEntity(); emodel.AcDetail = "完整经济人资料无邀请码奖励20元"; emodel.Addtime = DateTime.Now; emodel.MoneyCount = 20; emodel.Broker = brokerModel; emodel.Event = coneve; _eventOrderService.Create(emodel); //添加到经纪人账户表 BrokeAccountEntity brokeraccountmodel = new BrokeAccountEntity(); brokeraccountmodel.MoneyDesc = "完整经济人资料奖励20元"; brokeraccountmodel.Balancenum = 20; brokeraccountmodel.Adduser = brokerModel.Id; brokeraccountmodel.Addtime = DateTime.Now; brokeraccountmodel.Upuser = brokerModel.Id; brokeraccountmodel.Uptime = DateTime.Now; brokeraccountmodel.Broker = brokerModel; brokeraccountmodel.Type = 2; brokeraccountmodel.State = 0; _brokerAccountService.Create(brokeraccountmodel); //添加记录到AgentBill表 AgentBillEntity abmmodel = new AgentBillEntity(); abmmodel.AgentId = brokerModel.Id; abmmodel.Agentname = brokerModel.Brokername; abmmodel.LandagentId = 1; abmmodel.Amount = 20; abmmodel.Isinvoice = false; abmmodel.Checkoutdate = DateTime.Now; abmmodel.Addtime = DateTime.Now; abmmodel.Updtime = DateTime.Now; abmmodel.EventOrderId = emodel.Id; _agentBillService.Create(abmmodel); brokerModel.Level = qlevel; brokerModel.Amount += 20; _brokerService.Update(brokerModel); //给20元钱 等级设为青铜 // tsCope.Complete(); //} } else { if (_brokerService.Update(brokerModel) != null) { //等级设为青铜 brokerModel.Level = qlevel; _brokerService.Update(brokerModel); return(PageHelper.toJson(PageHelper.ReturnValue(true, "邀请码输入错误!"))); } } #endregion } #endregion } } else { if (_brokerService.Update(brokerModel) != null) { //白银人数超过3000 等级设为白银 brokerModel.Level = level; _brokerService.Update(brokerModel); } } #endregion } else//邀请码没有填写 没有参与过活动 给20元钱 等级设为青铜 { #region 没有填写邀请码 给20元钱 等级设为青铜 var levelConn = new LevelSearchCondition { Name = "青铜" }; var qlevel = _levelService.GetLevelsByCondition(levelConn).FirstOrDefault(); //等级为青铜 //判断青铜是否《=1000 BrokerSearchCondition qbsearchModel = new BrokerSearchCondition { Levels = qlevel }; var eventcon = new EventOrderSearchCondition //判断该经济人有无参与活动 等于0是没参与 等于1是参与过 { Brokers = _brokerService.GetBrokerById(brokerModel.Id) }; var num = _eventOrderService.GetEventOrderCount(eventcon); //Brokers if (_brokerService.GetBrokerCount(qbsearchModel) <= 1000 && num == 0) //判断青铜是否《=1000 { //青铜等级人数《=1000 给20元钱 等级设为青铜 //using (TransactionScope tsCope = new TransactionScope(TransactionScopeOption.RequiresNew)) //{ //添加到活动订单表 var eve = new EventSearchCondition { EventContent = "完善经纪人资料活动" }; var coneve = _eventService.GetEventByCondition(eve).FirstOrDefault(); EventOrderEntity emodel = new EventOrderEntity(); emodel.AcDetail = "完整经济人资料无邀请码奖励20元"; emodel.Addtime = DateTime.Now; emodel.MoneyCount = 20; emodel.Event = coneve; emodel.Broker = brokerModel; _eventOrderService.Create(emodel); //添加到经纪人账户表 BrokeAccountEntity brokeraccountmodel = new BrokeAccountEntity(); brokeraccountmodel.MoneyDesc = "完整经济人资料奖励20元"; brokeraccountmodel.Balancenum = 20; brokeraccountmodel.Adduser = brokerModel.Id; brokeraccountmodel.Addtime = DateTime.Now; brokeraccountmodel.Upuser = brokerModel.Id; brokeraccountmodel.Uptime = DateTime.Now; brokeraccountmodel.Broker = brokerModel; brokeraccountmodel.Type = 2; brokeraccountmodel.State = 0; _brokerAccountService.Create(brokeraccountmodel); //添加记录到AgentBill表 AgentBillEntity abmmodel = new AgentBillEntity(); abmmodel.AgentId = brokerModel.Id; abmmodel.Agentname = brokerModel.Brokername; abmmodel.LandagentId = 1; abmmodel.Amount = 20; abmmodel.Isinvoice = false; abmmodel.Checkoutdate = DateTime.Now; abmmodel.Addtime = DateTime.Now; abmmodel.Updtime = DateTime.Now; abmmodel.EventOrderId = emodel.Id; _agentBillService.Create(abmmodel); brokerModel.Level = qlevel; brokerModel.Amount += 20; _brokerService.Update(brokerModel); // tsCope.Complete(); //} } else { if (_brokerService.Update(brokerModel) != null) { //青铜人数已经超过1000人 则等级直接设为青铜 brokerModel.Level = qlevel; _brokerService.Update(brokerModel); } } #endregion } } #endregion } else { return(PageHelper.toJson(PageHelper.ReturnValue(true, "该活动已经下架!"))); } #endregion try { if (_brokerService.Update(brokerModel) != null) { return(PageHelper.toJson(PageHelper.ReturnValue(true, "数据更新成功!"))); } } catch { return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据更新失败!"))); } } return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据验证错误!"))); }
public void PostBrokerNotification([FromBody] BrokerModel brokerModified) { _service.UpdateBrokers(brokerModified); }
//functions to update single entity on client side public void UpdateBrokers(BrokerModel broker) { BrokerOutViewModel outViewBroker = new BrokerOutViewModel(broker); Clients.All.updateBrokers(outViewBroker); }
public void Update(BrokerModel entity) { _repository.Update(entity); }
/// <summary> /// Executes any open orders allowed by the specified tick. /// </summary> /// <param name="tick">The tick.</param> /// <returns>the number of orders executed using the tick.</returns> public int Execute(TickImpl tick) { //TODO: in order to calculate the floating PnL ticks are send to the account for calculations. //Also this location is incorrect! Default.OnTick(tick); BrokerCostCalculation(tick); if (_pendorders == 0) { return(0); } //Check if we need to process the order as a trade or use the bid ask fills UseBidAskFills = tick.HasAsk && tick.HasBid; int filledorders = 0; SimAccount[] accts = new SimAccount[MasterOrders.Count]; MasterOrders.Keys.CopyTo(accts, 0); for (int idx = 0; idx < accts.Length; idx++) { // go through each account SimAccount a = accts[idx]; // if account has requested no executions, skip it if (!a.Execute) { continue; } //Check for a margin call by the broker if (a.MarginLevel <= BrokerModel.StopOutLevel()) { //cancel this order MasterOrders[a].ForEach(x => { ((PendingOrderImpl)x).OrderStatus = StatusType.INSUFFICIENT_CAPITAL; x.Cancel(); }); } // make sure we have a record for this account if (!MasterTrades.ContainsKey(a.Id)) { MasterTrades.Add(a.Id, new List <Trade>()); } // track orders being removed and trades that need notification List <int> notifytrade = new List <int>(); List <int> remove = new List <int>(); // go through each order in the account for (int i = 0; i < MasterOrders[a].Count; i++) { //Get the order object PendingOrderImpl po = (PendingOrderImpl)MasterOrders[a][i]; OrderImpl o = (OrderImpl)po.Order; //make sure tick is for the right stock, and right exchange if (tick.Symbol != o.Symbol) { continue; } //Check if order is in a correct state if (po.OrderStatus != StatusType.OK) { remove.Add(i); // count the trade filledorders++; continue; } if (UseHighLiquidityFillsEod) { po.OrderStatus = o.Fill(tick, BrokerModel, UseBidAskFills, false, true); } else if (o.ValidInstruct <= OrderInstructionType.GTC) { po.OrderStatus = o.Fill(tick, BrokerModel, UseBidAskFills, false); // fill our trade } else if (o.ValidInstruct == OrderInstructionType.OPG) { // if it's already opened, we missed our shot if (_hasopened.Contains(o.Symbol)) { continue; } // otherwise make sure it's really the opening if (tick.Source == Opgex) { // it's the opening tick, so fill it as an opg po.OrderStatus = o.Fill(tick, BrokerModel, UseBidAskFills, true); // mark this symbol as already being open _hasopened.Add(tick.Symbol); } } // other orders fill normally, except MOC orders which are at 4:00PM else if (o.ValidInstruct == OrderInstructionType.MOC) { if (tick.Time >= 160000000) { po.OrderStatus = o.Fill(tick, BrokerModel, UseBidAskFills, false); // fill our trade } } else { po.OrderStatus = o.Fill(tick, BrokerModel, UseBidAskFills, false); // fill our trade } if (po.OrderStatus == StatusType.ORDER_FILLED) { // remove filled size from size available in trade tick.Size -= o.UnsignedSize; // get copy of trade for recording TradeImpl trade = new TradeImpl(o); // if trade represents entire requested order, mark order for removal if (trade.UnsignedSize == o.UnsignedSize) { remove.Add(i); } else // otherwise reflect order's remaining size { o.Size = (o.UnsignedSize - trade.UnsignedSize) * (o.Direction == Direction.Long ? 1 : -1); } // record trade MasterTrades[a.Id].Add(trade); // mark it for notification notifytrade.Add(MasterTrades[a.Id].Count - 1); // count the trade filledorders++; } } // notify subscribers of trade if ((GotFill != null) && a.Notify) { for (int tradeidx = 0; tradeidx < notifytrade.Count; tradeidx++) { TradeImpl t = (TradeImpl)MasterTrades[a.Id][notifytrade[tradeidx]]; var account = Acctlist[Accounts[0]]; t.Account = account; t.AccountName = t.Account.Id; account.OnFill(t); GotFill(t, MasterOrders[a][remove[tradeidx]]); } } int rmcount = remove.Count; // remove the filled orders for (int i = remove.Count - 1; i >= 0; i--) { MasterOrders[a].RemoveAt(remove[i]); } // unmark filled orders as pending _pendorders -= rmcount; if (_pendorders < 0) { _pendorders = 0; } } return(filledorders); }
/// <summary> /// Fill order, if possible /// </summary> /// <param name="broker">Associated broker model</param> /// <param name="datapoint">Currently received data point</param> /// <param name="pendingorder">Pending order to check for filling</param> /// <param name="highliquidfill">If true, size of ticks are not taken in to account</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public override Fill FillOrder(BrokerModel broker, DataPoint datapoint, PendingOrder pendingorder, bool highliquidfill) { throw new NotImplementedException(); }
/// <summary> /// Fills this order with a tick /// </summary> /// <param name="t"></param> /// <param name="c"></param> /// <returns></returns> public StatusType Fill(Tick t, BrokerModel c) { return(Fill(t, c, false)); }