Ejemplo n.º 1
0
        private void ScheduleMessages(long delay, SimulationMessage message)
        {
            var atTime = delay + TimePeriod;

            if (!_messageStash.TryGetValue(atTime, out PriorityQueue <SimulationMessage> stash))
            {
                stash = new PriorityQueue <SimulationMessage>();
                _messageStash.Add(atTime, stash);
            }
            stash.Enqueue(message);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PortfolioManager"/> class for running a backtest.
        /// </summary>
        /// <param name="portfolioimplementations">The portfolioimplementations.</param>
        /// <param name="simulation">The backtest.</param>
        public PortfolioManager(PortfolioImplementations portfolioimplementations, SimulationMessage simulation)
            : this(portfolioimplementations)
        {
            //Set initial message
            _initialMessageInstance = simulation;

            //Since this is a backtest request
            RunMode = RunMode.Backtester;

            //World clock is depended on data received
            var clock = new WorldClock(() => PortfolioImplementations.DataFeed.LastDataReceivedUtc == DateTime.MinValue ?
                                       simulation.StartDateTime :
                                       portfolioimplementations.DataFeed.LastDataReceivedUtc);

            //Get additional information
            if (!Enum.TryParse(simulation.AccountType, out AccountType accounttype))
            {
                throw new Exception($"Cannot initialize backtest account type {simulation.AccountType}");
            }
            if (!Enum.TryParse(simulation.BrokerType, out BrokerType brokertype))
            {
                throw new Exception($"Cannot initialize backtest broker type {simulation.BrokerType}");
            }
            if (!Enum.TryParse(simulation.BaseCurrency, out CurrencyType basecurrency))
            {
                throw new Exception($"Cannot initialize backtest base currency type {simulation.BaseCurrency}");
            }

            //Get latest currency rates, so we are up to date (trough forced reload)
            _log.Debug($"Initializing currency implementation: {PortfolioImplementations.Currency.GetType().FullName}");
            Config.LoadConfigFile <CurrencyRatesConfig[]>(Config.GlobalConfig.CurrencyRatesConfigFile, true);
            PortfolioImplementations.Currency.Initialize(clock, true);

            //Get broker model
            var brokermodel = BrokerModelFactory.GetBroker(accounttype, brokertype);

            //Check if the currency selected matches the currency of this broker (for instance when using crypto currencies)
            decimal allocatedfunds = simulation.QuantFund.AllocatedFunds;
            brokermodel.GetCompatibleInitialCapital(portfolioimplementations.Currency, ref basecurrency, ref allocatedfunds);
            simulation.QuantFund.AllocatedFunds = allocatedfunds;

            //Create portfolio
            _portfolio = CreatePortfolio(simulation.PortfolioId, Guid.NewGuid().ToString(), brokermodel,
                                         simulation.Leverage, basecurrency, basecurrency, clock, simulation.ExtendedMarketHours);

            //Set initial funds
            _portfolio.CashManager.AddCash(basecurrency, allocatedfunds);

            //Set initial fund message
            _initialFundMessage = simulation.QuantFund;
        }
Ejemplo n.º 3
0
        public static int GetSimulationPercentComplete(string simulationID)
        {
            int percent = 0;

            if (RunSimulation.Simulations.ContainsKey(simulationID))
            {
                List <SimulationMessage> listSimulation = Simulation.SimulationMessaging.GetProgressList();
                lock (listSimulation)
                {
                    SimulationMessage message = listSimulation.FindLast(delegate(SimulationMessage sm) { return(sm.SimulationID == simulationID); });
                    percent = message.Percent;
                }
            }
            return(percent);
        }
        public void MessageArrived(string channelName, object message)
        {
            if (channelName == "SimulationMessageChannel")
            {
                if (message is SimulationMessage)
                {
                    SimulationMessage simMessage = (SimulationMessage)message;

                    if (simMessage == SimulationMessage.Alive)
                    {
                        this.communicator.AttemptSimulationConnection();
                    }
                    else if (simMessage == SimulationMessage.Dead)
                    {
                        this.communicator.SimulatorLost();
                    }
                    else if (simMessage == SimulationMessage.Searching)
                    {
                        try
                        {
                            // notify
                            Console.WriteLine(DateTime.Now.ToString() + ": Received Simulation Search Message");

                            // ping sim
                            bool b = this.communicator.PingSimulation();

                            if (!b)
                            {
                                // notify
                                Console.WriteLine(DateTime.Now.ToString() + ": Not connected to sim, reconnecting");

                                // attempt sim connect
                                this.communicator.AttemptSimulationConnection();
                            }
                        }
                        catch
                        {
                            // notify
                            Console.WriteLine(DateTime.Now.ToString() + ": Not connected to sim, reconnecting");

                            // attempt sim connect
                            this.communicator.AttemptSimulationConnection();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Adds the message passed message to the agent's message collection identified byt he passed agent id.
        /// </summary>
        /// <param name="agentId">Agent identifier.</param>
        /// <param name="message">Message.</param>
        public void AddMessageForAgent(Guid agentId, SimulationMessage message)
        {
            // try to get any messages already added for this agent
            var labelMessagesForSingleAgent = GetMessagesForAgent(agentId);

            // if there are no messages for this agent in the collection, create a message collection for this agent
            if (!labelMessagesForMultipleAgents.ContainsKey(agentId))
            {
                labelMessagesForMultipleAgents.Add(agentId, labelMessagesForSingleAgent);
            }

            // if there are no messages of the passed type in the agent's message collection, add it to his collection
            //if (!labelMessagesForSingleAgent.ContainsKey(message.Type))
            //{
            //	Color fontColor;
            //	int fontSizeContent;
            //	string fontPath = GetLabelFontDetails(out fontColor, out fontSizeContent);
            //	//SimulationLabel labelMessage = controlFactory.CreateSimulationLabel(Vector.Zero, fontPath, fontSizeContent, fontColor, message);
            //	//labelMessagesForSingleAgent.Add(message.Type, labelMessage);
            //}
        }
Ejemplo n.º 6
0
 public SimulationLabel(Vector position, TrueTypeText trueTypeText, SimulationMessage simulationMessage)
 {
     TrueTypeText      = trueTypeText;
     SimulationMessage = simulationMessage;
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Initialize message queue instance
        /// </summary>
        public void Initialize()
        {
            //Check if assembly exists
            if (!TryConvertAssemblyToBase64(Config.PortfolioConfig.Assembly, out string assembly))
            {
                _log.Error($"Cannot derive quant fund from base64 encoded variant, please check input");
                return;
            }

            //Get message instance based on config
            if (Config.GlobalConfig.Mode == "Backtester")
            {
                //Check if quant funds are defined in config
                if (Config.PortfolioConfig.QuantFunds.Length == 0)
                {
                    _log.Error($"No quant funds defined in portfolio config, cannot initiate backtest");
                    return;
                }

                //Set initiating message
                SimulationMessage backtestmessage = new SimulationMessage
                {
                    UniqueId            = Guid.NewGuid().ToString(),
                    AccountType         = Config.PortfolioConfig.AccountType,
                    BaseCurrency        = Config.PortfolioConfig.BaseCurrency,
                    BrokerType          = Config.PortfolioConfig.BrokerType,
                    Leverage            = Config.PortfolioConfig.Leverage,
                    MessageType         = MessageType.Backtest,
                    IsResult            = false,
                    PortfolioId         = Guid.NewGuid().ToString(),
                    SendUtc             = DateTime.UtcNow,
                    StartDateTime       = Time.FromUnixTime(Config.PortfolioConfig.StartDateUtc),
                    EndDateTime         = Time.FromUnixTime(Config.PortfolioConfig.EndDateUtc),
                    FrameworkVersion    = Framework.CurrentVersion,
                    ExtendedMarketHours = Config.PortfolioConfig.ExtendedMarketHours
                };

                //Set fund message
                backtestmessage.QuantFund = CreateFund(Config.PortfolioConfig.QuantFunds[0], assembly);

                //Add to known messages
                messages.Add(backtestmessage);
            }
            else if (Config.GlobalConfig.Mode == "LiveTrading")
            {
                //Create message
                var livetradingmessage = new LiveTradingMessage
                {
                    AccountId           = "",
                    AccountType         = Config.PortfolioConfig.AccountType,
                    QuantFund           = CreateFund(Config.PortfolioConfig.QuantFunds[0], assembly),
                    UniqueId            = Guid.NewGuid().ToString(),
                    MessageType         = MessageType.LiveTrading,
                    SendUtc             = DateTime.UtcNow,
                    FrameworkVersion    = Framework.CurrentVersion,
                    IsResult            = false,
                    BaseCurrency        = Config.PortfolioConfig.BaseCurrency,
                    BrokerType          = Config.PortfolioConfig.BrokerType,
                    ExtendedMarketHours = Config.PortfolioConfig.ExtendedMarketHours,
                    Leverage            = Config.PortfolioConfig.Leverage,
                    PortfolioId         = Guid.NewGuid().ToString(),
                    DisplayCurrency     = Config.PortfolioConfig.DisplayCurrency,
                    ResultOk            = false,
                    ResultMessage       = string.Empty
                };

                //Add to known messages
                messages.Add(livetradingmessage);
            }
            else
            {
                _log.Error($"Could not initialize local message queue, no input found in global config");
            }
        }