private ScrapListenner() : base(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP) { logger = LoggerBuilder.Init().Set(GetType()).Info("Listen Start!"); Bind(new IPEndPoint(IPAddress.Any, BrokerInfo.GetPort())); Listen(20); ThreadPool.QueueUserWorkItem((c) => { while (true) { Socket client = Accept(); ThreadPool.QueueUserWorkItem((b) => { Socket a = (Socket)b; byte[] buffer = new byte[4]; a.Receive(buffer, 4, SocketFlags.None); int size = BitConverter.ToInt32(buffer, 0); buffer = new byte[size]; a.Receive(buffer, size, SocketFlags.None); a.Send(new byte[] { 9 }); a.Close(); String msg = Encoding.UTF8.GetString(buffer); logger.Info(" [WEB LOG] Send messate - " + msg); Result result = Result.Build(msg); //TODO: this function is that send just to get the message from the scraper to the server. //the structure is key, ResultType, ScrapType, Index, Separation, Data. ServerConnector.Instance().Send(buffer); }, client); } }); }
/// <summary> /// Handle incoming commands /// </summary> /// <param name="commandTransport">An ITransport</param> /// <param name="command">A Command</param> protected void OnCommand(ITransport commandTransport, Command command) { if (command is MessageDispatch) { DispatchMessage((MessageDispatch)command); } else if (command is WireFormatInfo) { this.brokerWireFormatInfo = (WireFormatInfo)command; } else if (command is BrokerInfo) { this.brokerInfo = (BrokerInfo)command; } else if (command is ShutdownInfo) { //ShutdownInfo info = (ShutdownInfo)command; if (!closing && !closed) { OnException(commandTransport, new NMSException("Broker closed this connection.")); } } else { Tracer.Error("Unknown command: " + command); } }
/// <summary> /// Update BrokerInfo in the DB /// </summary> /// <param name="brokerI">BrokerInfo objecto to update</param> public void UpdateBrokerInfo(BrokerInfo brokerI) { BrokerInfo bi = _context.BrokerInfo.FirstOrDefault(x => x.Id == brokerI.Id); bi.Name = brokerI.Name; bi.MiddleName = brokerI.MiddleName; bi.LastName = brokerI.LastName; bi.NickName = brokerI.NickName; bi.DOB = brokerI.DOB; bi.Nationality = brokerI.Nationality; bi.Relationship = brokerI.Relationship; bi.AdressType = brokerI.AdressType; bi.Adress = brokerI.Adress; bi.City = brokerI.City; bi.State = brokerI.State; bi.County = brokerI.County; bi.ZipCode = brokerI.ZipCode; bi.Population = brokerI.Population; bi.Country = brokerI.Country; bi.PhoneType = brokerI.PhoneType; bi.PhonePriority = brokerI.PhonePriority; bi.PhoneCountry = brokerI.PhoneCountry; bi.PhoneNumber = brokerI.PhoneNumber; bi.EmailType = brokerI.EmailType; bi.EmailPriority = brokerI.EmailType; bi.Emailadress = brokerI.Emailadress; _context.SaveChanges(); }
public override void OnStrategyStart() { base.OnStrategyStart(); // 测试用,自定义交易时间,仿真或实盘时可删除 base.TimeHelper = new TimeHelper(new int[] { 0, 2400 }, 2100, 1458); base.TargetPosition = 0; //base.DualPosition.Long.Qty = 0; //base.DualPosition.Long.QtyToday = 0; //base.DualPosition.Short.Qty = 0; //base.DualPosition.Short.QtyToday = 0; if (BrokerInfo == null) { // 使用静态的主要原因是每个实例都来取一次没有必要 BrokerInfo = DataManager.GetBrokerInfo(); } if (BrokerInfo.Accounts.Count > 0) { BrokerAccount brokerAccount = BrokerInfo.Accounts[0]; GetBrokerInfoHelper.Transform(brokerAccount, base.DualPosition); } LoadHistoricalBars(Clock.Now); BarSeries bars1min = GetBars(BarType.Time, BarSize); fastSMA = new SMA(bars1min, fastLength, Color.Red); slowSMA = new SMA(bars1min, slowLength, Color.Green); Draw(fastSMA, 0); Draw(slowSMA, 0); }
// // Un-marshal an object instance from the data input stream // public override void LooseUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn) { base.LooseUnmarshal(wireFormat, o, dataIn); BrokerInfo info = (BrokerInfo)o; info.BrokerId = (BrokerId)LooseUnmarshalCachedObject(wireFormat, dataIn); info.BrokerURL = LooseUnmarshalString(dataIn); if (dataIn.ReadBoolean()) { short size = dataIn.ReadInt16(); BrokerInfo[] value = new BrokerInfo[size]; for (int i = 0; i < size; i++) { value[i] = (BrokerInfo)LooseUnmarshalNestedObject(wireFormat, dataIn); } info.PeerBrokerInfos = value; } else { info.PeerBrokerInfos = null; } info.BrokerName = LooseUnmarshalString(dataIn); info.SlaveBroker = dataIn.ReadBoolean(); info.MasterBroker = dataIn.ReadBoolean(); info.FaultTolerantConfiguration = dataIn.ReadBoolean(); }
public async Task <AllBrokerData> SellStock(BrokerInfo brokerInfo) { var playerBrokerAccount = cache.Get <AllBrokerData>(brokerInfo.PlayerName + "_Broker"); if (playerBrokerAccount == null) { throw new Exception("No broker account exists for provided player"); } var playerBankAccount = cache.Get <AllBankRecords>(brokerInfo.PlayerName + "_Bank"); var turn = cache.Get <Clock>(brokerInfo.PlayerName + "_Clock"); var totalPrice = brokerInfo.StockPrice * brokerInfo.Quantity; var bankTransaction = new BankTransaction(); bankTransaction.PlayerName = playerBankAccount.Accounts.PlayerName; bankTransaction.Price = totalPrice; bankTransaction.Transceiver = brokerInfo.Sector; bankTransaction.Turn = turn.PlayerTurn + 1; await bankService.Deposit(bankTransaction); var brokerRecords = new AllBrokerData() { }; brokerRecords = playerBrokerAccount; brokerInfo.Status = Constants.sellStock; brokerRecords.BrokerInfos.Add(brokerInfo); cache.Set(brokerInfo.PlayerName + "_Broker", brokerRecords, Constants.cacheTime); return(brokerRecords); }
private BrokerConnection BuildAndStartBrokerConnection(BrokerInfo brokerInfo) { IPEndPoint brokerEndpoint; if (_producer != null) { brokerEndpoint = brokerInfo.ProducerAddress.ToEndPoint(); } else if (_consumer != null) { brokerEndpoint = brokerInfo.ConsumerAddress.ToEndPoint(); } else { throw new Exception("ClientService must set producer or consumer."); } var brokerAdminEndpoint = brokerInfo.AdminAddress.ToEndPoint(); var remotingClient = new SocketRemotingClient(_setting.ClientName, brokerEndpoint, _setting.SocketSetting); var adminRemotingClient = new SocketRemotingClient(_setting.ClientName, brokerAdminEndpoint, _setting.SocketSetting); var brokerConnection = new BrokerConnection(brokerInfo, remotingClient, adminRemotingClient); if (_producer != null && _producer.ResponseHandler != null) { remotingClient.RegisterResponseHandler((int)BrokerRequestCode.SendMessage, _producer.ResponseHandler); remotingClient.RegisterResponseHandler((int)BrokerRequestCode.BatchSendMessage, _producer.ResponseHandler); } brokerConnection.Start(); return(brokerConnection); }
/// <summary> /// Sends news object to data layer to update in the DB /// </summary> /// <param name="brokerI">news object to update in the DB</param> public void EditBroker(BrokerInfo brokerI) { if (BrokerExistsById(brokerI)) { _brokerRepo.UpdateBrokerInfo(brokerI); } }
// // Un-marshal an object instance from the data input stream // public override void TightUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn, BooleanStream bs) { base.TightUnmarshal(wireFormat, o, dataIn, bs); BrokerInfo info = (BrokerInfo)o; info.BrokerId = (BrokerId)TightUnmarshalCachedObject(wireFormat, dataIn, bs); info.BrokerURL = TightUnmarshalString(dataIn, bs); if (bs.ReadBoolean()) { short size = dataIn.ReadInt16(); BrokerInfo[] value = new BrokerInfo[size]; for (int i = 0; i < size; i++) { value[i] = (BrokerInfo)TightUnmarshalNestedObject(wireFormat, dataIn, bs); } info.PeerBrokerInfos = value; } else { info.PeerBrokerInfos = null; } info.BrokerName = TightUnmarshalString(dataIn, bs); info.SlaveBroker = bs.ReadBoolean(); info.MasterBroker = bs.ReadBoolean(); info.FaultTolerantConfiguration = bs.ReadBoolean(); info.DuplexConnection = bs.ReadBoolean(); info.NetworkConnection = bs.ReadBoolean(); info.ConnectionId = TightUnmarshalLong(wireFormat, dataIn, bs); }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { tdlog.Info("GetBrokerInfo"); //TraderApi.TD_ReqQryTradingAccount(m_pTdApi); //TraderApi.TD_ReqQryInvestorPosition(m_pTdApi, null); //timerAccount.Enabled = false; //timerAccount.Enabled = true; //timerPonstion.Enabled = false; //timerPonstion.Enabled = true; BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID) { BuyingPower = m_TradingAccount.Available }; Type t = typeof(CThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TThostFtdcPosiDirectionType PosiDirection = (TThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? brokerPosition.LongQty = pos; else brokerPosition.ShortQty = -pos; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
/// <summary> /// Sends news object to data layer to delete from DB /// </summary> /// <param name="id">Id of news to delete from the DB</param> public void RemoveBroker(int id) { BrokerInfo broker = _brokerRepo.GetById(id); if (BrokerExistsById(broker)) { _brokerRepo.DeleteBrokerInfo(broker); } }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { } else { return(brokerInfo); } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID) { BuyingPower = m_TradingAccount.Available }; Type t = typeof(CThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } foreach (CThostFtdcInvestorPositionField pos in _dictPositions.Values) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = pos.InstrumentID }; if (TThostFtdcPosiDirectionType.Long == pos.PosiDirection) { brokerPosition.LongQty = pos.Position; } else if (TThostFtdcPosiDirectionType.Short == pos.PosiDirection) { brokerPosition.ShortQty = pos.Position; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; Type t2 = typeof(CThostFtdcInvestorPositionField); FieldInfo[] fields2 = t2.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields2) { brokerPosition.AddCustomField(field.Name, field.GetValue(pos).ToString()); } brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return(brokerInfo); }
/// <summary> /// Sends a brokerI object to data layer to insert into the DB /// </summary> /// <param name="brokerI">brokerI object to insert in the DB</param> public void AddBroker(BrokerInfo brokerI) { //if (NewsExists(brokerI)) //{ // throw new NewsAlreadyExistException(); //} _brokerRepo.InsertBrokerInfo(brokerI); }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { } else { return brokerInfo; } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID) { BuyingPower = m_TradingAccount.Available }; Type t = typeof(CThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } foreach (CThostFtdcInvestorPositionField pos in _dictPositions.Values) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = pos.InstrumentID }; if (TThostFtdcPosiDirectionType.Long == pos.PosiDirection) { brokerPosition.LongQty = pos.Position; } else if (TThostFtdcPosiDirectionType.Short == pos.PosiDirection) { brokerPosition.ShortQty = pos.Position; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; Type t2 = typeof(CThostFtdcInvestorPositionField); FieldInfo[] fields2 = t2.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields2) { brokerPosition.AddCustomField(field.Name, field.GetValue(pos).ToString()); } brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
public async Task <IActionResult> GetBrokerInfo([FromBody] BrokerInfo brokerInfo) { try { var result = await BrokerController.GetBrokerInfoFromNext(brokerInfo); var response = Ok(new { result }); return(response); } catch (Exception err) { Console.WriteLine(err); return(null); } }
public ActionResult CreateBroker(BrokerViewModels model) { if (model.BrokerInfo.Name != null) { BrokerInfo broker = new BrokerInfo(); broker = model.BrokerInfo; _brokerBLL.AddBroker(broker); } return(RedirectToAction("List")); }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (!this.isConnected) { this.EmitError(this.Id, -1, "The TDXTradeProvider is not connected."); return(brokerInfo); } ReportArgs rargs = this.trader.QueryFund(); if (rargs.Succeeded && rargs.Result != null) { FundRecord fundRecord = (FundRecord)rargs.Result; BrokerAccount brokerAccount = new BrokerAccount("通达信-" + this.fundID); brokerAccount.AddField("Balance", fundRecord.Balance.ToString()); brokerAccount.AddField("Available", fundRecord.Available.ToString()); brokerAccount.AddField("TotalAssets", fundRecord.TotalAsserts.ToString()); brokerAccount.AddField("Desirable", fundRecord.Desirable.ToString()); brokerAccount.AddField("MarketValue", fundRecord.MarketValue.ToString()); brokerAccount.AddField("Frozen", fundRecord.Frozen.ToString()); brokerAccount.BuyingPower = fundRecord.Available; brokerInfo.Accounts.Add(brokerAccount); rargs = this.trader.QueryPositions(); if (rargs.Succeeded && rargs.Result != null) { List <PositionRecord> positions = (List <PositionRecord>)rargs.Result; foreach (PositionRecord position in positions) { BrokerPosition brokerPosition = new BrokerPosition(); brokerPosition.SecurityExchange = position.SecurityExchange; brokerPosition.Symbol = position.SecurityExchange + "." + position.SecurityID; brokerPosition.AddCustomField("Available", position.Available.ToString()); brokerPosition.Qty = position.Quantity; brokerPosition.AddCustomField("CostPrice", position.CostPrice.ToString()); brokerPosition.LongQty = position.Quantity; brokerAccount.AddPosition(brokerPosition); } } else { this.EmitError(this.Id, -1, rargs.ErrorInfo); } } else { this.EmitError(this.Id, -1, rargs.ErrorInfo); } return(brokerInfo); }
public void OnCommand(ITransport sender, Command command) { if (command != null) { if (command.IsResponse) { Object oo = null; lock (((ICollection)requestMap).SyncRoot) { int v = ((Response)command).CorrelationId; try { if (requestMap.ContainsKey(v)) { oo = requestMap[v]; requestMap.Remove(v); } } catch { } } Tracked t = oo as Tracked; if (t != null) { t.onResponses(); } } if (!initialized) { if (command.IsBrokerInfo) { BrokerInfo info = (BrokerInfo)command; BrokerInfo[] peers = info.PeerBrokerInfos; if (peers != null) { for (int i = 0; i < peers.Length; i++) { String brokerString = peers[i].BrokerURL; Add(brokerString); } } initialized = true; } } } this.Command(sender, command); }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); this.trador.QueryFund(); this.trador.QueryHold(); autoResetEvent.WaitOne(5000); if (this.brokerAccount != null) { brokerInfo.Accounts.Add(this.brokerAccount); } return(brokerInfo); }
// // Write a object instance to data output stream // public override void LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut) { BrokerInfo info = (BrokerInfo)o; base.LooseMarshal(wireFormat, o, dataOut); LooseMarshalCachedObject(wireFormat, (DataStructure)info.BrokerId, dataOut); LooseMarshalString(info.BrokerURL, dataOut); LooseMarshalObjectArray(wireFormat, info.PeerBrokerInfos, dataOut); LooseMarshalString(info.BrokerName, dataOut); dataOut.Write(info.SlaveBroker); dataOut.Write(info.MasterBroker); dataOut.Write(info.FaultTolerantConfiguration); }
/// <summary> /// Handle incoming commands /// </summary> /// <param name="commandTransport">An ITransport</param> /// <param name="command">A Command</param> protected void OnCommand(ITransport commandTransport, Command command) { if (command is MessageDispatch) { DispatchMessage((MessageDispatch)command); } else if (command is KeepAliveInfo) { OnKeepAliveCommand(commandTransport, (KeepAliveInfo)command); } else if (command is WireFormatInfo) { this.brokerWireFormatInfo = (WireFormatInfo)command; } else if (command is BrokerInfo) { this.brokerInfo = (BrokerInfo)command; } else if (command is ShutdownInfo) { if (!closing && !closed) { OnException(commandTransport, new NMSException("Broker closed this connection.")); } } else if (command is ConnectionError) { if (!closing && !closed) { ConnectionError connectionError = (ConnectionError)command; BrokerError brokerError = connectionError.Exception; string message = "Broker connection error."; string cause = ""; if (null != brokerError) { message = brokerError.Message; if (null != brokerError.Cause) { cause = brokerError.Cause.Message; } } OnException(commandTransport, new NMSConnectionException(message, cause)); } } else { Tracer.Error("Unknown command: " + command); } }
public ActionResult Update(int id) { if (id != 0) { BrokerInfo broker = _brokerBLL.GetBroker(id); var brokerVM = new BrokerViewModels(); brokerVM.BrokerInfo = broker; return(View(brokerVM)); } else { return(RedirectToAction("List")); } }
// // Write a object instance to data output stream // public override void TightMarshal2(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut, BooleanStream bs) { base.TightMarshal2(wireFormat, o, dataOut, bs); BrokerInfo info = (BrokerInfo)o; TightMarshalCachedObject2(wireFormat, (DataStructure)info.BrokerId, dataOut, bs); TightMarshalString2(info.BrokerURL, dataOut, bs); TightMarshalObjectArray2(wireFormat, info.PeerBrokerInfos, dataOut, bs); TightMarshalString2(info.BrokerName, dataOut, bs); bs.ReadBoolean(); bs.ReadBoolean(); bs.ReadBoolean(); }
public async Task <AllBrokerData> SellStock(BrokerInfo brokerInfo) { var stockbuy = new StockMarketService(); var markets = cache.Get <List <AllStockMarketRecords> >(Constants.marketData); var playerBrokerAccount = cache.Get <AllBrokerData>(brokerInfo.PlayerName + "_Broker"); if (playerBrokerAccount == null) { throw new Exception("No broker account exists for provided player"); } var playerBankAccount = cache.Get <AllBankRecords>(brokerInfo.PlayerName + "_Bank"); var turn = cache.Get <Clock>(brokerInfo.PlayerName + "_Clock"); var totalPrice = brokerInfo.StockPrice * brokerInfo.Quantity; var bankTransaction = new BankTransaction(); bankTransaction.PlayerName = playerBankAccount.Accounts.PlayerName; bankTransaction.Price = totalPrice; bankTransaction.Transceiver = brokerInfo.Sector; bankTransaction.Turn = turn.PlayerTurn + 1; await bankService.Deposit(bankTransaction); var brokerRecords = new AllBrokerData() { }; brokerRecords = playerBrokerAccount; brokerInfo.Status = Constants.sellStock; brokerInfo.IsAvailable = false; brokerRecords.BrokerInfos.Add(brokerInfo); foreach (var item in brokerRecords.BrokerInfos) { if (item.Sector == brokerInfo.Sector && item.Stock == brokerInfo.Stock && item.Quantity == brokerInfo.Quantity && item.Status == Constants.boughtStock) { item.IsAvailable = false; } } cache.Set(brokerInfo.PlayerName + "_Broker", brokerRecords, Constants.cacheTime); TurnChange(); var CompaniesList = await GetStocks(brokerInfo.Stock); stockbuy.PriceUpdate(brokerInfo, CompaniesList, markets, "Sell"); return(brokerRecords); }
// // Write the booleans that this object uses to a BooleanStream // public override int TightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) { BrokerInfo info = (BrokerInfo)o; int rc = base.TightMarshal1(wireFormat, info, bs); rc += TightMarshalCachedObject1(wireFormat, (DataStructure)info.BrokerId, bs); rc += TightMarshalString1(info.BrokerURL, bs); rc += TightMarshalObjectArray1(wireFormat, info.PeerBrokerInfos, bs); rc += TightMarshalString1(info.BrokerName, bs); bs.WriteBoolean(info.SlaveBroker); bs.WriteBoolean(info.MasterBroker); bs.WriteBoolean(info.FaultTolerantConfiguration); return(rc + 0); }
public void TestGetActualBroker() { var metadata = new Metadata { }; var b = new BrokerInfo { Id = "1", Host = "localhost", Port = 9292, }; metadata = metadata with { Brokers = metadata.Brokers.Add(b.Id, b) }; var broker = metadata.GetBroker("1"); Assert.Equal(b, broker); }
public async Task <AllBrokerData> BuyStock(BrokerInfo brokerInfo) { var stockbuy = new StockMarketService(); var markets = cache.Get <List <AllStockMarketRecords> >(Constants.marketData); var playerBrokerAccount = cache.Get <AllBrokerData>(brokerInfo.PlayerName + "_Broker"); if (playerBrokerAccount == null) { throw new Exception("No broker account exists for provided player"); } var playerBankAccount = cache.Get <AllBankRecords>(brokerInfo.PlayerName + "_Bank"); var turn = cache.Get <Clock>(brokerInfo.PlayerName + "_Clock"); var totalPrice = brokerInfo.StockPrice * brokerInfo.Quantity; if (playerBankAccount != null) { if (playerBankAccount.Accounts.Balance < totalPrice) { throw new Exception("Player doesn't have enough money to buy"); } } var bankTransaction = new BankTransaction(); bankTransaction.PlayerName = playerBankAccount.Accounts.PlayerName; bankTransaction.Price = totalPrice; bankTransaction.Transceiver = brokerInfo.Sector; bankTransaction.Turn = turn.PlayerTurn + 1; await bankService.Withdraw(bankTransaction); var brokerRecords = new AllBrokerData(); brokerRecords = playerBrokerAccount; brokerInfo.Status = Constants.boughtStock; brokerInfo.IsAvailable = true; brokerRecords.BrokerInfos.Add(brokerInfo); cache.Set(brokerInfo.PlayerName + "_Broker", brokerRecords, Constants.cacheTime); TurnChange(); var CompaniesList = await GetStocks(brokerInfo.Stock); stockbuy.PriceUpdate(brokerInfo, CompaniesList, markets, "Buy"); return(brokerRecords); }
private BrokerInfo CreateBrokerInfo(int nodeId, string host, int port, int partitionId, bool leader) { var brokerInfo = new BrokerInfo { Host = host + nodeId, NodeId = nodeId, Port = port }; var partition = new Partition { PartitionId = partitionId, Role = leader ? Partition.Types.PartitionBrokerRole.Leader : Partition.Types.PartitionBrokerRole.Follower }; brokerInfo.Partitions.Add(partition); return(brokerInfo); }
public async Task <AllBrokerData> BuyStock(BrokerInfo brokerInfo) { var playerBrokerAccount = cache.Get <AllBrokerData>(brokerInfo.PlayerName + "_Broker"); if (playerBrokerAccount == null) { throw new Exception("No broker account exists for provided player"); } var playerBankAccount = cache.Get <AllBankRecords>(brokerInfo.PlayerName + "_Bank"); var turn = cache.Get <Clock>(brokerInfo.PlayerName + "_Clock"); var totalPrice = brokerInfo.StockPrice * brokerInfo.Quantity; if (playerBankAccount != null) { if (playerBankAccount.Accounts.Balance < totalPrice) { throw new Exception("Player doesn't have enough money to buy"); } } var bankTransaction = new BankTransaction(); bankTransaction.PlayerName = playerBankAccount.Accounts.PlayerName; bankTransaction.Price = totalPrice; bankTransaction.Transceiver = brokerInfo.Sector; bankTransaction.Turn = turn.PlayerTurn + 1; await bankService.Withdraw(bankTransaction); var brokerRecords = new AllBrokerData(); brokerRecords = playerBrokerAccount; brokerInfo.Status = Constants.boughtStock; brokerRecords.BrokerInfos.Add(brokerInfo); cache.Set(brokerInfo.PlayerName + "_Broker", brokerRecords, Constants.cacheTime); return(brokerRecords); }
public void Send(String msg) { logger.Debug("▼▽▼▽▼▽ SEND BROKER ▼▽▼▽▼▽"); logger.Debug(msg); logger.Debug("△▲△▲△▲ SEND BROKER △▲△▲△▲"); if (Debug.IsDebug()) { return; } Thread thread = new Thread(() => { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); if (Debug.IsDebug()) { Console.WriteLine(msg); return; } socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), BrokerInfo.GetPort())); byte[] data = Encoding.UTF8.GetBytes(msg); byte[] size = BitConverter.GetBytes(data.Length); socket.Send(size, 4, SocketFlags.None); socket.Send(data, data.Length, SocketFlags.None); try { byte[] ret = new byte[1]; socket.Receive(ret, 1, SocketFlags.None); socket.Close(); } catch (Exception e) { logger.Error(e); } }); queue.Add(thread); thread.Start(); }
/// <summary> /// Handle incoming commands /// </summary> /// <param name="transport">An ITransport</param> /// <param name="command">A Command</param> protected void OnCommand(ITransport transport, Command command) { if (command is MessageDispatch) { MessageDispatch dispatch = (MessageDispatch)command; ConsumerId consumerId = dispatch.ConsumerId; MessageConsumer consumer = (MessageConsumer)consumers[consumerId]; if (consumer == null) { Tracer.Error("No such consumer active: " + consumerId); } else { ActiveMQMessage message = (ActiveMQMessage)dispatch.Message; consumer.Dispatch(message); } } else if (command is WireFormatInfo) { this.brokerWireFormatInfo = (WireFormatInfo)command; } else if (command is BrokerInfo) { this.brokerInfo = (BrokerInfo)command; } else if (command is ShutdownInfo) { //ShutdownInfo info = (ShutdownInfo)command; if (!closing && !closed) { OnException(transport, new NMSException("Broker closed this connection.")); } } else { Tracer.Error("Unknown command: " + command); } }
public void StingrayOQConstructorTest() { // StingrayOQ target = new StingrayOQ(); StingrayOQ_Accessor target = new StingrayOQ_Accessor(); // base Properties Assert.AreEqual("finantic's Execution Provider for Interactive Brokers", target.description, "Description"); Assert.AreEqual(129, target.id, "Id"); Assert.AreEqual("StingrayOQ", target.name, "Name"); Assert.AreEqual("http://www.finantic.de", target.url, "Url"); // Properties Assert.AreEqual("1.42.3.5", target.StingrayOQVersion, "StingrayOQVersion"); Assert.AreEqual(4262, target.ClientId, "ClientId"); Assert.AreEqual("127.0.0.1", target.Hostname, "HostName"); Assert.AreEqual(LogDestination.File, target.LogDestination, "LogDestination"); Assert.AreEqual(LoggerLevel.Error, target.LoggerLevel, "LoggerLevel"); Assert.AreEqual(false, target.OutsideRTH, "OutsideRTH"); Assert.AreEqual(7496, target.Port, "Port"); // TWS default port Assert.AreEqual(false, target.TWSConnected, "TWSConnected"); Assert.AreEqual(true, target.AutoTransmit, "AutoTransmit"); // FA Assert.AreEqual(FinancialAdvisorAllocationMethod.None, target.FAMethod, "FAMethod"); Assert.AreEqual(null, target.FAGroup, "FAGroup"); Assert.AreEqual(null, target.FAPercentage, "FAPercentage"); Assert.AreEqual(null, target.FAProfile, "FAProfile"); //Version must match AssemblyVersion in Mockups->AssemblyInfo.cs Assert.AreEqual("1.42.3.5", target.Version(), "Version"); // Accounts Assert.IsNotNull(target.Accounts, "Accounts not null"); // Broker Info BrokerInfo brokerInfo = target.GetBrokerInfo(); Assert.IsNotNull(brokerInfo, "brokerInfo not null"); }
protected virtual BrokerInfo GetBrokerInfo() { BrokerInfo bi = new BrokerInfo(); return bi; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { Console.WriteLine(string.Format("GetBrokerInfo:{0}", Clock.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"))); //TraderApi.TD_ReqQryTradingAccount(m_pTdApi); //TraderApi.TD_ReqQryInvestorPosition(m_pTdApi, null); //timerAccount.Enabled = false; //timerAccount.Enabled = true; //timerPonstion.Enabled = false; //timerPonstion.Enabled = true; BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID); // account fields brokerAccount.BuyingPower = m_TradingAccount.Available; brokerAccount.AddField("Available", m_TradingAccount.Available.ToString()); brokerAccount.AddField("Balance", m_TradingAccount.Balance.ToString()); brokerAccount.AddField("CashIn", m_TradingAccount.CashIn.ToString()); brokerAccount.AddField("CloseProfit", m_TradingAccount.CloseProfit.ToString()); brokerAccount.AddField("Commission", m_TradingAccount.Commission.ToString()); brokerAccount.AddField("Credit", m_TradingAccount.Credit.ToString()); brokerAccount.AddField("CurrMargin", m_TradingAccount.CurrMargin.ToString()); brokerAccount.AddField("DeliveryMargin", m_TradingAccount.DeliveryMargin.ToString()); brokerAccount.AddField("Deposit", m_TradingAccount.Deposit.ToString()); brokerAccount.AddField("ExchangeDeliveryMargin", m_TradingAccount.ExchangeDeliveryMargin.ToString()); brokerAccount.AddField("ExchangeMargin", m_TradingAccount.ExchangeMargin.ToString()); brokerAccount.AddField("FrozenCash", m_TradingAccount.FrozenCash.ToString()); brokerAccount.AddField("FrozenCommission", m_TradingAccount.FrozenCommission.ToString()); brokerAccount.AddField("FrozenMargin", m_TradingAccount.FrozenMargin.ToString()); brokerAccount.AddField("Interest", m_TradingAccount.Interest.ToString()); brokerAccount.AddField("InterestBase", m_TradingAccount.InterestBase.ToString()); brokerAccount.AddField("Mortgage", m_TradingAccount.Mortgage.ToString()); brokerAccount.AddField("PositionProfit", m_TradingAccount.PositionProfit.ToString()); brokerAccount.AddField("PreBalance", m_TradingAccount.PreBalance.ToString()); brokerAccount.AddField("PreCredit", m_TradingAccount.PreCredit.ToString()); brokerAccount.AddField("PreDeposit", m_TradingAccount.PreDeposit.ToString()); brokerAccount.AddField("PreMargin", m_TradingAccount.PreMargin.ToString()); brokerAccount.AddField("PreMortgage", m_TradingAccount.PreMortgage.ToString()); brokerAccount.AddField("Reserve", m_TradingAccount.Reserve.ToString()); brokerAccount.AddField("SettlementID", m_TradingAccount.SettlementID.ToString()); brokerAccount.AddField("Withdraw", m_TradingAccount.Withdraw.ToString()); brokerAccount.AddField("WithdrawQuota", m_TradingAccount.WithdrawQuota.ToString()); DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TThostFtdcPosiDirectionType PosiDirection = (TThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? brokerPosition.LongQty = pos; else brokerPosition.ShortQty = -pos; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }
public BrokerInfo GetBrokerInfo() { BrokerInfo brokerInfo = new BrokerInfo(); if (IsConnected) { if (_bTdConnected) { //tdlog.Info("GetBrokerInfo"); } else { //if (nGetBrokerInfoCount < 5) //{ // tdlog.Info("GetBrokerInfo,交易没有连接,查询无效,5次后将不显示"); // ++nGetBrokerInfoCount; //} return null; } BrokerAccount brokerAccount = new BrokerAccount(m_TradingAccount.AccountID); // account fields brokerAccount.BuyingPower = m_TradingAccount.Available; Type t = typeof(CZQThostFtdcTradingAccountField); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { brokerAccount.AddField(field.Name, field.GetValue(m_TradingAccount).ToString()); } DataRow[] rows = _dbInMemInvestorPosition.SelectAll(); foreach (DataRow dr in rows) { BrokerPosition brokerPosition = new BrokerPosition { Symbol = dr[DbInMemInvestorPosition.InstrumentID].ToString() }; int pos = (int)dr[DbInMemInvestorPosition.Position]; TZQThostFtdcPosiDirectionType PosiDirection = (TZQThostFtdcPosiDirectionType)dr[DbInMemInvestorPosition.PosiDirection]; if (TZQThostFtdcPosiDirectionType.Long == PosiDirection) { brokerPosition.LongQty = pos; } else if (TZQThostFtdcPosiDirectionType.Short == PosiDirection) { brokerPosition.ShortQty = pos; } else { if (pos >= 0)//净NET这个概念是什么情况? brokerPosition.LongQty = pos; else brokerPosition.ShortQty = -pos; } brokerPosition.Qty = brokerPosition.LongQty - brokerPosition.ShortQty; brokerPosition.AddCustomField(DbInMemInvestorPosition.PosiDirection, PosiDirection.ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.HedgeFlag, ((TZQThostFtdcHedgeFlagType)dr[DbInMemInvestorPosition.HedgeFlag]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.PositionDate, ((TZQThostFtdcPositionDateType)dr[DbInMemInvestorPosition.PositionDate]).ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.LongFrozen, dr[DbInMemInvestorPosition.LongFrozen].ToString()); brokerPosition.AddCustomField(DbInMemInvestorPosition.ShortFrozen, dr[DbInMemInvestorPosition.ShortFrozen].ToString()); brokerAccount.AddPosition(brokerPosition); } brokerInfo.Accounts.Add(brokerAccount); } return brokerInfo; }