Beispiel #1
0
        /// <summary>
        /// Updates available projects in the combo box
        /// </summary>
        public async void UpdateAvailableProjects(bool showLoginDialog = true)
        {
            VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Loading available projects...");
            if (await _authenticationCommand.Login(ServiceProvider.GlobalProvider, false, showLoginDialog))
            {
                try
                {
                    var projectNames = await System.Threading.Tasks.Task.Run(() =>
                    {
                        var api      = AuthorizationManager.GetInstance().GetApi();
                        var projects = api.ListProjects().Projects;
                        return(projects.Select(p => Tuple.Create(p.ProjectId, p.Name)).ToList());
                    });

                    // Clear available projects
                    projectNameBox.Items.Clear();
                    // Clear rows in the backtest data grid
                    _dataGridCollection.Clear();
                    if (projectNames.Count > 0)
                    {
                        projectNames.ForEach(p => projectNameBox.Items.Add(new ProjectNameDialog.ComboboxItem(p.Item1, p.Item2)));
                        VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Successfully loaded projects");
                    }
                    else
                    {
                        VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "No projects available");
                    }
                }
                catch (Exception exception)
                {
                    VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                                "QuantConnect Exception", exception.ToString());
                }
            }
        }
Beispiel #2
0
        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            VSActivityLog.Info("Login button clicked");
            try
            {
                // Disable textbox passwordBox and login button
                userIdBox.IsReadOnly     = true;
                accessTokenBox.IsEnabled = false;
                logInButton.IsEnabled    = false;

                var userId      = userIdBox.Text;
                var accessToken = accessTokenBox.Password;
                var credentials = new Credentials(userId, accessToken);
                if (await _authorizationManager.Login(credentials))
                {
                    VSActivityLog.Info("Logged in successfully");
                    VsUtils.DisplayInStatusBar(_serviceProvider, "Logged into QuantConnect");
                    _credentials = new Credentials(userId, accessToken);
                    Close();
                    return;
                }
            }
            catch (Exception exception)
            {
                VsUtils.ShowErrorMessageBox(_serviceProvider, "QuantConnect Login Exception", exception.ToString());
                VSActivityLog.Error(exception.ToString());
            }
            VsUtils.DisplayInStatusBar(_serviceProvider, "Failed to login");
            userIdBox.BorderBrush      = Brushes.Red;
            accessTokenBox.BorderBrush = Brushes.Red;
            // Re enable button and textbox
            userIdBox.IsReadOnly     = false;
            accessTokenBox.IsEnabled = true;
            logInButton.IsEnabled    = true;
        }
Beispiel #3
0
        /// <summary>
        /// Callback for the delete button in the backtest data grid, shared by all rows. Deletes backtest.
        /// </summary>
        private async void Delete_OnClick(object sender, RoutedEventArgs e)
        {
            var obj = ((FrameworkElement)sender).DataContext as DataGridItem;

            if (obj != null)
            {
                var projectId  = obj.ProjectId;
                var backtestId = obj.BacktestId;
                VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Deleting backtest...");
                var deleteResult = false;
                if (await _authenticationCommand.Login(ServiceProvider.GlobalProvider, false))
                {
                    try
                    {
                        deleteResult = await System.Threading.Tasks.Task.Run(() =>
                        {
                            var api = AuthorizationManager.GetInstance().GetApi();
                            return(api.DeleteBacktest(projectId, backtestId).Success);
                        });
                    }
                    catch (Exception exception)
                    {
                        VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                                    "QuantConnect Exception", exception.ToString());
                    }
                }
                if (deleteResult)
                {
                    var selectedItem = projectNameBox.SelectedItem as ComboboxProjectItem;
                    // Verify the backtest is from the selected project
                    if (selectedItem?.Id == projectId)
                    {
                        lock (_dataGridCollection)
                        {
                            foreach (DataGridItem item in _dataGridCollection)
                            {
                                if (item.BacktestId == backtestId)
                                {
                                    _dataGridCollection.Remove(item);
                                    break;
                                }
                            }
                        }
                    }
                    VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Successfully deleted backtest");
                }
                else
                {
                    VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Error when deleting backtest");
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Uploads a list of files to a specific project at QuantConnect
        /// </summary>
        /// <param name="selectedProjectId">Target project Id</param>
        /// <param name="files">List of files to upload</param>
        /// <returns>Returns false if any file failed to be uploaded</returns>
        private bool UploadFilesToServer(int selectedProjectId, IEnumerable <SelectedItem> files)
        {
            VsUtils.DisplayInStatusBar(_serviceProvider, "Uploading files to server...");
            var api = AuthorizationManager.GetInstance().GetApi();
            // Counters to keep track of files uploaded or not
            var filesUploaded    = 0;
            var filesNotUploaded = 0;

            foreach (var file in files)
            {
                api.DeleteProjectFile(selectedProjectId, file.FileName);
                try
                {
                    var fileContent = File.ReadAllText(file.FilePath);
                    var response    = api.AddProjectFile(selectedProjectId, file.FileName, fileContent);
                    if (response.Success)
                    {
                        filesUploaded++;
                    }
                    else
                    {
                        VSActivityLog.Error("Failed to add project file " + file.FileName);
                        filesNotUploaded++;
                    }
                }
                catch (Exception exception)
                {
                    VSActivityLog.Error("Exception adding project file " + file.FileName + ". Exception " + exception);
                    filesNotUploaded++;
                }
            }
            // Update Status bar accordingly based on counters
            var message = "Files upload complete";

            message += (filesUploaded != 0) ? ". Uploaded " + filesUploaded : "";
            message += (filesNotUploaded != 0) ? ". Failed to upload " + filesNotUploaded : "";
            VsUtils.DisplayInStatusBar(_serviceProvider, message);

            // Return false if any file failed to be uploaded
            var result = filesNotUploaded == 0;

            if (!result)
            {
                VsUtils.ShowErrorMessageBox(_serviceProvider, "Upload Files Failed", message);
            }
            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// Updates available backtests in the backtest data grid for a specific project
        /// </summary>
        /// <param name="projectId">Target project id</param>
        private async void UpdateAvailableBacktests(int projectId)
        {
            VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Loading project backtests...");
            if (await _authenticationCommand.Login(ServiceProvider.GlobalProvider, false))
            {
                try
                {
                    var backtestsList = await System.Threading.Tasks.Task.Run(() =>
                    {
                        var api    = AuthorizationManager.GetInstance().GetApi();
                        var result = api.ListBacktests(projectId);
                        return(result.Backtests);
                    });

                    var selectedItem = projectNameBox.SelectedItem as ComboboxProjectItem;
                    // Verify the backtest are from the selected project
                    if (selectedItem?.Id == projectId)
                    {
                        lock (_dataGridCollection)
                        {
                            _dataGridCollection.Clear();
                            // Setting a limit of _maximumBacktestToShow backtests in the table...
                            for (var i = 0; i < backtestsList.Count && i < _maximumBacktestToShow; i++)
                            {
                                _dataGridCollection.Add(new DataGridItem
                                {
                                    Name       = backtestsList[i].Name,
                                    Progress   = backtestsList[i].Progress,
                                    ProjectId  = projectId,
                                    Date       = backtestsList[i].Created,
                                    BacktestId = backtestsList[i].BacktestId,
                                    Status     = string.IsNullOrEmpty(backtestsList[i].Error) ?
                                                 DataGridItem.BacktestSucceeded : DataGridItem.BacktestFailed,
                                    Note = backtestsList[i].Note
                                });
                            }
                        }
                        VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Successfully loaded backtests");
                    }
                }
                catch (Exception exception)
                {
                    VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                                "QuantConnect Exception", exception.ToString());
                }
            }
        }
Beispiel #6
0
 private void SaveToQuantConnectCallback(object sender, EventArgs e)
 {
     try
     {
         ExecuteOnProjectAsync(sender, (selectedProjectId, selectedProjectName, files) =>
         {
             System.Threading.Tasks.Task.Factory.StartNew(() =>
             {
                 UploadFilesToServer(selectedProjectId, files);
             }, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
         });
     }
     catch (Exception exception)
     {
         VsUtils.ShowErrorMessageBox(_serviceProvider, "QuantConnect Exception", exception.ToString());
     }
 }
Beispiel #7
0
        /// <summary>
        /// Callback for the edit button. Will show a new popup so the user can edit backtest name and note.
        /// Will update the server through API.
        /// </summary>
        private async void Edit_OnClick(object sender, RoutedEventArgs e)
        {
            var obj = ((FrameworkElement)sender).DataContext as DataGridItem;

            if (obj != null)
            {
                var projectId    = obj.ProjectId;
                var backtestId   = obj.BacktestId;
                var backtestNote = obj.Note;
                var window       = new EditBacktestDialog(obj.Name, backtestNote);
                VsUtils.DisplayDialogWindow(window);
                if (window.BacktestNameProvided &&
                    !string.IsNullOrEmpty(window.BacktestName) &&
                    await _authenticationCommand.Login(ServiceProvider.GlobalProvider, false))
                {
                    var result = false;
                    try
                    {
                        result = await System.Threading.Tasks.Task.Run(() =>
                        {
                            var api = AuthorizationManager.GetInstance().GetApi();
                            return(api.UpdateBacktest(projectId, backtestId, window.BacktestName, window.BacktestNote).Success);
                        });
                    }
                    catch (Exception exception)
                    {
                        VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                                    "QuantConnect Exception", exception.ToString());
                    }
                    if (result)
                    {
                        // lets update the data grid without having to go to the server again
                        obj.Name = window.BacktestName;
                        obj.Note = window.BacktestNote;
                        VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Successfully edited backtest");
                    }
                    else
                    {
                        VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Failed to edit backtest");
                    }
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Callback for the new project button. Will show a new popup so the user can select name and language
        /// Will create project calling the server through API.
        /// </summary>
        private async void NewProjectButton_OnClick(object sender, RoutedEventArgs e)
        {
            var window = new NewProjectDialog();

            VsUtils.DisplayDialogWindow(window);
            if (window.CreateNewProject &&
                await _authenticationCommand.Login(ServiceProvider.GlobalProvider, false))
            {
                var result    = false;
                var projectId = 0;
                try
                {
                    var apiResponse = await System.Threading.Tasks.Task.Run(() =>
                    {
                        var api = AuthorizationManager.GetInstance().GetApi();
                        return(api.CreateProject(window.NewProjectName, window.NewProjectLanguage));
                    });

                    if (apiResponse.Success && apiResponse.Projects.Count > 0)
                    {
                        result    = true;
                        projectId = apiResponse.Projects.First().ProjectId;
                    }
                }
                catch (Exception exception)
                {
                    VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                                "QuantConnect Exception", exception.ToString());
                }
                if (result)
                {
                    // lets update the combo box without having to go to the server again
                    var newProject = new ComboboxProjectItem(projectId, window.NewProjectName, window.NewProjectLanguage);
                    projectNameBox.Items.Add(newProject);
                    projectNameBox.SelectedItem = newProject;
                    VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Successfully created a new project");
                }
                else
                {
                    VsUtils.DisplayInStatusBar(ServiceProvider.GlobalProvider, "Failed to create a new project");
                }
            }
        }
        private void SendForBacktestingCallback(object sender, EventArgs e)
        {
            try
            {
                ExecuteOnProjectAsync(sender, async(selectedProjectId, selectedProjectName, files) =>
                {
                    var uploadResult = await System.Threading.Tasks.Task.Run(() =>
                                                                             UploadFilesToServer(selectedProjectId, files));
                    if (!uploadResult)
                    {
                        return;
                    }

                    var compilationResult = await CompileProjectOnServer(selectedProjectId);
                    if (!compilationResult.Item1)
                    {
                        var errorDialog = new ErrorDialog("Compilation Error", compilationResult.Item2);
                        VsUtils.DisplayDialogWindow(errorDialog);
                        return;
                    }

                    var backtestResult = await BacktestProjectOnServer(selectedProjectId, compilationResult.Item2);
                    if (!backtestResult.Item1)
                    {
                        var errorDialog = new ErrorDialog("Backtest Failed", backtestResult.Item2.Error);
                        VsUtils.DisplayDialogWindow(errorDialog);
                        return;
                    }

                    var projectUrl = string.Format(
                        CultureInfo.CurrentCulture,
                        "https://www.quantconnect.com/terminal/#open/{0}/{1}",
                        selectedProjectId,
                        backtestResult.Item2.BacktestId
                        );
                    Process.Start(projectUrl);
                });
            }
            catch (Exception exception)
            {
                VsUtils.ShowErrorMessageBox(_serviceProvider, "QuantConnect Exception", exception.ToString());
            }
        }
        /// <summary>
        /// Authenticate API
        /// </summary>
        /// <param name="credentials">User id and access token to authenticate the API</param>
        /// <returns>true if successfully authenticated API, false otherwise</returns>
        public async System.Threading.Tasks.Task <bool> Login(Credentials credentials)
        {
            VSActivityLog.Info("Authenticating QuantConnect API");
            try
            {
                var api = new Api.Api();
                api.Initialize(int.Parse(credentials.UserId), credentials.AccessToken, Globals.DataFolder);
                var apiConnected = await System.Threading.Tasks.Task.Run(() => api.Connected);

                if (apiConnected)
                {
                    _api = api;
                    return(true);
                }
            }
            catch (Exception exception)
            {
                VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                            "QuantConnect Exception", exception.ToString());
            }
            return(false);
        }