Esempio n. 1
1
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            m_Playing = true;
            m_Engine = new Engine.Engine();

            if (RadioButtonWebcam.IsChecked.Value)
            {
                m_Capture = new Capture(0);
                m_Capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 1280);
                m_Capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 720);
            }
            else
            {
                m_Capture = new Capture(System.IO.Path.GetFullPath(".\\..\\Videos\\vidD.mp4"));
            }

            m_Timer = new Timer(ExpectedFrameUpdate, null, 0, 1000 / 15);

            m_DisplayFrames = new Thread(ShowFrames);
            m_DisplayFrames.Start();
        }
Esempio n. 2
0
        public MainWindow()
        {
            InitializeComponent();

            _gameEngine = new Engine.Engine();

            _gameEngine.Game.Board.ItemMoved += RenderCanvas;

            foreach (var cell in _gameEngine.Game.Board.Rows.SelectMany(r => r))
            {
                var border = new Rectangle()
                {
                    Stroke          = new SolidColorBrush(Colors.Black),
                    StrokeThickness = 1,
                    Width           = unitSize,
                    Height          = unitSize
                };

                main.Children.Add(border);

                Canvas.SetLeft(border, cell.X * unitSize);
                Canvas.SetTop(border, cell.Y * unitSize);
            }

            base.KeyDown += OnKey;

            _gameEngine.Start();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var settings = e.Parameter as Domain.Settings;

            EngineSettings.Instance.ReadSettings(settings);
            _engine = MonoGame.Framework.XamlGame <Engine.Engine> .Create(string.Empty, Window.Current.CoreWindow, swapChainPanel);
        }
Esempio n. 4
0
        public static void Main(string[] args)
        {
            NLP_Lexer.Lexer nlpLexer = new NLP_Lexer.Lexer(ACCESS_TOKEN);

            // Test input
            string inp_a = "print add 4 and 5";

            string lex_chunk_a = nlpLexer.Tokenise(inp_a);

            Console.WriteLine("Input = \n\t" + inp_a);

            Console.WriteLine(lex_chunk_a);
            try
            {
                CoreParser.Lexer lexer = new CoreParser.Lexer(lex_chunk_a);
                lexer.Tokenise();
                List <Token>               tokens = lexer.getTokenList();
                CoreParser.Parser.Parser   parser = new CoreParser.Parser.Parser();
                CoreParser.Parser.AST.Node ast    = parser.Parse(tokens);
                Engine.Engine              engine = new Engine.Engine();
                engine.Run(ast);
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 5
0
        public CharacterSelection(Engine.Engine runner)
        {
            _runner = runner;
            _availableCharacters = new List <CharacterOverview>(new[] {
                new CharacterOverview
                {
                    Address = "Test1",
                    Funds   = (decimal)3.5,
                    Gold    = (decimal)0.1,
                    IsBound = true,
                    Level   = 1,
                    Name    = "Test Name",
                    Rating  = (decimal)3.5
                },
                new CharacterOverview
                {
                    Address = "Test2",
                    Funds   = (decimal)3.4515,
                    Gold    = (decimal)0.0,
                    IsBound = true,
                    Level   = 2,
                    Name    = "Test2 Name",
                    Rating  = (decimal)15.6
                }
            });
            _selectedCharacter = null;

            var fileMenu = new MenuEntry("File", "m_File", null);

            MainMenuEntries = new List <MenuEntry>(new[]
            {
                fileMenu,
                new MenuEntry("Character Selection", "m_CharSel", fileMenu, () => { IsVisible = !IsVisible; }, () => IsVisible, () => true),
            });
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            Engine.Engine engine = new Engine.Engine();
            engine.Start();

            Console.ReadKey();

            engine.Stop();
        }
Esempio n. 7
0
 static void Main()
 {
     if (Environment.OSVersion.Version.Major >= 6)
     {
         SetProcessDPIAware();
     }
     using (var engine = new Engine.Engine())
         engine.Run();
 }
Esempio n. 8
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            EngineSettings.Instance.ReadSettings(JsonConvert.DeserializeObject <PointCloudViewer.Domain.Settings>(Intent.GetStringExtra("Settings")));
            var engineInstance = new Engine.Engine();

            SetContentView((Android.Views.View)engineInstance.Services.GetService(typeof(Android.Views.View)));
            engineInstance.Run();
        }
Esempio n. 9
0
 public Bridge(Engine.Engine engine, FpsCounter fpsCounter)
 {
     State = new State
     {
         Projection = engine.GraphicsSettings.Projection,
         Fps        = fpsCounter.Fps,
         ClearColor = engine.GraphicsSettings.ClearColor
     };
 }
Esempio n. 10
0
        /// <summary>
        /// Overridden from the base Game.Initialize. Once the GraphicsDevice is setup,
        /// we'll use the viewport to initialize some values.
        /// </summary>
        protected override void Initialize()
        {
            engine = new Engine.Engine ();
            //pakmak = new Player.Player ();

            //map = new Map.Map (Constants.MAP_SIZE_HEIGHT, Constants.MAP_SIZE_WIDTH);
            playerMoveSpeed = Constants.PLAYER_MOVE_SPEED;

            base.Initialize ();
        }
Esempio n. 11
0
        public void Start(Engine.Engine runner)
        {
            _runner = runner;

            // Just to keep you waiting and show the loadscreen... :p
            Thread.Sleep(1000);

            _characterSelection = new CharacterSelection(_runner);
            _runner.GetSubSystem <Engine.Subsystems.Ui>().Windows.Add(_characterSelection);
        }
Esempio n. 12
0
        public void TryMakeMove_Finds_Promotion_Move(string promotionMove)
        {
            var mockLogger = new Mock <ILog>();
            var engine     = new Engine.Engine(mockLogger.Object);

            engine.SetBoard("8/8/8/8/8/K1k5/2p5/8 b - - 11 5");
            engine.TryMakeMove(promotionMove);

            VerifyNoErrorsOutput(mockLogger);
        }
Esempio n. 13
0
        public PauseForm(Engine.Engine engine, SaveManager manager, Integration.IMouse mouse, Engine.IDrawer drawer, IGameScene scene) : base(new Color(204, 153, 51), 150, null, mouse, drawer)
        {
            var list = new Box[] { new Box("Resume", Resume), new Box("Save", Save) };

            selectBox = new SelectBox(new Vector2(0, 20), list, drawer, mouse);
            controls.Add(selectBox);
            this.engine  = engine;
            this.manager = manager;
            SaveForm     = new SaveWorldForm(manager, this, mouse, drawer, scene);
        }
Esempio n. 14
0
        public void TryMakeMove_Finds_EnPassant_Move(string fen, string enpassantMove)
        {
            var mockLogger = new Mock <ILog>();
            var engine     = new Engine.Engine(mockLogger.Object);

            engine.SetBoard(fen);
            engine.TryMakeMove(enpassantMove);

            VerifyNoErrorsOutput(mockLogger);
        }
Esempio n. 15
0
        public Service1()
        {
            this.mEngine = new Engine.Engine();
            this.mEngine.Start();

            //mTimer = new Timer(OnTimer);
            //mMonitor = new ProgramMonitor();

            //mTimer.Change(1000, 1000);
            InitializeComponent();
        }
Esempio n. 16
0
        public override void Verify(Autodesk.Revit.DB.CodeChecking.ServiceData data)
        {
            Autodesk.Revit.DB.CodeChecking.Storage.StorageService  service         = Autodesk.Revit.DB.CodeChecking.Storage.StorageService.GetStorageService();
            Autodesk.Revit.DB.CodeChecking.Storage.StorageDocument storageDocument = service.GetStorageDocument(data.Document);


            Main.Calculation.EngineData enginData = new Main.Calculation.EngineData();
            Engine.Engine engine = new Engine.Engine(enginData);

            engine.Calculate(this, data);
        }
Esempio n. 17
0
 public ChessBoard()
 {
     IsWithPC   = false;
     engine     = new Engine.Engine();
     move       = new MoveCoord();
     IsPCMove   = false;
     isSelected = false;
     newFigure  = new Square(new NotFigur());
     InitializeComponent();
     NewChessBoard(true);
     IsInsert    = false;
     IsStartGame = false;
 }
Esempio n. 18
0
        private ChessEngine.Engine.Engine ReturnNewState(ChessEngine.Engine.Engine engine, byte piece, byte move)
        {
            ChessEngine.Engine.Engine newState = new Engine.Engine();
            newState.ChessBoard = new Board(engine.ChessBoard);
            byte[] sourcePos      = engine.CalculateColumnAndRow((byte)(piece));
            byte[] destinationPos = engine.CalculateColumnAndRow(move);

            if (!newState.MovePiece(sourcePos[0], sourcePos[1], destinationPos[0], destinationPos[1]))
            {
                return(null);
            }

            return(newState);
        }
Esempio n. 19
0
        /// <summary>
        /// Construct a game with an engine and two players
        /// </summary>
        /// <param name="engine">The engin the game will use</param>
        /// <param name="whitePlayer">White player</param>
        /// <param name="blackPlayer">Black player</param>
        /// <param name="container">Model container</param>
        public Game(Engine.Engine engine, Player whitePlayer, Player blackPlayer, Container container)
        {
            WhitePlayer = whitePlayer;
            BlackPlayer = blackPlayer;
            Engine      = engine;
            Container   = container;

            WhitePlayer.MoveDone += MoveHandler;
            BlackPlayer.MoveDone += MoveHandler;

            _currentPlayer = WhitePlayer;
            RaiseBoardState();
            // TODO : trouver une meilleure solution
            _currentPlayer.Play(null);
        }
Esempio n. 20
0
        public AIMove GetAIMove(Engine.Engine engine)
        {
            overTime = false;
            bestMove = new AIMove();
            timer.Reset();
            timer.Start();
            MaxValue(maxDepth, double.MinValue, double.MaxValue, engine);

            //No legal move was found
            if (bestMove.DestinationColumn == 0 && bestMove.DestinationRow == null && bestMove.SourceColumn == 0 && bestMove.SourceRow == null)
            {
                return(null);
            }

            return(bestMove);
        }
Esempio n. 21
0
        private void decodeButton_Click(object sender, EventArgs e)
        {
            String text = null;

            text = this.textBoxEmailHeader.Text;
            String mailType = this.comboBox1.Text;

            if (!text.Equals("") && !mailType.Equals(""))
            {
                engine             = new Engine.Engine(text, mailType);
                outputTextBox.Text = engine.engineOutput;
            }
            else
            {
                outputTextBox.Text = "";
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            var engine = new Engine.Engine();

            while (true)
            {
                Console.WriteLine("Input command: ");
                var command = Console.ReadLine()
                              .Trim()
                              .ToLower();

                if (command.Equals("end"))
                {
                    break;
                }

                try
                {
                    switch (command)
                    {
                    case "create":
                        var createData = ReadDataFromConsole();
                        engine.Create(createData);
                        break;

                    case "update":
                        var updateData = ReadDataFromConsole();
                        engine.Update(updateData);
                        break;

                    case "delete":
                        var eventName = ReadEventNameFromConsole();
                        engine.Delete(eventName);
                        break;

                    case "print all":
                        Console.WriteLine(engine.PrintAllEvents());
                        break;
                    }
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Esempio n. 23
0
        protected override Task <int> OnExecute(CommandLineApplication app)
        {
            var engineConfiguration = TryGetEngineConfigurationOrTerminate(repositoryPathOption.Value());
            var buildConfiguration  = TryGetBuildConfigurationOrTerminate(engineConfiguration.RepositoryDirectoryPath);

            var engine = new Engine.Engine(
                engineConfiguration,
                buildConfiguration);

            engineConfiguration.Outputter.Write("Available jobs:");
            for (var i = 0; i < engine.Jobs.Length; i++)
            {
                engineConfiguration.Outputter.Write(
                    $"[{i}]: {engine.Jobs[i].Name}");
            }

            return(Task.FromResult(0));
        }
        /// <summary>
        /// The main method of the Console UI of the game.
        /// </summary>
        public static void Main()
        {
            var printer = new Printer();

            var reader = new Reader();

            var gameInitializator = new GameInitializer.GameInitializer(printer, reader);

            var game = gameInitializator.Initialize();

            var scoreboard = new Scoreboard();

            var commandManager = new CommandManager();

            var boardHistory = new BoardHistory();

            EngineTemplate engine = new Engine.Engine(game, scoreboard, printer, reader, commandManager, boardHistory);

            engine.Run();
        }
Esempio n. 25
0
 public IEnumerable <ProcessingResult> Get()
 {
     //IEnumerable<ProcessingResult> retVal = new List<ProcessingResult>(1)
     //{
     //	new ProcessingResult()
     //	{
     //		IsAvg = true,
     //		Coordinates = new double[2] {45.239225 , 45.239225 },
     //		StreetNameNum = new string[2] {"Narodnog fronta", "25" },
     //		ValuesByHour = new float[24]
     //		{
     //				81 ,
     //				65 ,
     //				60 ,
     //				75 ,
     //				105 ,
     //				88 ,
     //				48 ,
     //				34 ,
     //				71 ,
     //				55 ,
     //				40 ,
     //				55 ,
     //				105 ,
     //				88 ,
     //				38 ,
     //				54 ,
     //				81 ,
     //				75 ,
     //				80 ,
     //				95 ,
     //				105 ,
     //				38 ,
     //				28 ,
     //				34
     //		}
     //	}
     //};
     Engine.Engine engine = new Engine.Engine();
     return(engine.GetProcessingResults());
 }
Esempio n. 26
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            m_Playing = true;
            m_Engine  = new Engine.Engine();

            if (RadioButtonWebcam.IsChecked.Value)
            {
                m_Capture = new Capture(0);
                m_Capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 1280);
                m_Capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 720);
            }
            else
            {
                m_Capture = new Capture(System.IO.Path.GetFullPath(".\\..\\Videos\\vidD.mp4"));
            }

            m_Timer = new Timer(ExpectedFrameUpdate, null, 0, 1000 / 15);

            m_DisplayFrames = new Thread(ShowFrames);
            m_DisplayFrames.Start();
        }
Esempio n. 27
0
        private void ButtonGo_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            m_Engine = new Engine.Engine();
            m_Engine.BoardImagePath = System.IO.Path.GetFullPath(".\\..\\Images\\MyBoards\\Board01.jpg");
            m_Engine.Process();

            sw.Stop();
            TextBlockTimeTaken.Text = sw.ElapsedMilliseconds.ToString() + "ms";

            OrigImage.Source = BitmapSourceConvert.ToBitmapSource(m_Engine.Board.BoardImage);
            OrigImageWithQuads.Source = BitmapSourceConvert.ToBitmapSource(m_Engine.Board.BoardImageWithBoxes);
            ShowPieceImage();
            //GrayImage.Source = BitmapSourceConvert.ToBitmapSource(engine.Board.GrayImage);
            //CannyImage.Source = BitmapSourceConvert.ToBitmapSource(engine.Board.CannyImage);
            //LinesImage.Source = BitmapSourceConvert.ToBitmapSource(engine.Board.LinesImage);
            WarpedImage.Source = BitmapSourceConvert.ToBitmapSource(m_Engine.Board.WarpedImage);
            WarpedCannyImage.Source = BitmapSourceConvert.ToBitmapSource(m_Engine.Board.WarpedCannyImage);
            WarpedLinesImage.Source = BitmapSourceConvert.ToBitmapSource(m_Engine.Board.WarpedLinesImage);
            GridBoxesImage.Source = BitmapSourceConvert.ToBitmapSource(m_Engine.Board.GridQuadsImage);
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var engine = new Engine.Engine();

            engine.Game.Board.ItemMoved += OnChange;

            engine.Start();

            while (true)
            {
                var key = Console.ReadKey();

                if (key.Key == ConsoleKey.Escape)
                {
                    break;
                }

                switch (key.Key)
                {
                case ConsoleKey.LeftArrow:
                    engine.Game.MoveActiveTetromino(Direction.Left);
                    break;

                case ConsoleKey.RightArrow:
                    engine.Game.MoveActiveTetromino(Direction.Right);
                    break;

                case ConsoleKey.UpArrow:
                    engine.Game.RotateActiveTetromino();
                    break;

                case ConsoleKey.DownArrow:
                    engine.Game.MoveActiveTetromino(Direction.Down);
                    break;
                }
            }
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            //Initialize:
            string mode = "RELEASE";
#if DEBUG
            mode = "DEBUG";
#endif
            if (Config.Get("environment") == "backtesting-desktop")
            {
                Application.EnableVisualStyles();
                Thread thread = new Thread(RunLeanEngineWinForm);
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join(); 
            }
            else
            {
                Log.LogHandler = Composer.Instance.GetExportedValueByTypeName<ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));

                var liveMode = Config.GetBool("live-mode");
                Log.DebuggingEnabled = Config.GetBool("debug-mode");
            //Name thread for the profiler:
            Thread.CurrentThread.Name = "Algorithm Analysis Thread";
            Log.Trace("Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v" + Globals.Version + " Mode: " + mode);
            Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString());
            Log.Trace("Engine.Main(): Memory " + OS.ApplicationMemoryUsed + "Mb-App  " + +OS.TotalPhysicalMemoryUsed + "Mb-Used  " + OS.TotalPhysicalMemory + "Mb-Total");

            //Import external libraries specific to physical server location (cloud/local)
            LeanEngineSystemHandlers leanEngineSystemHandlers;
            try
            {
                leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            //Setup packeting, queue and controls system: These don't do much locally.
            leanEngineSystemHandlers.Initialize();

            //-> Pull job from QuantConnect job queue, or, pull local build:
            string assemblyPath;
            var job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath);

            if (job == null)
            {
                throw new Exception("Engine.Main(): Job was null.");
            }

            LeanEngineAlgorithmHandlers leanEngineAlgorithmHandlers;
            try
            {
                leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            // log the job endpoints
            Log.Trace("JOB HANDLERS: ");
            Log.Trace("         DataFeed:     " + leanEngineAlgorithmHandlers.DataFeed.GetType().FullName);
            Log.Trace("         Setup:        " + leanEngineAlgorithmHandlers.Setup.GetType().FullName);
            Log.Trace("         RealTime:     " + leanEngineAlgorithmHandlers.RealTime.GetType().FullName);
            Log.Trace("         Results:      " + leanEngineAlgorithmHandlers.Results.GetType().FullName);
            Log.Trace("         Transactions: " + leanEngineAlgorithmHandlers.Transactions.GetType().FullName);
            Log.Trace("         History:      " + leanEngineAlgorithmHandlers.HistoryProvider.GetType().FullName);
            Log.Trace("         Commands:     " + leanEngineAlgorithmHandlers.CommandQueue.GetType().FullName);
            if (job is LiveNodePacket) Log.Trace("         Brokerage:    " + ((LiveNodePacket)job).Brokerage);

            // if the job version doesn't match this instance version then we can't process it
            // we also don't want to reprocess redelivered jobs
            if (VersionHelper.IsNotEqualVersion(job.Version) || job.Redelivered)
            {
                Log.Error("Engine.Run(): Job Version: " + job.Version + "  Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered);
                //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating.
                //In this event kill the old algorithm and leave a message so the user can later review.
                leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage);
                leanEngineSystemHandlers.Notify.SetAuthentication(job);
                leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.AlgorithmId, _collapseMessage));
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                return;
            }

            try
            {
                var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
                engine.Run(job, assemblyPath);
            }
            finally
            {
                //Delete the message from the job queue:
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId);

                // clean up resources
                leanEngineSystemHandlers.Dispose();
                leanEngineAlgorithmHandlers.Dispose();
                Log.LogHandler.Dispose();
            }
            }

        }
Esempio n. 30
0
        protected override Task <int> OnExecute(CommandLineApplication app)
        {
            var engineConfiguration = TryGetEngineConfigurationOrTerminate(_repositoryPathOption.Value());
            var buildConfiguration  = TryGetBuildConfigurationOrTerminate(engineConfiguration.RepositoryDirectoryPath);

            var engine = new Engine.Engine(
                engineConfiguration,
                buildConfiguration);

            engine.JobStarting += (sender, args) =>
            {
                Outputter.Write($"Starting '{args.Job.Name}'...");
            };

            engine.JobEnded += (sender, args) =>
            {
                switch (args.ExecutionResult.ResultType)
                {
                case JobExecutionResultType.Success:
                    Outputter.WriteSuccess($"Job '{args.Job.Name}' successfully executed.");
                    break;

                case JobExecutionResultType.Failure:
                    Outputter.WriteError($"Job '{args.Job.Name}' failed.");
                    break;

                case JobExecutionResultType.NotExecuted:
                    Outputter.WriteError($"Job '{args.Job.Name}' will not be executed.");
                    break;

                case JobExecutionResultType.JobNotFound:
                    Outputter.WriteError("Specified job index not found. Use 'jobs' command to list available jobs.");
                    break;

                case JobExecutionResultType.SolutionFileNotFound:
                    Outputter.WriteError("Solution was not found.");
                    break;

                case JobExecutionResultType.UnhandledException:
                    Outputter.WriteError($"Unhandled exception while executing '{args.Job.Name}': " +
                                         $"{args.ExecutionResult.UnhandledException.Message}");
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            };

            int[] jobs;

            try
            {
                jobs = _jobsIndexesOption
                       .Values
                       .Select(int.Parse)
                       .ToArray();
            }
            catch (Exception)
            {
                Outputter.WriteError("Job option receives a integer as input. Use 'jobs' command to list all available jobs.");
                return(Task.FromResult(1));
            }

            var jobsResults = new List <JobExecutionResult>();

            if (jobs.Length == 0)
            {
                jobsResults = engine.ExecuteAllJobs().ToList();
            }
            else
            {
                foreach (var jobIndex in jobs)
                {
                    jobsResults.Add(engine.ExecuteJob(jobIndex));
                }
            }

            PrintFinalResults(jobsResults);
            return(Task.FromResult(0));
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            //Initialize:
            var mode = "RELEASE";

            #if DEBUG
            mode = "DEBUG";
            #endif

            if (OS.IsWindows)
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;
            }

            // expect first argument to be config file name
            if (args.Length > 0)
            {
                Config.MergeCommandLineArgumentsWithConfiguration(LeanArgumentParser.ParseArguments(args));
            }

            var liveMode = Config.GetBool("live-mode");
            Log.DebuggingEnabled = Config.GetBool("debug-mode");
            Log.FilePath         = Path.Combine(Config.Get("results-destination-folder"), "log.txt");
            Log.LogHandler       = Composer.Instance.GetExportedValueByTypeName <ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));

            //Name thread for the profiler:
            Thread.CurrentThread.Name = "Algorithm Analysis Thread";
            Log.Trace($"Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v{Globals.Version} Mode: {mode} ({(Environment.Is64BitProcess ? "64" : "32")}bit) Host: {Environment.MachineName}");
            Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString());

            //Import external libraries specific to physical server location (cloud/local)

            try
            {
                leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            //Setup packeting, queue and controls system: These don't do much locally.
            leanEngineSystemHandlers.Initialize();

            //-> Pull job from QuantConnect job queue, or, pull local build:
            string assemblyPath;
            job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath);

            if (job == null)
            {
                const string jobNullMessage = "Engine.Main(): Sorry we could not process this algorithm request.";
                Log.Error(jobNullMessage);
                throw new ArgumentException(jobNullMessage);
            }

            try
            {
                leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            // if the job version doesn't match this instance version then we can't process it
            // we also don't want to reprocess redelivered jobs
            if (job.Redelivered)
            {
                Log.Error("Engine.Run(): Job Version: " + job.Version + "  Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered);
                //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating.
                //In this event kill the old algorithm and leave a message so the user can later review.
                leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage);
                leanEngineSystemHandlers.Notify.SetAuthentication(job);
                leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.UserId, job.AlgorithmId, _collapseMessage));
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                Exit(1);
            }

            try
            {
                // Set our exit handler for the algorithm
                Console.CancelKeyPress += new ConsoleCancelEventHandler(ExitKeyPress);

                // Create the algorithm manager and start our engine
                algorithmManager = new AlgorithmManager(liveMode, job);

                leanEngineSystemHandlers.LeanManager.Initialize(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, job, algorithmManager);

                var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
                engine.Run(job, algorithmManager, assemblyPath, WorkerThread.Instance);
            }
            finally
            {
                var algorithmStatus = algorithmManager?.State ?? AlgorithmStatus.DeployError;

                Exit(algorithmStatus != AlgorithmStatus.Completed ? 1 : 0);
            }
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            if (OS.IsWindows)
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;
            }

            // expect first argument to be config file name
            if (args.Length > 0)
            {
                Config.MergeCommandLineArgumentsWithConfiguration(LeanArgumentParser.ParseArguments(args));
            }

            var liveMode = Config.GetBool("live-mode");

            //Name thread for the profiler:
            Thread.CurrentThread.Name = "Algorithm Analysis Thread";

            Initializer.Start();
            leanEngineSystemHandlers = Initializer.GetSystemHandlers();

            //-> Pull job from QuantConnect job queue, or, pull local build:
            string assemblyPath;

            job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath);

            leanEngineAlgorithmHandlers = Initializer.GetAlgorithmHandlers();

            if (job == null)
            {
                const string jobNullMessage = "Engine.Main(): Sorry we could not process this algorithm request.";
                Log.Error(jobNullMessage);
                throw new ArgumentException(jobNullMessage);
            }

            // if the job version doesn't match this instance version then we can't process it
            // we also don't want to reprocess redelivered jobs
            if (job.Redelivered)
            {
                Log.Error("Engine.Run(): Job Version: " + job.Version + "  Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered);
                //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating.
                //In this event kill the old algorithm and leave a message so the user can later review.
                leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage);
                leanEngineSystemHandlers.Notify.SetAuthentication(job);
                leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.UserId, job.AlgorithmId, _collapseMessage));
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                Exit(1);
            }

            try
            {
                // Set our exit handler for the algorithm
                Console.CancelKeyPress += new ConsoleCancelEventHandler(ExitKeyPress);

                // Create the algorithm manager and start our engine
                algorithmManager = new AlgorithmManager(liveMode, job);

                leanEngineSystemHandlers.LeanManager.Initialize(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, job, algorithmManager);

                var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
                engine.Run(job, algorithmManager, assemblyPath, WorkerThread.Instance);
            }
            finally
            {
                var algorithmStatus = algorithmManager?.State ?? AlgorithmStatus.DeployError;

                Exit(algorithmStatus != AlgorithmStatus.Completed ? 1 : 0);
            }
        }
Esempio n. 33
0
 public TargetReachedEngineEventArgs(Engine.Engine engine, Entity reachedTarget, SetParentResult parentEnterResult) : base(engine)
 {
     ReachedTarget     = reachedTarget;
     ParentEnterResult = parentEnterResult;
 }
Esempio n. 34
0
        static void Main(string[] args)
        {
            Log.LogHandler = Composer.Instance.GetExportedValueByTypeName <ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));

            //Initialize:
            string mode     = "RELEASE";
            var    liveMode = Config.GetBool("live-mode");

            Log.DebuggingEnabled = Config.GetBool("debug-mode");

#if DEBUG
            mode = "DEBUG";
#endif

            //Name thread for the profiler:
            Thread.CurrentThread.Name = "Algorithm Analysis Thread";
            Log.Trace("Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v" + Constants.Version + " Mode: " + mode);
            Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString());
            Log.Trace("Engine.Main(): Memory " + OS.ApplicationMemoryUsed + "Mb-App  " + +OS.TotalPhysicalMemoryUsed + "Mb-Used  " + OS.TotalPhysicalMemory + "Mb-Total");

            //Import external libraries specific to physical server location (cloud/local)
            LeanEngineSystemHandlers leanEngineSystemHandlers;
            try
            {
                leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            //Setup packeting, queue and controls system: These don't do much locally.
            leanEngineSystemHandlers.Initialize();

            //-> Pull job from QuantConnect job queue, or, pull local build:
            string assemblyPath;
            var    job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath);

            if (job == null)
            {
                throw new Exception("Engine.Main(): Job was null.");
            }

            LeanEngineAlgorithmHandlers leanEngineAlgorithmHandlers;
            try
            {
                leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            // log the job endpoints
            Log.Trace("JOB HANDLERS: ");
            Log.Trace("         DataFeed:     " + leanEngineAlgorithmHandlers.DataFeed.GetType().FullName);
            Log.Trace("         Setup:        " + leanEngineAlgorithmHandlers.Setup.GetType().FullName);
            Log.Trace("         RealTime:     " + leanEngineAlgorithmHandlers.RealTime.GetType().FullName);
            Log.Trace("         Results:      " + leanEngineAlgorithmHandlers.Results.GetType().FullName);
            Log.Trace("         Transactions: " + leanEngineAlgorithmHandlers.Transactions.GetType().FullName);
            Log.Trace("         History:      " + leanEngineAlgorithmHandlers.HistoryProvider.GetType().FullName);
            Log.Trace("         Commands:     " + leanEngineAlgorithmHandlers.CommandQueue.GetType().FullName);
            if (job is LiveNodePacket)
            {
                Log.Trace("         Brokerage:    " + ((LiveNodePacket)job).Brokerage);
            }

            // if the job version doesn't match this instance version then we can't process it
            // we also don't want to reprocess redelivered jobs
            if (job.Version != Constants.Version || job.Redelivered)
            {
                Log.Error("Engine.Run(): Job Version: " + job.Version + "  Deployed Version: " + Constants.Version + " Redelivered: " + job.Redelivered);
                //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating.
                //In this event kill the old algorithm and leave a message so the user can later review.
                leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage);
                leanEngineSystemHandlers.Notify.SetChannel(job.Channel);
                leanEngineSystemHandlers.Notify.RuntimeError(job.AlgorithmId, _collapseMessage);
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                return;
            }

            try
            {
                var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
                engine.Run(job, assemblyPath);
            }
            finally
            {
                //Delete the message from the job queue:
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId);

                // clean up resources
                leanEngineSystemHandlers.Dispose();
                leanEngineAlgorithmHandlers.Dispose();
                Log.LogHandler.Dispose();
            }
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            var mode = "RELEASE";

            #if DEBUG
            mode = "DEBUG";
            #endif

            var environment = Config.Get("environment");
            var liveMode    = Config.GetBool("live-mode");
            Log.DebuggingEnabled = Config.GetBool("debug-mode");
            Log.LogHandler       = Composer.Instance.GetExportedValueByTypeName <ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));

            Thread.CurrentThread.Name = "Algorithm Analysis Thread";
            Log.Trace("Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v" + Globals.Version + " Mode: " + mode);
            Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString());
            Log.Trace("Engine.Main(): Memory " + OS.ApplicationMemoryUsed + "Mb-App  " + +OS.TotalPhysicalMemoryUsed + "Mb-Used  " + OS.TotalPhysicalMemory + "Mb-Total");

            LeanEngineSystemHandlers leanEngineSystemHandlers;
            try
            {
                leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            leanEngineSystemHandlers.Initialize();

            string assemblyPath;
            var    job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath);

            if (job == null)
            {
                throw new Exception("Engine.Main(): Job was null.");
            }

            LeanEngineAlgorithmHandlers leanEngineAlgorithmHandlers;
            try
            {
                leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            if (environment == "backtesting-desktop")
            {
                Application.EnableVisualStyles();
                var messagingHandler = leanEngineSystemHandlers.Notify;
                var thread           = new Thread(() => LaunchUX(messagingHandler, job));
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }

            Log.Trace("JOB HANDLERS: ");
            Log.Trace("         DataFeed:     " + leanEngineAlgorithmHandlers.DataFeed.GetType().FullName);
            Log.Trace("         Setup:        " + leanEngineAlgorithmHandlers.Setup.GetType().FullName);
            Log.Trace("         RealTime:     " + leanEngineAlgorithmHandlers.RealTime.GetType().FullName);
            Log.Trace("         Results:      " + leanEngineAlgorithmHandlers.Results.GetType().FullName);
            Log.Trace("         Transactions: " + leanEngineAlgorithmHandlers.Transactions.GetType().FullName);
            Log.Trace("         History:      " + leanEngineAlgorithmHandlers.HistoryProvider.GetType().FullName);
            Log.Trace("         Commands:     " + leanEngineAlgorithmHandlers.CommandQueue.GetType().FullName);
            if (job is LiveNodePacket)
            {
                Log.Trace("         Brokerage:    " + ((LiveNodePacket)job).Brokerage);
            }

            if (VersionHelper.IsNotEqualVersion(job.Version) || job.Redelivered)
            {
                Log.Error("Engine.Run(): Job Version: " + job.Version + "  Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered);
                leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage);
                leanEngineSystemHandlers.Notify.SetAuthentication(job);
                leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.AlgorithmId, _collapseMessage));
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                return;
            }

            try
            {
                var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
                engine.Run(job, assemblyPath);
            }
            finally
            {
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId);

                leanEngineSystemHandlers.Dispose();
                leanEngineAlgorithmHandlers.Dispose();
                Log.LogHandler.Dispose();
            }
        }
Esempio n. 36
0
        static void Main(string[] args)
        {
            //Initialize:
            var mode = "RELEASE";

            #if DEBUG
            mode = "DEBUG";
            #endif

            if (OS.IsWindows)
            {
                Console.OutputEncoding = System.Text.Encoding.Unicode;
            }

            var environment = Config.Get("environment");
            var liveMode    = Config.GetBool("live-mode");
            Log.DebuggingEnabled = Config.GetBool("debug-mode");
            Log.LogHandler       = Composer.Instance.GetExportedValueByTypeName <ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));

            //Name thread for the profiler:
            Thread.CurrentThread.Name = "Algorithm Analysis Thread";
            Log.Trace("Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v" + Globals.Version + " Mode: " + mode + " (" + (Environment.Is64BitProcess ? "64" : "32") + "bit)");
            Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString());
            Log.Trace("Engine.Main(): Memory " + OS.ApplicationMemoryUsed + "Mb-App  " + +OS.TotalPhysicalMemoryUsed + "Mb-Used  " + OS.TotalPhysicalMemory + "Mb-Total");

            //Import external libraries specific to physical server location (cloud/local)
            LeanEngineSystemHandlers leanEngineSystemHandlers;
            try
            {
                leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            //Setup packeting, queue and controls system: These don't do much locally.
            leanEngineSystemHandlers.Initialize();

            //-> Pull job from QuantConnect job queue, or, pull local build:
            string assemblyPath;
            var    job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath);

            if (job == null)
            {
                throw new Exception("Engine.Main(): Job was null.");
            }

            LeanEngineAlgorithmHandlers leanEngineAlgorithmHandlers;
            try
            {
                leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance);
            }
            catch (CompositionException compositionException)
            {
                Log.Error("Engine.Main(): Failed to load library: " + compositionException);
                throw;
            }

            if (environment.EndsWith("-desktop"))
            {
                var info = new ProcessStartInfo
                {
                    UseShellExecute = false,
                    FileName        = Config.Get("desktop-exe"),
                    Arguments       = Config.Get("desktop-http-port")
                };
                Process.Start(info);
            }

            // if the job version doesn't match this instance version then we can't process it
            // we also don't want to reprocess redelivered jobs
            if (VersionHelper.IsNotEqualVersion(job.Version) || job.Redelivered)
            {
                Log.Error("Engine.Run(): Job Version: " + job.Version + "  Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered);
                //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating.
                //In this event kill the old algorithm and leave a message so the user can later review.
                leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage);
                leanEngineSystemHandlers.Notify.SetAuthentication(job);
                leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.UserId, job.AlgorithmId, _collapseMessage));
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                return;
            }

            try
            {
                var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode);
                engine.Run(job, assemblyPath);
            }
            finally
            {
                //Delete the message from the job queue:
                leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job);
                Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId);

                // clean up resources
                leanEngineSystemHandlers.Dispose();
                leanEngineAlgorithmHandlers.Dispose();
                Log.LogHandler.Dispose();
            }
        }
Esempio n. 37
0
 public Screen(Engine.Engine engine) : base(null, engine.Width, engine.Height)
 {
 }