/// <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); }
void Start() { IPconfigScript = FindObjectOfType <BrokerConnection>(); TopicScript = FindObjectOfType <DropdownMessageTopic>(); messages = new List <string>(); //PopulateDropDownList(); }
/// <summary> /// Sends the instance information message. /// </summary> /// <param name="connection">The connection.</param> public void SendInstanceInfoMessage(BrokerConnection connection) { if (!IsRunning || !HasSubscribers) { return; } Enqueue(InstanceMessage.Generate(connection)); }
/// <summary> /// <description>Function that only allows one intance of this script to exist in the game scene</description> /// </summary> public void SingletonCheck() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); } }
/// <summary> /// Generate instance information message /// </summary> /// <param name="broker"></param> /// <returns></returns> public static InstanceMessage Generate(BrokerConnection broker) { return(new InstanceMessage { CPU = Instance.CpuUsedPercentage, LatencyInMS = broker.LatencyInMS, Location = Config.GlobalConfig.ServerLocation, RAM = Instance.PhysicalMemoryUsed, Server = Config.GlobalConfig.ServerName }); }
static void Main(string[] args) { Console.SetOut(new PrefixedWriter()); var database = new List <API.DemoMessage>(); var connection = new BrokerConnection(); connection.Open(); Console.WriteLine("Connected"); connection.SubscribeRead(); connection.SubscribeWrite(); Console.WriteLine("Subscribed to \'demo.read.single\' and \'demo.write.single\'"); connection.WriteToDatabaseEvent += (o, e) => { var match = database.FirstOrDefault(message => message.Id == e.Message.Id); if (match == null) { database.Add(e.Message); Console.WriteLine("Added a new message to database: Id: [{0}], description: {1}", e.Message.Id, e.Message.Description); } else { match.Description = e.Message.Description; match.Updated = e.Message.Updated; Console.WriteLine("Updated message: Id: [{0}], description: {1}, updated: {2}", e.Message.Id, e.Message.Description, e.Message.Updated.ToDateTime()); } }; connection.ReadFromDatabaseEvent += (o, e) => { Console.WriteLine("Got read from database request for ID: [{0}], with reply queue: [{1}]", e.Message.Id, e.ReplyQueue); var match = database.FirstOrDefault(message => message.Id == e.Message.Id); if (match == null) { Console.WriteLine("No match found in database for ID: [{0}], aborting request", e.Message.Id); return; } connection.PublishRead(e.ReplyQueue, match); Console.WriteLine("Match found, message written to queue: [{0}],\n" + "Id: [{1}], description: [{2}], updated: [{3}]", e.ReplyQueue, match.Id, match.Description, match.Updated); }; Console.ReadKey(); connection.Close(); Console.WriteLine("Disconnected"); }
public void Register() { var connection = new BrokerConnection { EndPoint = KeyVault.GetValue("RABBITMQ_ENDPOINT"), Port = Convert.ToInt32(KeyVault.GetValue("RABBITMQ_PORT")), QueueName = KeyVault.GetValue("RESERVATION_RESPONSE_QUEUENAME"), UserName = "******", Password = "******" }; _messageBroker.ReceiveMessageAsync( connection, actionEvent: NotificationEventsHandler.NotificationReceived ); }
/// <summary> /// Initializes a new instance of the <see cref="PortfolioImplementations"/> class. /// </summary> /// <param name="actionsScheduler">The actions scheduler.</param> /// <param name="api">The API.</param> /// <param name="brokerconnection">The brokerconnection.</param> /// <param name="cluster">The cluster.</param> /// <param name="datafeed">The datafeed.</param> /// <param name="datafilter">The datafilter.</param> /// <param name="eventrunner">The eventrunner.</param> /// <param name="exceptionhandler">The exceptionhandler.</param> /// <param name="messagequeue">The messagequeue.</param> /// <param name="ordertickethandler">The ordertickethandler.</param> /// <param name="currency">The currency.</param> public PortfolioImplementations(ActionsScheduler actionsScheduler, Benchmark benchmark, BrokerConnection brokerconnection, Cluster cluster, DataFeed datafeed, DataFilter datafilter, EventRunner eventrunner, ExceptionHandler exceptionhandler, MessageQueue messagequeue, OrderTicketHandler ordertickethandler, Currency currency) { ActionsScheduler = actionsScheduler; Benchmark = benchmark; BrokerConnection = brokerconnection; Cluster = cluster; DataFeed = datafeed; DataFilter = datafilter; EventRunner = eventrunner; ExceptionHandler = exceptionhandler; MessageQueue = messagequeue; OrderTicketHandler = ordertickethandler; Currency = currency; }
/// <summary> /// Process submit order /// </summary> /// <param name="ticket"></param> protected virtual OrderTicketResponse CancelOrder(CancelOrderTicket ticket) { //Check if we can get the order if (!OrderTracker.TryGetOrder(ticket.OrderId, out PendingOrder pendingorder)) { _log.Error($"Unable to cancel order with ID {ticket.OrderId}, order id unkown."); return(OrderTicketResponse.Error(ticket.OrderId, OrderTicketResponseErrorCode.UnableToFindOrder)); } //Check if order is closed if (pendingorder.Order.State.IsDone()) { return(OrderTicketResponse.Error(ticket.OrderId, OrderTicketResponseErrorCode.InvalidOrderStatus)); } //try and cancel the order bool ordercancelled = false; try { ordercancelled = BrokerConnection.CancelOrder(pendingorder); } catch (Exception exc) { _log.Error(exc, $"Could not cancel order with id {ticket.OrderId} broker connection refused to do so"); } //If not managed to cancel if (!ordercancelled) { var message = $"Brokerconnection failed to cancel order with id {ticket.OrderId}"; Portfolio.Log(LogLevel.Error, message); HandleOrderTicketEvent(OrderTicketEvent.Error(ticket.OrderId)); return(OrderTicketResponse.Error(ticket.OrderId, OrderTicketResponseErrorCode.BrokerageFailedToCancelOrder)); } //Order was cancelled var order = pendingorder.Order as OrderImpl; order.State = OrderState.Cancelled; pendingorder.UpdateOrder(order); //Return result for order ticket return(OrderTicketResponse.Processed(ticket.OrderId)); }
public List <PriceCandle> GetPriceCandles(string broker, string granularity, DateTime from, string mode = "Practice") { switch (broker) { case "Oanda": _factory = new OandaFactory(mode, _configuration); break; default: break; } BrokerConnection connection = _factory.GetBrokerConnection(); List <PriceCandle> candle = connection.FetchCandles(granularity, from); return(candle); }
public static async Task Main(string[] args) { Console.SetOut(new PrefixedWriter()); var connection = new BrokerConnection(); connection.Open(); Console.WriteLine("Connected"); // Subscribe to any requests received connection.Subscribe(); Console.WriteLine("Subscribed to to anonymous queue"); // Produce couple of messages to queue var msg1 = new API.DemoMessage { Id = 10, Description = "First message", Updated = Timestamp.FromDateTime(DateTime.Now.ToUniversalTime()) }; var msg2 = new API.DemoMessage { Id = 20, Description = "Second message", Updated = Timestamp.FromDateTime(DateTime.Now.ToUniversalTime()) }; connection.Produce(msg1); connection.Produce(msg2); Console.WriteLine("Produced 2 messages to queue: \'demo.write.single\'"); // Ask for some message from queue try { Console.WriteLine("Sent request for queue: \'demo.read.single\' with id: 10"); var received1 = await TimeoutAfter(Requests.RequestMessage(connection, 10), TimeSpan.FromSeconds(2)); Console.WriteLine("Received message: ID: [{0}], Description: [{1}], Updated: [{2}]", received1.Id, received1.Description, received1.Updated); } catch (TimeoutException e) { Console.WriteLine(e.Message); } connection.Close(); Console.WriteLine("Disconnected"); }
/// <summary> /// Synchronizes the current brokerage funds with the fund manager. /// TODO: needs to be done regularly /// </summary> protected virtual void SyncbrokerageFunds() { try { if (!Monitor.TryEnter(_balancechecklocker)) { return; } //Logging _log.Trace($"Performing brokerage funds synchronization for broker {BrokerConnection.BrokerType}"); IReadOnlyList <CashPosition> currentfunds = null; try { currentfunds = BrokerConnection.GetAccountFunds(); } catch (Exception exc) { _log.Error(exc); } //Check if we have data if (currentfunds == null || currentfunds.Count == 0) { return; } //Perform sync to fund manager foreach (var funds in currentfunds) { CashManager.Process(AccountActionType.Sync, funds.BaseCurrency, funds.TotalCash); } //Set to already synced _lastBalanceSync = Portfolio.Clock.CurrentUtc; } finally { Monitor.Exit(_balancechecklocker); } }
/// <summary> /// Add booking actor method. /// Send a message to theater azure function via service bus. Just for *DEMO* /// Save the booking object in state /// </summary> /// <param name="booking">booking object</param> /// <returns></returns> public async Task AddBooking(Booking booking, CancellationToken cancellationToken) { var connection = new BrokerConnection { EndPoint = KeyVault.GetValue("RABBITMQ_ENDPOINT"), Port = Convert.ToInt32(KeyVault.GetValue("RABBITMQ_PORT")), QueueName = _queueName, UserName = "******", Password = "******" }; try { await this._bookingMessageBroker.SendMessageAsync( connection, booking); await this._bookingRepository.AddBooking(booking); } catch (Exception ex) { throw ex; } }
private RemotingRequest BuildBatchSendMessageRequest(IEnumerable <Message> messages, int queueId, BrokerConnection brokerConnection) { var request = new BatchSendMessageRequest { Messages = messages, QueueId = queueId, ProducerAddress = brokerConnection.RemotingClient.LocalEndPoint.ToAddress() }; var data = BatchMessageUtils.EncodeSendMessageRequest(request); if (data.Length > Setting.MessageMaxSize * messages.Count()) { throw new Exception("Message size cannot exceed max message size:" + Setting.MessageMaxSize); } return(new RemotingRequest((int)BrokerRequestCode.BatchSendMessage, data)); }
private RemotingRequest BuildSendMessageRequest(Message message, int queueId, BrokerConnection brokerConnection) { var request = new SendMessageRequest { Message = message, QueueId = queueId, ProducerAddress = brokerConnection.RemotingClient.LocalEndPoint.ToAddress() }; var data = MessageUtils.EncodeSendMessageRequest(request); if (data.Length > Setting.MessageMaxSize) { throw new Exception("Message size cannot exceed max message size:" + Setting.MessageMaxSize); } return(new RemotingRequest((int)BrokerRequestCode.SendMessage, data)); }
public void SetUp() { this.mqttClientMock = new Mock <MqttClient>(); this.brokerConnection = new BrokerConnection("0040744360800"); }
private bool TryGetAvailableMessageQueue(Message message, string routingKey, out MessageQueue messageQueue, out BrokerConnection brokerConnection) { messageQueue = null; brokerConnection = null; var retryCount = 0; while (retryCount <= Setting.SendMessageMaxRetryCount) { messageQueue = GetAvailableMessageQueue(message, routingKey); if (messageQueue == null) { if (retryCount == 0) { _logger.ErrorFormat("No available message queue for topic [{0}]", message.Topic); } else { _logger.ErrorFormat("No available message queue for topic [{0}], retryTimes: {1}", message.Topic, retryCount); } } else { brokerConnection = _clientService.GetBrokerConnection(messageQueue.BrokerName); if (brokerConnection != null && brokerConnection.RemotingClient.IsConnected) { return(true); } if (retryCount == 0) { _logger.ErrorFormat("Broker is unavailable for queue [{0}]", messageQueue); } else { _logger.ErrorFormat("Broker is unavailable for queue [{0}], retryTimes: {1}", message.Topic, retryCount); } } retryCount++; } return(false); }
protected override void ConnectToBroker(BrokerConnection brokerConn) { brokerConn.Connection = MockConn.Object; }
/// <summary> /// Default constructor /// </summary> /// <param name="brokerConnection"></param> public MessagePublisher(BrokerConnection brokerConnection) { _channel = brokerConnection?.CreateChannel() ?? throw new ArgumentNullException(nameof(brokerConnection)); }
/// <summary> /// Process submit order /// </summary> /// <param name="ticket"></param> protected virtual OrderTicketResponse SubmitOrder(SubmitOrderTicket ticket) { //Get order from factory PendingOrder pendingorder = OrderFactory.CreateOrder(ticket); OrderImpl order = pendingorder.Order as OrderImpl; //Round off order quantity for correct amounts RoundLotSize(order); //try and get the order from the order tracker if (!OrderTracker.TryAddOrder(pendingorder)) { _log.Error($"Unable to add new order, order with id {pendingorder.OrderId} was already submitted"); return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.OrderAlreadyExists, $"Current order with id {pendingorder.OrderId} was already submitted")); } if (!OrderTracker.TryGetOrder(pendingorder.OrderId, out pendingorder)) { _log.Error($"Unable to retrieve newly added order, order with id {pendingorder.OrderId} was cannot be processed properly"); return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.UnableToFindOrder, $"Current order with id {pendingorder.OrderId} cannot be found")); } //Round of prices RoundOrderPrices(order); //Set our new order pendingorder.UpdateOrder(order); //Check for correct size if (order.Quantity == 0) { order.State = OrderState.Invalid; var ticketresponse = OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.OrderQuantityZero); Portfolio.Log(LogLevel.Error, ticketresponse.ErrorMessage); return(ticketresponse); } //Check if we have enough capital for an order bool sufficientcapital = GetSufficientCapitalForOrder(pendingorder); if (!sufficientcapital) { //Not enough capital to execute this order order.State = OrderState.Invalid; var response = OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.InsufficientBuyingPower, $"Cannot execute order with id {order.InternalId}, insufficient funds to execute order."); Portfolio.Log(LogLevel.Error, response.ErrorMessage); HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, $"Insufficent capital to execute order")); return(response); } //Check if broker accepts order at this moment try { if (!Portfolio.BrokerModel.CanSubmitOrder(order, out var message)) { //Broker model did not accept this order order.State = OrderState.Invalid; var response = OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.BrokerageModelRefusedToSubmitOrder, $"Order with id {order.InternalId}: {message}"); Portfolio.Log(LogLevel.Error, ""); HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, $"Broker model of type {Portfolio.BrokerModel.BrokerType} declared order cannot be submitted, message: {message}")); return(response); } } catch (Exception exc) { _log.Error(exc, $"Could not run CanSubmitOrder on order with id {order.InternalId}, please check the implemented logic"); order.State = OrderState.Invalid; return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.ProcessingError, $"Current order with id {pendingorder.OrderId} cannot be processed due to error")); } //Try to execute this order to the broker connection attached bool ordersuccess = false; try { ordersuccess = BrokerConnection.SubmitOrder(pendingorder); } catch (Exception exc) { _log.Error(exc); } //Check if placing the order was a success if (!ordersuccess) { order.State = OrderState.Invalid; var submitmessage = "BrokerConnection failed to place order"; var response = OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.BrokerageFailedToSubmitOrder, submitmessage); Portfolio.Log(LogLevel.Error, submitmessage); HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, submitmessage)); return(response); } order.State = OrderState.Submitted; return(OrderTicketResponse.Processed(order.InternalId)); }
/// <summary> /// Submit update order /// </summary> /// <param name="ticket"></param> protected virtual OrderTicketResponse UpdateOrder(UpdateOrderTicket ticket) { //Get current pending order if (!OrderTracker.TryGetOrder(ticket.OrderId, out PendingOrder pendingorder)) { _log.Error($"Unable to retrieve order with id {ticket.OrderId} could not proceed"); return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.UnableToFindOrder, $"Current order with id {pendingorder.OrderId} cannot be found")); } //Get the order var order = pendingorder.Order as OrderImpl; //Check if we can update this order if (!CanUpdateOrder(order)) { return(OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.InvalidOrderStatus, $"Unable to update order with id {order.InternalId} and current state {order.State}")); } //Check if we can process this order try { if (!Portfolio.BrokerModel.CanUpdateOrder(order, out string message)) { //Notify we cannot update this order order.State = OrderState.Invalid; var response = OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.BrokerageModelRefusedToUpdateOrder, $"Cannot update order {order.InternalId}: {message}"); Portfolio.Log(LogLevel.Error, response.ErrorMessage); HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, response.ErrorMessage)); return(response); } } catch (Exception exc) { _log.Error(exc, $"Could not run CanUpdateOrder on order with id {order.InternalId}, please check the implemented logic"); order.State = OrderState.Invalid; return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.ProcessingError, $"Current order with id {pendingorder.OrderId} cannot be processed due to error")); } //Check order quantity and pricing in case this is out of range RoundLotSize(order); RoundOrderPrices(order); //Try and update this order bool orderupdatesucceeded = false; try { orderupdatesucceeded = BrokerConnection.UpdateOrder(pendingorder); } catch (Exception exc) { _log.Error(exc); } //Process a failed order update event if (!orderupdatesucceeded) { var errormessage = $"Broker connection failed to update order with id {order.InternalId} with connection type {BrokerConnection.BrokerType}"; Portfolio.Log(LogLevel.Error, errormessage); HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, "Failed to update order")); return(OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.BrokerageFailedToUpdateOrder, errormessage)); } else { //Apply updates to order order.Update(ticket); pendingorder.UpdateOrder(order); } return(OrderTicketResponse.Processed(order.InternalId)); }
public void Configure(Action <BrokerConnection> configure) { Connection = new BrokerConnection(); configure(Connection); }
private RemotingRequest BuildSendMessageRequest(Message message, int queueId, BrokerConnection brokerConnection) { var request = new SendMessageRequest { Message = message, QueueId = queueId }; request.Message.ProducerAddress = brokerConnection.RemotingClient.LocalEndPoint.ToAddress(); var data = MessageUtils.EncodeSendMessageRequest(request); if (data.Length > Setting.MessageMaxSize) { throw new Exception("Message size cannot exceed max message size:" + Setting.MessageMaxSize); } return new RemotingRequest((int)BrokerRequestCode.SendMessage, data); }
private bool TryGetAvailableMessageQueue(Message message, string routingKey, out MessageQueue messageQueue, out BrokerConnection brokerConnection) { messageQueue = null; brokerConnection = null; var retryCount = 0; while (retryCount <= Setting.SendMessageMaxRetryCount) { messageQueue = GetAvailableMessageQueue(message, routingKey); if (messageQueue == null) { if (retryCount == 0) { _logger.ErrorFormat("No available message queue for topic [{0}]", message.Topic); } else { _logger.ErrorFormat("No available message queue for topic [{0}], retryTimes: {1}", message.Topic, retryCount); } } else { brokerConnection = _clientService.GetBrokerConnection(messageQueue.BrokerName); if (brokerConnection != null && brokerConnection.RemotingClient.IsConnected) { return true; } if (retryCount == 0) { _logger.ErrorFormat("Broker is unavailable for queue [{0}]", messageQueue); } else { _logger.ErrorFormat("Broker is unavailable for queue [{0}], retryTimes: {1}", message.Topic, retryCount); } } retryCount++; } return false; }