Exemplo n.º 1
0
        public Simulation(
            ISimulationParameters simulationParams,
            IMutator mutator,
            IItemSelector itemSelector,
            IPopulationLogger logger,
            IEvaluator evaluator,
            ICrossoverSelector selector,
            ICrossBreeder breeder,
            IPopulationGenerator populationGenerator)
        {
            ObjectValidator.IfNullThrowException(simulationParams, nameof(simulationParams));
            ObjectValidator.IfNullThrowException(mutator, nameof(mutator));
            ObjectValidator.IfNullThrowException(itemSelector, nameof(itemSelector));
            ObjectValidator.IfNullThrowException(logger, nameof(logger));
            ObjectValidator.IfNullThrowException(evaluator, nameof(evaluator));
            ObjectValidator.IfNullThrowException(selector, nameof(selector));
            ObjectValidator.IfNullThrowException(breeder, nameof(breeder));
            ObjectValidator.IfNullThrowException(populationGenerator, nameof(populationGenerator));

            _mutator              = mutator;
            _itemSelector         = itemSelector;
            _logger               = logger;
            _evaluator            = evaluator;
            _selector             = selector;
            _breeder              = breeder;
            _populationGenerator  = populationGenerator;
            _simulationParameters = simulationParams;
        }
        public IEnumerable <Individual> GeneratePopulation(int size, ISimulationParameters sim)
        {
            var population = new List <Individual>();
            var array      = new int[sim.CitiesAmount + 1];
            var items      = (Item[])sim.Items.Clone();

            for (var i = 0; i < sim.CitiesAmount; i++)
            {
                array[i] = i + 1;
            }

            for (var i = 0; i < size; i++)
            {
                rand.Next();
                for (var j = 0; j < sim.CitiesAmount; j++)
                {
                    var index = rand.Next(sim.CitiesAmount);
                    var swp   = array[index];
                    array[index] = array[j];
                    array[j]     = swp;
                }

                array[sim.CitiesAmount] = array[0];
                population.Add(new Individual {
                    Route = (int[])array.Clone(), Picks = (Item[])items.Clone()
                });
            }

            return(population);
        }
Exemplo n.º 3
0
        private static void InitialiseContainer()
        {
            var containerBuilder = new ContainerBuilder();
            IDatabaseConnectionCredentials connectionCredentials = _appConfigurationManager.GetDatabaseConnectionCredentials();
            ISimulationParameters          simulationParameters  = _commandLineArgumentManager.GetSimulationParameters();

            containerBuilder.Register <ILogger>(x => _logger).SingleInstance();
            containerBuilder.Register <IDatabaseConnectionCredentials>(x => connectionCredentials).SingleInstance();
            containerBuilder.Register <ISimulationParameters>(x => simulationParameters).SingleInstance();
            containerBuilder.Register <IAppConfigurationManager>(x => _appConfigurationManager).SingleInstance();

            containerBuilder.RegisterType <SimulationTypeManager>().As <ISimulationTypeManager>().SingleInstance();
            containerBuilder.RegisterType <MySqlConnectionWrapper>().As <IMySqlConnectionWrapper>().SingleInstance();
            containerBuilder.RegisterType <PersistenceManager>().As <IPersistenceManager>().SingleInstance();
            containerBuilder.RegisterType <SecurityDataReader>().As <ISecurityDataReader>().SingleInstance();
            containerBuilder.RegisterType <NotificationManager>().As <INotificationManager>().SingleInstance();
            containerBuilder.RegisterType <DiagnosticManager>().As <IDiagnosticManager>().SingleInstance();

            containerBuilder.RegisterType <CalendarRebalanceScheduleManager>().As <ICalendarRebalanceScheduleManager>();
            containerBuilder.RegisterType <SecurityDataSqlFactory>().As <ISecurityDataSqlFactory>();
            containerBuilder.RegisterType <MySqlCommandWrapperFactory>().As <IMySqlCommandWrapperFactory>();
            containerBuilder.RegisterType <XmlModelFactory>().As <IXmlModelFactory>();
            containerBuilder.RegisterType <PortfolioValuationSummaryXmlWriter>().As <IPortfolioValuationSummaryReportWriter>();
            containerBuilder.RegisterType <StatisticsCalculationManager>().As <IStatisticsCalculationManager>();
            containerBuilder.RegisterType <HashingFilenameGenerator>().As <IHashingFilenameGenerator>();

            containerBuilder.RegisterType <PortfolioValuationReporter>().As <IPortfolioValuationReporter, IStartable>().SingleInstance();
            containerBuilder.RegisterType <MarketDataManager>().As <IMarketDataManager, IStartable>().SingleInstance();

            _container = containerBuilder.Build();
        }
Exemplo n.º 4
0
        public void recvSimulationNotification(ISimulationParameters sim, ISimulationEvent se)
        {
            SingletonLogger.Instance().DebugLog(typeof(AbstractPassiveTrajectoryFactory), "AbstractPassiveTrajectoryFactory recvSimulationNotification");

            // events received from ISimulation

            if (se.OrderbookEvent == null)
            {
                if (se is ISimulationStart)
                {
                    SingletonLogger.Instance().DebugLog(typeof(AbstractPassiveTrajectoryFactory), "AbstractPassiveTrajectoryFactory SET Sim!");
                    _sim = sim;
                    reset();
                    SimulationStartNotification();
                }

                if (se is ISimulationEnd)
                {
                    SimulationEndNotification();
                    SingletonLogger.Instance().DebugLog(typeof(AbstractPassiveTrajectoryFactory), "AbstractPassiveTrajectoryFactory CLEAR Sim!");
                    _sim = null;
                }
            }
            else
            {
                if (_sim == null)
                {
                    // too late
                    SingletonLogger.Instance().DebugLog(typeof(AbstractPassiveTrajectoryFactory), "AbstractPassiveTrajectoryFactory Too Late!");
                    return;
                }

                if (se.OrderbookEvent is IOrderbookEvent_FillOrder)
                {
                    IOrderbookEvent_FillOrder fillEvent = (IOrderbookEvent_FillOrder)se.OrderbookEvent;
                    IOrder filledOrder = fillEvent.getOrder();
                    if (fillEvent.orderFilled())
                    {
                        FilledOrderNotification(filledOrder, fillEvent.getExecutionPrice(), fillEvent.getVolume());
                    }
                    else
                    {
                        PartialFilledOrderNotification(filledOrder, fillEvent.getExecutionPrice(), fillEvent.getVolume());
                    }
                }
                else if (se.OrderbookEvent is IOrderbookEvent_AddOrder)
                {
                    IOrderbookEvent_AddOrder addEvent = (IOrderbookEvent_AddOrder)se.OrderbookEvent;
                    IOrder newOrder = addEvent.getOrder();
                    NewOrderNotification(newOrder);
                }
                else if (se.OrderbookEvent is IOrderbookEvent_CancelOrder)
                {
                    IOrderbookEvent_CancelOrder cancelEvent = (IOrderbookEvent_CancelOrder)se.OrderbookEvent;
                    IOrder cancelledOrder = cancelEvent.getOrder();
                    CancelOrderNotification(cancelledOrder);
                }
            }
        }
Exemplo n.º 5
0
        public void recvSimulationNotification(ISimulationParameters sim, ISimulationEvent se)
        {
            // events received from ISimulation

            if (se.OrderbookEvent == null)
            {
                if (se is ISimulationStart)
                {
                    SingletonLogger.Instance().DebugLog(typeof(AbstractAgentEvaluationFactory), "*** AbstractAgentEvaluationFactory got ISimulationStart");
                    _sim = sim;
                    reset();
                    SimulationStartNotification();
                }

                if (se is ISimulationEnd)
                {
                    SingletonLogger.Instance().DebugLog(typeof(AbstractAgentEvaluationFactory), "*** AbstractAgentEvaluationFactory got ISimulationEnd");
                    SimulationEndNotification();
                    _sim = null;
                }
            }
            else
            {
                SingletonLogger.Instance().DebugLog(typeof(AbstractAgentEvaluationFactory), "*** AbstractAgentEvaluationFactory got ISimulationEvent with non-null Orderbook");

                if (se.OrderbookEvent is IOrderbookEvent_FillOrder)
                {
                    IOrderbookEvent_FillOrder fillEvent = (IOrderbookEvent_FillOrder)se.OrderbookEvent;
                    IOrder filledOrder = fillEvent.getOrder();
                    if (fillEvent.orderFilled())
                    {
                        FilledOrderNotification(filledOrder, fillEvent.getExecutionPrice(), fillEvent.getVolume());
                    }
                    else
                    {
                        PartialFilledOrderNotification(filledOrder, fillEvent.getExecutionPrice(), fillEvent.getVolume());
                    }
                }
                else if (se.OrderbookEvent is IOrderbookEvent_AddOrder)
                {
                    IOrderbookEvent_AddOrder addEvent = (IOrderbookEvent_AddOrder)se.OrderbookEvent;
                    IOrder newOrder = addEvent.getOrder();
                    NewOrderNotification(newOrder);
                }
                else if (se.OrderbookEvent is IOrderbookEvent_CancelOrder)
                {
                    IOrderbookEvent_CancelOrder cancelEvent = (IOrderbookEvent_CancelOrder)se.OrderbookEvent;
                    IOrder cancelledOrder = cancelEvent.getOrder();
                    CancelOrderNotification(cancelledOrder);
                }
            }
        }
Exemplo n.º 6
0
        public MarketDataManager(ISecurityDataReader securityDataReader,
                                 INotificationManager notificationManager,
                                 ISimulationParameters simulationParameters)
        {
            _startDate        = simulationParameters.SimulationStartDate;
            _endDate          = simulationParameters.SimulationEndDate;
            _symbolCollection = simulationParameters.StockPortfolioSymbols;

            _securityDataReader  = securityDataReader;
            _notificationManager = notificationManager;

            _notificationManager.SimulationStarted += NotificationManager_SimulationStarted;
        }
Exemplo n.º 7
0
        internal static void Main(string[] args)
        {
            _appConfigurationManager    = new AppConfigurationManager();
            _commandLineArgumentManager = new CommandLineArgumentManager(_appConfigurationManager.UseCommandLineArgs, args);

            string logFile = _appConfigurationManager.GetLogFile();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(LogEventLevel.Verbose)
                         //.WriteTo.File(logFile, rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Verbose)
                         .CreateLogger();

            _logger = Log.Logger;

            InitialiseContainer();
            ISimulationTypeManager simulationTypeManager = _container.Resolve <ISimulationTypeManager>();

            simulationTypeManager.InitialiseManager(_commandLineArgumentManager.GetSimulationType());

            if (simulationTypeManager.SimulationManager == null)
            {
                _logger.Fatal("Unknown simulation type supplied.  Unable to proceed...");
                return;
            }

            simulationTypeManager.SimulationManager.Start();

            IAccount primaryAccount = _appConfigurationManager.GetAccount();
            ISimulationParameters simulationParameters = _container.Resolve <ISimulationParameters>();

            _logger.Information("Portfolio Simulation");
            _logger.Information("====================");
            _logger.Information($"Initial account: Currency: {primaryAccount.Currency} Balance: {primaryAccount.Balance}");
            _logger.Information($"Simulation Period: {simulationParameters.SimulationStartDate.ToShortDateString()} - {simulationParameters.SimulationEndDate.ToShortDateString()}");
            _logger.Information($"Simulation Type: {simulationParameters.SimulationType}");

            _logger.Information("Simulation starting...");
            var notificationManager = _container.Resolve <INotificationManager>();

            notificationManager.SimulationEnded += (s, e) => _simulationComplete = true;
            notificationManager.TriggerSimulationStart();

            while (!_simulationComplete)
            {
                System.Threading.Thread.Sleep(1000 * 10); // sleep for 10 seconds
            }
        }
Exemplo n.º 8
0
        public Individual EvaluateIndividual(Individual individual, ISimulationParameters simulationParams)
        {
            var result = new Individual
            {
                Picks = (Item[])individual.Picks.Clone(),
                Route = (int[])individual.Route.Clone()
            };

            var carrying = 0.0;
            var profit   = 0.0;
            var time     = 0.0;

            //for (var i = 0; i < simulationParams.Cities.Length; i++)
            //{
            //    result.Picks[i] = _itemSelector.SelectItemByPwRatio(simulationParams.Cities[result.Route[i] - 1]);
            //}

            if (result.Picks.Sum(s => s?.Weight ?? 0) > simulationParams.KnapsackCapacity)
            {
                result.Picks = _itemSelector.FreeKnapsackSpace(result.Picks, simulationParams.KnapsackCapacity);
            }

            for (var i = 0; i < simulationParams.Cities.Length; i++)
            {
                var index    = result.Route[i];
                var velocity = simulationParams.MaxSpeed - carrying *
                               (simulationParams.MaxSpeed - simulationParams.MinSpeed) /
                               simulationParams.KnapsackCapacity;
                var dist = simulationParams.Cities[index - 1]
                           .CalculateDistance(simulationParams.Cities[result.Route[i + 1] - 1]);
                time += dist / velocity;

                var item = result.Picks.SingleOrDefault(s => s.NodeNumber == index);
                carrying += item?.Weight ?? 0;
                profit   += item?.Profit ?? 0;
            }

            result.Profit  = profit;
            result.Time    = time;
            result.Fitness = 10 * profit - 0.3 * time;
            return(result);
        }
Exemplo n.º 9
0
        // handle events from simulation
        public void recvSimulationNotification(ISimulationParameters sim, ISimulationEvent se)
        {
            if (se.OrderbookEvent == null)
            {
                if (se is ISimulationStart)
                {
                    SingletonLogger.Instance().InfoLog(typeof(AbstractAgent), "AbstractAgent " + GetName() + " Start @ " + Scheduler.GetTime());
                    _sim = sim;
                    SimulationStartNotification(sim.Population);
                }

                if (se is ISimulationEnd)
                {
                    SingletonLogger.Instance().InfoLog(typeof(AbstractAgent), "AbstractAgent " + GetName() + " End @ " + Scheduler.GetTime());
                    SimulationEndNotification();
                    //CancelAllOpenOrders();
                    _sim = null;
                }
            }
        }
Exemplo n.º 10
0
        // constructor
        protected AbstractAgent(IBlauPoint coordinates, IAgentFactory creator, int id, double burnin)
        {
            _coordinates = coordinates;
            _creator     = creator;
            _burnin      = burnin;

            // implicit assignment, allocates the ID dynamically
            if (id < 0)
            {
                // dynamic assignment
                _id = _nextID;
                _nextID++;
            }
            else
            {
                // explicit assignment (used in cloning, for example)
                _id = id;
            }

            // the ecosystem, initially null
            _sim = null;

            // the metrics associated with this Agent
            _metrics = new Dictionary <string, double>();

            // the list of open orders
            _orders = new List <IOrder>();

            // basic stats that every Agent maintains
            SetMetricValue(NumBids_METRICNAME, 0.0);
            SetMetricValue(NumAsks_METRICNAME, 0.0);
            SetMetricValue(Holdings_METRICNAME, 0.0);

            // boot message
            this.Send(this, new ActionPrompt(), GetTimeToNextActionPrompt());
            if (LoggerDiags.Enabled)
            {
                SingletonLogger.Instance().InfoLog(typeof(AbstractAgent), "AbstractAgent " + GetName() + " Constructed @ " + Scheduler.GetTime());
            }
        }
Exemplo n.º 11
0
 // delegate signals from the Simulation to appropriate agents
 public void recvSimulationNotification(ISimulationParameters sim, ISimulationEvent se)
 {
     if (se.OrderbookEvent == null)
     {
         // start and end events go to all agents
         if (se is ISimulationStart)
         {
             foreach (IAgent ag in _agents)
             {
                 ag.recvSimulationNotification(sim, se);
             }
         }
         else if (se is ISimulationEnd)
         {
             foreach (IAgent ag in _agents)
             {
                 ag.recvSimulationNotification(sim, se);
             }
         }
     }
     else
     {
         // fill events go to the order owner only
         if (se.OrderbookEvent is IOrderbookEvent_FillOrder)
         {
             IOrderbookEvent_FillOrder fillEvent = (IOrderbookEvent_FillOrder)se.OrderbookEvent;
             IOrderOwner owner = fillEvent.getOrder().getOwner();
             if (_agents.Contains((IAgent)owner))
             {
                 owner.recvOrderNotification(sim.Orderbook, fillEvent);
             }
             else
             {
                 throw new Exception("Population is attempting to forward signal to an unrecognized IAgent");
             }
         }
         // Add and Cancel events are ignored by the Population class
     }
 }
Exemplo n.º 12
0
 public IEnumerable <Individual> EvaluatePopulation(IEnumerable <Individual> population, ISimulationParameters simulationParams)
 {
     return(population.Select(s => EvaluateIndividual(s, simulationParams)));
 }
 public HashingFilenameGenerator(ILogger logger, ISimulationParameters simulationParameters)
 {
     _simulationParameters = simulationParameters;
     _logger = logger;
 }
Exemplo n.º 14
0
 public void reset(ISimulationParameters sim)
 {
     _trajectory = new Trajectory(this.Name, TemporalGranularityThreshold, _historicalBias, _burnin);
     _sim        = sim;
 }