Files
quantconnect--lean/Queues/JobQueue.cs
Adalyat Nazirov a4f66628fd Lean Optimization interface in QCAlgorithm (#4923)
* initial commit

* run parametrized algorithm with command line parameters

* skeleton: top level structure

* OptimizationNodePacket scheme

* pass parameters as HashSet

* run Lean and read results

* call method on optimization completion

* refactor public interfaces

- close ParameterSet collection; allow only get operations
- explicit method to start LeanOptimizer

* synchronize RunLean method; the result could come in before the backtest id is set in the collections

* another portion of refactoring and interface changes

* comments

* comments & tests for Extremum, Minimization and Maximization classes

* unify optimization paramater values (min, max, step) & mode GridSearch tests

- swap min&max if necessary
- iterate left => right (negate step value if necessary) & provide default step value if step == 0
- no StackOverflow Exception
- parameterSet Id should be global for current generator and retain between steps
- test signle point boundary (min == max)

* BruteForceStrategy tests

* more comments

* Update Optimizer assembly information

- Update Optimizer projects assembly information to match behavior of
  the other projects

* Tweaks

- Adding comments
- Replace OnComplete for Ended event
- Replace Abort for Dispose
- ConsoleLeanOptimizer will keep track of running processes
- Each backtest will store results in a separated directory, so they
  don't fight for the log.txt file.
- Adding cmdline option for lean to close automatically
- Adding concurrent execution backtest limit
- Console optimizer will start Lean minimized
- Escape spaces in Json path

* remove parameter set generator abstraction layer

we don't need this flexibility now.

* refactor public methods; Step shouldn't be public

* constraints: wip

* define contract

* comparison operators and tests

* specify JsonProperty values

* Move SafeMultiply100 to extensions

* Throw exception on failed Optimizer.Start

* constraints: wip

* change finish & dispose process

* minor fixes

- handle force lean abort
- notify consumer if target has been reached

* target & constraints; adapt unit tests

* Minor Tweaks and fixes

- Some logging improvements
- Remove Public since not required

* Ignore empty ParameterValue

* simplify condition

* avoid reinitialization

* reduce type; force immutable

* unit tests for constraints  and target value

* parse & normalize percent values, i.e. 20% => 0.2

* fixup

* Target & Constraint & OptimizationNodePacket unit tests

* Add more json unit tests

- Adding more json conversion unit tests. Fix bug for Extremum which
  wasn't using the converter.

* LeanOptimizer tests

* Estimation results

* User thread safe counters

* LeanOptimizer unit tests; push OptimizationResult on Ended event

* more unit tests

* Minor tweaks

-Estimate ToString in a single line.
-Typos and missing header file

* Add base SendUpdate method

- Add base SendUpdate method for LeanOptimizer

* fix LeanOptimizer test; rely on internal Update rather than timer

* Add OptimizationStatus

- Add missing commments and OptimizationStatus

* EulerSearch implementation: wip

* OptimizationParameter custom converter

* change the type

* make step optional

* change folder structure

* enumerate optimization parameter using IEnumerable & IEnumerator

* unit tests: parameters & objectives

* unit tests: strategies

* remove redundant TODO

* change Euler search boundaries

* more Euler tests

* prevent race condition

* Add account/read endpoint

- Adding account/read endpoint. Adding unit test

* Add status check before running lean

* Minor self review

- Adding missing comments, minor changes

* remove array parameters

* minor changes

- tidy up config file, rename variable
- accept min less or equal than max

* move OptimizationParameter methods to strategies

* Minor improvements for BaseResultHandler derivates

* minor changes

- strict requirements for Step and MinStep values
- strategy specific settigs

* Add TotalRuntime to estimate

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>
2020-12-02 20:10:40 -03:00

206 lines
8.5 KiB
C#

/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using QuantConnect.Python;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.Util;
namespace QuantConnect.Queues
{
/// <summary>
/// Implementation of local/desktop job request:
/// </summary>
public class JobQueue : IJobQueueHandler
{
// The type name of the QuantConnect.Brokerages.Paper.PaperBrokerage
private static readonly TextWriter Console = System.Console.Out;
private const string PaperBrokerageTypeName = "PaperBrokerage";
private const string DefaultHistoryProvider = "SubscriptionDataReaderHistoryProvider";
private const string DefaultDataQueueHandler = "LiveDataQueue";
private const string DefaultDataChannelProvider = "DataChannelProvider";
private bool _liveMode = Config.GetBool("live-mode");
private static readonly string AccessToken = Config.Get("api-access-token");
private static readonly int UserId = Config.GetInt("job-user-id", 0);
private static readonly int ProjectId = Config.GetInt("job-project-id", 0);
private readonly string AlgorithmTypeName = Config.Get("algorithm-type-name");
private readonly Language Language = (Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language"));
/// <summary>
/// Physical location of Algorithm DLL.
/// </summary>
private string AlgorithmLocation
{
get
{
// we expect this dll to be copied into the output directory
return Config.Get("algorithm-location", "QuantConnect.Algorithm.CSharp.dll");
}
}
/// <summary>
/// Initialize the job queue:
/// </summary>
public void Initialize(IApi api)
{
//
}
/// <summary>
/// Desktop/Local Get Next Task - Get task from the Algorithm folder of VS Solution.
/// </summary>
/// <returns></returns>
public AlgorithmNodePacket NextJob(out string location)
{
location = GetAlgorithmLocation();
Log.Trace($"JobQueue.NextJob(): Selected {location}");
// check for parameters in the config
var parameters = new Dictionary<string, string>();
var parametersConfigString = Config.Get("parameters");
if (parametersConfigString != string.Empty)
{
parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersConfigString);
}
var controls = new Controls()
{
MinuteLimit = Config.GetInt("symbol-minute-limit", 10000),
SecondLimit = Config.GetInt("symbol-second-limit", 10000),
TickLimit = Config.GetInt("symbol-tick-limit", 10000),
RamAllocation = int.MaxValue,
MaximumDataPointsPerChartSeries = Config.GetInt("maximum-data-points-per-chart-series", 4000)
};
if ((Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language")) == Language.Python)
{
// Set the python path for loading python algorithms ("algorithm-location" config parameter)
var pythonFile = new FileInfo(location);
// PythonInitializer automatically adds the current working directory for us
PythonInitializer.SetPythonPathEnvironmentVariable(new string[] { pythonFile.Directory.FullName });
}
var algorithmId = Config.Get("algorithm-id", AlgorithmTypeName);
//If this isn't a backtesting mode/request, attempt a live job.
if (_liveMode)
{
var liveJob = new LiveNodePacket
{
Type = PacketType.LiveNode,
Algorithm = File.ReadAllBytes(AlgorithmLocation),
Brokerage = Config.Get("live-mode-brokerage", PaperBrokerageTypeName),
HistoryProvider = Config.Get("history-provider", DefaultHistoryProvider),
DataQueueHandler = Config.Get("data-queue-handler", DefaultDataQueueHandler),
DataChannelProvider = Config.Get("data-channel-provider", DefaultDataChannelProvider),
Channel = AccessToken,
UserToken = AccessToken,
UserId = UserId,
ProjectId = ProjectId,
Version = Globals.Version,
DeployId = algorithmId,
Parameters = parameters,
Language = Language,
Controls = controls
};
try
{
// import the brokerage data for the configured brokerage
var brokerageFactory = Composer.Instance.Single<IBrokerageFactory>(factory => factory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
liveJob.BrokerageData = brokerageFactory.BrokerageData;
}
catch (Exception err)
{
Log.Error(err, $"Error resolving BrokerageData for live job for brokerage {liveJob.Brokerage}");
}
return liveJob;
}
//Default run a backtesting job.
var backtestJob = new BacktestNodePacket(0, 0, "", new byte[] {}, "local")
{
Type = PacketType.BacktestNode,
Algorithm = File.ReadAllBytes(AlgorithmLocation),
HistoryProvider = Config.Get("history-provider", DefaultHistoryProvider),
Channel = AccessToken,
UserToken = AccessToken,
UserId = UserId,
ProjectId = ProjectId,
Version = Globals.Version,
BacktestId = algorithmId,
Language = Language,
Parameters = parameters,
Controls = controls
};
return backtestJob;
}
/// <summary>
/// Get the algorithm location for client side backtests.
/// </summary>
/// <returns></returns>
private string GetAlgorithmLocation()
{
if (Language == Language.Python)
{
var pythonSource = AlgorithmTypeName + ".py";
if (!File.Exists(pythonSource))
{
// Copies file to execution location
foreach (var file in new DirectoryInfo(Path.GetDirectoryName(AlgorithmLocation)).GetFiles("*.py"))
{
file.CopyTo(file.FullName.Replace(file.DirectoryName, Environment.CurrentDirectory), true);
}
if (!File.Exists(pythonSource))
{
throw new FileNotFoundException($"JobQueue.TryCreatePythonAlgorithm(): Unable to find py file: {pythonSource}");
}
}
}
return AlgorithmLocation;
}
/// <summary>
/// Desktop/Local acknowledge the task processed. Nothing to do.
/// </summary>
/// <param name="job"></param>
public void AcknowledgeJob(AlgorithmNodePacket job)
{
// Make the console window pause so we can read log output before exiting and killing the application completely
Console.WriteLine("Engine.Main(): Analysis Complete.");
// closing automatically is useful for optimization, we don't want to leave open all the ended lean instances
if (!Config.GetBool("close-automatically"))
{
Console.WriteLine("Engine.Main(): Press any key to continue.");
System.Console.Read();
}
}
}
}