17 using System.Collections.Generic;
18 using System.Globalization;
21 using Newtonsoft.Json;
22 using Newtonsoft.Json.Linq;
24 using static System.FormattableString;
34 private static string ConfigurationFileName =
"config.json";
42 if (File.Exists(fileName))
44 Log.
Trace(Invariant($
"Using {fileName} as configuration file"));
45 ConfigurationFileName = fileName;
49 Log.
Error(Invariant($
"Configuration file {fileName} does not exist, using {ConfigurationFileName}"));
59 if (cliArguments.ContainsKey(
"config"))
65 var jsonArguments = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(cliArguments));
67 Settings.Value.Merge(jsonArguments,
new JsonMergeSettings
69 MergeArrayHandling = MergeArrayHandling.Union
80 Settings =
new Lazy<JObject>(ConfigFactory);
83 private static Lazy<JObject> Settings =
new Lazy<JObject>(ConfigFactory);
85 private static JObject ConfigFactory()
88 if (!File.Exists(ConfigurationFileName))
92 {
"algorithm-type-name",
"BasicTemplateAlgorithm"},
94 {
"data-folder",
"../../../Data/"},
95 {
"messaging-handler",
"QuantConnect.Messaging.Messaging"},
96 {
"job-queue-handler",
"QuantConnect.Queues.JobQueue"},
97 {
"api-handler",
"QuantConnect.Api.Api"},
98 {
"setup-handler",
"QuantConnect.Lean.Engine.Setup.ConsoleSetupHandler"},
99 {
"result-handler",
"QuantConnect.Lean.Engine.Results.BacktestingResultHandler"},
100 {
"data-feed-handler",
"QuantConnect.Lean.Engine.DataFeeds.FileSystemDataFeed"},
101 {
"real-time-handler",
"QuantConnect.Lean.Engine.RealTime.BacktestingRealTimeHandler"},
102 {
"transaction-handler",
"QuantConnect.Lean.Engine.TransactionHandlers.BacktestingTransactionHandler"}
106 return JObject.Parse(
File.ReadAllText(ConfigurationFileName));
116 var environments =
new List<string>();
117 JToken currentEnvironment = Settings.Value;
118 var env = currentEnvironment[
"environment"];
119 while (currentEnvironment !=
null && env !=
null)
121 var currentEnv = env.Value<
string>();
122 environments.Add(currentEnv);
123 var moreEnvironments = currentEnvironment[
"environments"];
124 if (moreEnvironments ==
null)
129 currentEnvironment = moreEnvironments[currentEnv];
130 env = currentEnvironment[
"environment"];
132 return string.Join(
".", environments);
141 public static string Get(
string key,
string defaultValue =
"")
146 var token =
GetToken(Settings.Value, key);
149 Log.
Trace(Invariant($
"Config.Get(): Configuration key not found. Key: {key} - Using default value: {defaultValue}"));
152 return token.ToString();
160 return GetToken(Settings.Value, key);
169 public static void Set(
string key, dynamic value)
171 JToken environment = Settings.Value;
172 while (key.Contains(
'.', StringComparison.InvariantCulture))
174 var envName = key.Substring(0, key.IndexOf(
".", StringComparison.InvariantCulture));
175 key = key.Substring(key.IndexOf(
".", StringComparison.InvariantCulture) + 1);
176 var environments = environment[
"environments"];
177 if (environments ==
null)
179 environment[
"environments"] = environments =
new JObject();
181 environment = environments[envName];
183 environment[key] = value;
192 public static bool GetBool(
string key,
bool defaultValue =
false)
194 return GetValue(key, defaultValue);
203 public static int GetInt(
string key,
int defaultValue = 0)
205 return GetValue(key, defaultValue);
214 public static double GetDouble(
string key,
double defaultValue = 0.0)
216 return GetValue(key, defaultValue);
227 public static T
GetValue<T>(
string key, T defaultValue =
default(T))
230 if (key ==
"environment" && typeof (T) == typeof (
string))
return (T) (object)
GetEnvironment();
232 var token =
GetToken(Settings.Value, key);
235 var defaultValueString = defaultValue is IConvertible
236 ? ((IConvertible) defaultValue).ToString(CultureInfo.InvariantCulture)
237 : defaultValue is IFormattable
238 ? ((IFormattable) defaultValue).ToString(
null, CultureInfo.InvariantCulture)
239 : Invariant($
"{defaultValue}");
241 Log.
Trace(Invariant($
"Config.GetValue(): {key} - Using default value: {defaultValueString}"));
245 var type = typeof(T);
249 value = token.Value<
string>();
253 value = token.ToString();
258 return (T) Enum.Parse(type, value,
true);
261 if (typeof(IConvertible).IsAssignableFrom(type))
263 return (T) Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
269 var parse = type.GetMethod(
"Parse",
new[]{typeof(
string)});
272 var result = parse.Invoke(
null,
new object[] {value});
276 catch (Exception err)
278 Log.
Trace(Invariant($
"Config.GetValue<{typeof(T).Name}>({key},{defaultValue}): Failed to parse: {value}. Using default value."));
285 return JsonConvert.DeserializeObject<T>(value);
287 catch (Exception err)
289 Log.
Trace(Invariant($
"Config.GetValue<{typeof(T).Name}>({key},{defaultValue}): Failed to JSON deserialize: {value}. Using default value."));
305 return TryGetValue(key,
default(T), out value);
321 value = GetValue(key, defaultValue);
326 value = defaultValue;
334 public static void Write(
string targetPath =
null)
336 if (!Settings.IsValueCreated)
return;
337 var serialized = JsonConvert.SerializeObject(Settings.Value, Formatting.Indented);
339 var taget = ConfigurationFileName;
340 if (!
string.IsNullOrEmpty(targetPath))
342 taget = Path.Combine(targetPath, ConfigurationFileName);
344 File.WriteAllText(taget, serialized);
353 public static JObject
Flatten(
string overrideEnvironment)
355 return Flatten(Settings.Value, overrideEnvironment);
365 public static JObject
Flatten(JObject config,
string overrideEnvironment)
367 var clone = (JObject)config.DeepClone();
370 var environmentProperty = clone.Property(
"environment");
371 if (environmentProperty !=
null) environmentProperty.Remove();
373 if (!
string.IsNullOrEmpty(overrideEnvironment))
375 var environmentSections = overrideEnvironment.Split(
'.');
377 for (
int i = 0; i < environmentSections.Length; i++)
379 var env =
string.Join(
".environments.", environmentSections.Where((x, j) => j <= i));
381 var environments = config[
"environments"];
382 if (!(environments is JObject))
continue;
384 var settings = ((JObject) environments).SelectToken(env);
385 if (settings ==
null)
continue;
388 foreach (var token
in settings)
390 var path = Path.GetExtension(token.Path);
391 var dot = path.IndexOf(
".", StringComparison.InvariantCulture);
392 if (dot != -1) path = path.Substring(dot + 1);
395 var jProperty = clone.Property(path);
396 if (jProperty !=
null) jProperty.Remove();
398 var value = (token is JProperty ? ((JProperty) token).Value : token).ToString();
399 clone.Add(path, value);
405 var environmentsProperty = clone.Property(
"environments");
406 environmentsProperty?.Remove();
411 private static JToken
GetToken(JToken settings,
string key)
413 return GetToken(settings, key, settings.SelectToken(key));
416 private static JToken
GetToken(JToken settings,
string key, JToken current)
418 var environmentSetting = settings.SelectToken(
"environment");
419 if (environmentSetting !=
null)
421 var environmentSettingValue = environmentSetting.Value<
string>();
422 if (!
string.IsNullOrWhiteSpace(environmentSettingValue))
424 var environment = settings.SelectToken(
"environments." + environmentSettingValue);
425 if (environment !=
null)
427 var setting = environment.SelectToken(key);
433 return GetToken(environment, key, current);
439 return settings.SelectToken(key);