chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:02:50 +08:00
commit 0fc60fdcb1
5008 changed files with 910633 additions and 0 deletions
+103
View File
@@ -0,0 +1,103 @@
/*
* 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 QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command to add a security to the algorithm
/// </summary>
public class AddSecurityCommand : BaseCommand
{
/// <summary>
/// The security type of the security
/// </summary>
public SecurityType SecurityType { get; set; }
/// <summary>
/// The security's ticker symbol
/// </summary>
public string Symbol { get; set; }
/// <summary>
/// The requested resolution, defaults to Resolution.Minute
/// </summary>
public Resolution Resolution { get; set; }
/// <summary>
/// The security's market, defaults to <see cref="QuantConnect.Market.USA"/> except for Forex, defaults to <see cref="QuantConnect.Market.FXCM"/>
/// </summary>
public string Market { get; set; }
/// <summary>
/// The fill forward behavior, true to fill forward, false otherwise - defaults to true
/// </summary>
public bool FillDataForward { get; set; }
/// <summary>
/// The leverage for the security, defaults to 2 for equity, 50 for forex, and 1 for everything else
/// </summary>
public decimal Leverage { get; set; }
/// <summary>
/// The extended market hours flag, true to allow pre/post market data, false for only in market data
/// </summary>
public bool ExtendedMarketHours { get; set; }
/// <summary>
/// Default construct that applies default values
/// </summary>
public AddSecurityCommand()
{
Resolution = Resolution.Minute;
Market = null;
FillDataForward = true;
Leverage = Security.NullLeverage;
ExtendedMarketHours = false;
}
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
var security = algorithm.AddSecurity(SecurityType, Symbol, Resolution, Market, FillDataForward, Leverage, ExtendedMarketHours);
return new Result(this, true, security.Symbol);
}
/// <summary>
/// Result packet type for the <see cref="AddSecurityCommand"/> command
/// </summary>
public class Result : CommandResultPacket
{
/// <summary>
/// The symbol result from the add security command
/// </summary>
public Symbol Symbol { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Result"/> class
/// </summary>
public Result(AddSecurityCommand command, bool success, Symbol symbol)
: base(command, success)
{
Symbol = symbol;
}
}
}
}
+57
View File
@@ -0,0 +1,57 @@
/*
* 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 QuantConnect.Interfaces;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command that will change the algorithm's status
/// </summary>
public class AlgorithmStatusCommand : BaseCommand
{
/// <summary>
/// Gets or sets the algorithm status
/// </summary>
public AlgorithmStatus Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AlgorithmStatusCommand"/>
/// </summary>
public AlgorithmStatusCommand()
{
Status = AlgorithmStatus.Running;
}
/// <summary>
/// Initializes a new instance of the <see cref="AlgorithmStatusCommand"/> with
/// the specified status
/// </summary>
public AlgorithmStatusCommand(AlgorithmStatus status)
{
Status = status;
}
/// <summary>
/// Sets the algorithm's status to <see cref="Status"/>
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
algorithm.Status = Status;
return new CommandResultPacket(this, true);
}
}
}
+62
View File
@@ -0,0 +1,62 @@
/*
* 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 QuantConnect.Interfaces;
using System;
namespace QuantConnect.Commands
{
/// <summary>
/// Base command implementation
/// </summary>
public abstract class BaseCommand : ICommand
{
/// <summary>
/// Unique command id
/// </summary>
public string Id { get; set; }
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public abstract CommandResultPacket Run(IAlgorithm algorithm);
/// <summary>
/// Creats symbol using symbol properties.
/// </summary>
/// <param name="ticker">The string ticker symbol</param>
/// <param name="securityType">The security type of the ticker. If securityType == Option, then a canonical symbol is created</param>
/// <param name="market">The market the ticker resides in</param>
/// <param name="symbol">The algorithm to run this command against</param>
/// <exception cref="ArgumentException">If symbol is null or symbol can't be created with given args</exception>
protected Symbol GetSymbol(string ticker, SecurityType securityType, string market, Symbol symbol = null)
{
if (symbol != null)
{
// No need to create symbol if alrady exists
return symbol;
}
if (ticker != null && (securityType != null && securityType != SecurityType.Base) && market != null)
{
return Symbol.Create(ticker, securityType, market);
}
else
{
throw new ArgumentException($"BaseCommand.GetSymbol(): {Messages.BaseCommand.MissingValuesToGetSymbol}");
}
}
}
}
+151
View File
@@ -0,0 +1,151 @@
/*
* 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.Linq;
using Newtonsoft.Json;
using QuantConnect.Logging;
using QuantConnect.Packets;
using Newtonsoft.Json.Linq;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Commands
{
/// <summary>
/// Base algorithm command handler
/// </summary>
public abstract class BaseCommandHandler : ICommandHandler
{
/// <summary>
/// Command json settings
/// </summary>
protected static readonly JsonSerializerSettings Settings = new() { TypeNameHandling = TypeNameHandling.All };
/// <summary>
/// The algorithm instance
/// </summary>
protected IAlgorithm Algorithm { get; set; }
/// <summary>
/// Initializes this command queue for the specified job
/// </summary>
/// <param name="job">The job that defines what queue to bind to</param>
/// <param name="algorithm">The algorithm instance</param>
public virtual void Initialize(AlgorithmNodePacket job, IAlgorithm algorithm)
{
Algorithm = algorithm;
}
/// <summary>
/// Get the commands to run
/// </summary>
protected abstract IEnumerable<ICommand> GetCommands();
/// <summary>
/// Acknowledge a command that has been executed
/// </summary>
/// <param name="command">The command that was executed</param>
/// <param name="commandResultPacket">The result</param>
protected virtual void Acknowledge(ICommand command, CommandResultPacket commandResultPacket)
{
// nop
}
/// <summary>
/// Will consumer and execute any command in the queue
/// </summary>
public IEnumerable<CommandResultPacket> ProcessCommands()
{
List<CommandResultPacket> resultPackets = null;
try
{
foreach (var command in GetCommands().Where(c => c != null))
{
Log.Trace($"BaseCommandHandler.ProcessCommands(): {Messages.BaseCommandHandler.ExecutingCommand(command)}");
CommandResultPacket result;
try
{
result = command.Run(Algorithm);
}
catch (Exception err)
{
Log.Error(err);
Algorithm.Error($"{command.GetType().Name} Error: {err.Message}");
result = new CommandResultPacket(command, false);
}
Acknowledge(command, result);
if(resultPackets == null)
{
resultPackets = new List<CommandResultPacket>();
}
resultPackets.Add(result);
}
}
catch (Exception err)
{
Log.Error(err);
}
return resultPackets ?? Enumerable.Empty<CommandResultPacket>();
}
/// <summary>
/// Disposes of this instance
/// </summary>
public virtual void Dispose()
{
// nop
}
/// <summary>
/// Helper method to create a callback command
/// </summary>
protected ICommand TryGetCallbackCommand(string payload)
{
Dictionary<string, JToken> deserialized = new(StringComparer.InvariantCultureIgnoreCase);
try
{
if (!string.IsNullOrEmpty(payload))
{
var jobject = JObject.Parse(payload);
foreach (var kv in jobject)
{
deserialized[kv.Key] = kv.Value;
}
}
}
catch (Exception err)
{
Log.Error(err, $"Payload: '{payload}'");
return null;
}
if (!deserialized.TryGetValue("id", out var id) || id == null)
{
id = string.Empty;
}
if (!deserialized.TryGetValue("$type", out var type) || type == null)
{
type = string.Empty;
}
return new CallbackCommand { Id = id.ToString(), Type = type.ToString(), Payload = payload };
}
}
}
+63
View File
@@ -0,0 +1,63 @@
/*
* 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 Newtonsoft.Json;
using QuantConnect.Interfaces;
namespace QuantConnect.Commands
{
/// <summary>
/// Algorithm callback command type
/// </summary>
public class CallbackCommand : BaseCommand
{
/// <summary>
/// The target command type to run, if empty or null will be the generic untyped command handler
/// </summary>
public string Type { get; set; }
/// <summary>
/// The command payload
/// </summary>
public string Payload { get; set; }
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
if (string.IsNullOrEmpty(Type))
{
// target is the untyped algorithm handler
var result = algorithm.OnCommand(string.IsNullOrEmpty(Payload) ? null : JsonConvert.DeserializeObject<Command>(Payload));
return new CommandResultPacket(this, result);
}
return algorithm.RunCommand(this);
}
/// <summary>
/// The command string representation
/// </summary>
public override string ToString()
{
if (!string.IsNullOrEmpty(Type))
{
return Type;
}
return "OnCommand";
}
}
}
+62
View File
@@ -0,0 +1,62 @@
/*
* 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 QuantConnect.Interfaces;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command to cancel a specific order by id
/// </summary>
public class CancelOrderCommand : BaseCommand
{
/// <summary>
/// Gets or sets the order id to be cancelled
/// </summary>
public int OrderId { get; set; }
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
var ticket = algorithm.Transactions.CancelOrder(OrderId);
return ticket.CancelRequest != null && ticket.Status != Orders.OrderStatus.Invalid
? new Result(this, true, ticket.QuantityFilled)
: new Result(this, false, ticket.QuantityFilled);
}
/// <summary>
/// Result packet type for the <see cref="CancelOrderCommand"/> command
/// </summary>
public class Result : CommandResultPacket
{
/// <summary>
/// Gets or sets the quantity filled on the cancelled order
/// </summary>
public decimal QuantityFilled { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Result"/> class
/// </summary>
public Result(ICommand command, bool success, decimal quantityFilled)
: base(command, success)
{
QuantityFilled = quantityFilled;
}
}
}
}
+143
View File
@@ -0,0 +1,143 @@
/*
* 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.Linq;
using System.Dynamic;
using Newtonsoft.Json;
using QuantConnect.Data;
using System.Reflection;
using Newtonsoft.Json.Linq;
using System.Linq.Expressions;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Commands
{
/// <summary>
/// Base generic dynamic command class
/// </summary>
public class Command : DynamicObject
{
private static readonly MethodInfo SetPropertyMethodInfo = typeof(Command).GetMethod("SetProperty");
private static readonly MethodInfo GetPropertyMethodInfo = typeof(Command).GetMethod("GetProperty");
private readonly Dictionary<string, object> _storage = new(StringComparer.InvariantCultureIgnoreCase);
/// <summary>
/// Useful to string representation in python
/// </summary>
protected string PayloadData { get; set; }
/// <summary>
/// Get the metaObject required for Dynamism.
/// </summary>
public sealed override DynamicMetaObject GetMetaObject(Expression parameter)
{
return new SerializableDynamicMetaObject(parameter, this, SetPropertyMethodInfo, GetPropertyMethodInfo);
}
/// <summary>
/// Sets the property with the specified name to the value. This is a case-insensitve search.
/// </summary>
/// <param name="name">The property name to set</param>
/// <param name="value">The new property value</param>
/// <returns>Returns the input value back to the caller</returns>
public object SetProperty(string name, object value)
{
if (value is JArray jArray)
{
return _storage[name] = jArray.ToObject<List<object>>();
}
else if (value is JObject jobject)
{
return _storage[name] = jobject.ToObject<Dictionary<string, object>>();
}
else
{
return _storage[name] = value;
}
}
/// <summary>
/// Gets the property's value with the specified name. This is a case-insensitve search.
/// </summary>
/// <param name="name">The property name to access</param>
/// <returns>object value of BaseData</returns>
public object GetProperty(string name)
{
if (!_storage.TryGetValue(name, out var value))
{
var type = GetType();
if (type != typeof(Command))
{
var propertyInfo = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo != null)
{
return propertyInfo.GetValue(this, null);
}
var fieldInfo = type.GetField(name, BindingFlags.Public | BindingFlags.Instance);
if (fieldInfo != null)
{
return fieldInfo.GetValue(this);
}
}
return null;
}
return value;
}
/// <summary>
/// Run this command using the target algorithm
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <returns>True if success, false otherwise. Returning null will disable command feedback</returns>
public virtual bool? Run(IAlgorithm algorithm)
{
throw new NotImplementedException($"Please implement the 'def run(algorithm) -> bool | None:' method");
}
/// <summary>
/// The string representation of this command
/// </summary>
public override string ToString()
{
if (!string.IsNullOrEmpty(PayloadData))
{
return PayloadData;
}
return JsonConvert.SerializeObject(this);
}
/// <summary>
/// Helper class so we can serialize a command
/// </summary>
private class SerializableDynamicMetaObject : GetSetPropertyDynamicMetaObject
{
private readonly Command _object;
public SerializableDynamicMetaObject(Expression expression, object value, MethodInfo setPropertyMethodInfo, MethodInfo getPropertyMethodInfo)
: base(expression, value, setPropertyMethodInfo, getPropertyMethodInfo)
{
_object = (Command)value;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _object._storage.Keys.Concat(_object.GetType()
.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property).Select(x => x.Name));
}
}
}
}
+46
View File
@@ -0,0 +1,46 @@
/*
* 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 QuantConnect.Packets;
namespace QuantConnect.Commands
{
/// <summary>
/// Contains data held as the result of executing a command
/// </summary>
public class CommandResultPacket : Packet
{
/// <summary>
/// Gets or sets the command that produced this packet
/// </summary>
public string CommandName { get; set; }
/// <summary>
/// Gets or sets whether or not the
/// </summary>
public bool? Success { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CommandResultPacket"/> class
/// </summary>
public CommandResultPacket(ICommand command, bool? success)
: base(PacketType.CommandResult)
{
Success = success;
CommandName = command.GetType().Name;
}
}
}
+148
View File
@@ -0,0 +1,148 @@
/*
* 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.IO;
using Newtonsoft.Json;
using QuantConnect.Logging;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command handler that sources it's commands from a file on the local disk
/// </summary>
public class FileCommandHandler : BaseCommandHandler
{
private readonly Queue<ICommand> _commands = new();
private const string _commandFilePattern = "command*.json";
private const string _resultFileBaseName = "result-command";
/// <summary>
/// Initializes a new instance of the <see cref="FileCommandHandler"/> class
/// using the 'command-json-file' configuration value for the command json file
/// </summary>
public FileCommandHandler()
{
}
/// <summary>
/// Gets all the available command files
/// </summary>
/// <returns>Sorted enumerator of all the available command files</returns>
public static IEnumerable<FileInfo> GetCommandFiles()
{
var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
var filesFromPattern = currentDirectory.GetFiles(_commandFilePattern);
return filesFromPattern.OrderBy(file => file.Name);
}
/// <summary>
/// Gets the next command in the queue
/// </summary>
/// <returns>The next command in the queue, if present, null if no commands present</returns>
protected override IEnumerable<ICommand> GetCommands()
{
foreach(var file in GetCommandFiles())
{
// update the queue by reading the command file
ReadCommandFile(file.FullName);
while (_commands.Count != 0)
{
yield return _commands.Dequeue();
}
}
}
/// <summary>
/// Acknowledge a command that has been executed
/// </summary>
/// <param name="command">The command that was executed</param>
/// <param name="commandResultPacket">The result</param>
protected override void Acknowledge(ICommand command, CommandResultPacket commandResultPacket)
{
if (string.IsNullOrEmpty(command.Id))
{
Log.Error($"FileCommandHandler.Acknowledge(): {Messages.FileCommandHandler.NullOrEmptyCommandId}");
return;
}
var resultFilePath = $"{_resultFileBaseName}-{command.Id}.json";
File.WriteAllText(resultFilePath, JsonConvert.SerializeObject(commandResultPacket));
}
/// <summary>
/// Reads the commnd file on disk and populates the queue with the commands
/// </summary>
private void ReadCommandFile(string commandFilePath)
{
Log.Trace($"FileCommandHandler.ReadCommandFile(): {Messages.FileCommandHandler.ReadingCommandFile(commandFilePath)}");
string contents = null;
Exception exception = null;
object deserialized = null;
try
{
if (!File.Exists(commandFilePath))
{
Log.Error($"FileCommandHandler.ReadCommandFile(): {Messages.FileCommandHandler.CommandFileDoesNotExist(commandFilePath)}");
return;
}
contents = File.ReadAllText(commandFilePath);
deserialized = JsonConvert.DeserializeObject(contents, Settings);
}
catch (Exception err)
{
exception = err;
}
// remove the file when we're done reading it
File.Delete(commandFilePath);
// try it as an enumerable
var enumerable = deserialized as IEnumerable<ICommand>;
if (enumerable != null)
{
foreach (var command in enumerable)
{
_commands.Enqueue(command);
}
return;
}
// try it as a single command
var item = deserialized as ICommand;
if (item != null)
{
_commands.Enqueue(item);
return;
}
var callbackCommand = TryGetCallbackCommand(contents);
if (callbackCommand != null)
{
_commands.Enqueue(callbackCommand);
return;
}
if (exception != null)
{
// if we are here we failed
Log.Error(exception);
}
}
}
}
+36
View File
@@ -0,0 +1,36 @@
/*
* 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 QuantConnect.Interfaces;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command that can be run against a single algorithm
/// </summary>
public interface ICommand
{
/// <summary>
/// Unique command id
/// </summary>
string Id { get; set; }
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
CommandResultPacket Run(IAlgorithm algorithm);
}
}
+42
View File
@@ -0,0 +1,42 @@
/*
* 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 QuantConnect.Packets;
using QuantConnect.Interfaces;
using System.Collections.Generic;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command queue for the algorithm. This is an entry point
/// for external messages to act upon the running algorithm instance.
/// </summary>
public interface ICommandHandler : IDisposable
{
/// <summary>
/// Initializes this command queue for the specified job
/// </summary>
/// <param name="job">The job that defines what queue to bind to</param>
/// <param name="algorithm">The algorithm instance</param>
void Initialize(AlgorithmNodePacket job, IAlgorithm algorithm);
/// <summary>
/// Process any commands in the queue
/// </summary>
/// <returns>The command result packet of each command executed if any</returns>
IEnumerable<CommandResultPacket> ProcessCommands();
}
}
+59
View File
@@ -0,0 +1,59 @@
/*
* 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 QuantConnect.Interfaces;
using System;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command that will liquidate the entire algorithm
/// </summary>
public class LiquidateCommand : BaseCommand
{
/// <summary>
/// Gets or sets the string ticker symbol
/// </summary>
public string Ticker { get; set; }
/// <summary>
/// Gets or sets the security type of the ticker.
/// </summary>
public SecurityType SecurityType { get; set; }
/// <summary>
/// Gets or sets the market the ticker resides in
/// </summary>
public string Market { get; set; }
/// <summary>
/// Submits orders to liquidate all current holdings in the algorithm
/// </summary>
/// <param name="algorithm">The algorithm to be liquidated</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
if (Ticker != null || SecurityType != SecurityType.Base || Market != null)
{
var symbol = GetSymbol(Ticker, SecurityType, Market);
algorithm.Liquidate(symbol);
}
else
{
algorithm.Liquidate();
}
return new CommandResultPacket(this, true);
}
}
}
+110
View File
@@ -0,0 +1,110 @@
/*
* 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 QuantConnect.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command to submit an order to the algorithm
/// </summary>
public class OrderCommand : BaseCommand
{
/// <summary>
/// Gets or sets the symbol to be ordered
/// </summary>
public Symbol Symbol { get; set; }
/// <summary>
/// Gets or sets the string ticker symbol
/// </summary>
public string Ticker { get; set; }
/// <summary>
/// Gets or sets the security type of the ticker.
/// </summary>
public SecurityType SecurityType { get; set; }
/// <summary>
/// Gets or sets the market the ticker resides in
/// </summary>
public string Market { get; set; }
/// <summary>
/// Gets or sets the order type to be submted
/// </summary>
public OrderType OrderType { get; set; }
/// <summary>
/// Gets or sets the number of units to be ordered (directional)
/// </summary>
public decimal Quantity { get; set; }
/// <summary>
/// Gets or sets the limit price. Only applies to <see cref="QuantConnect.Orders.OrderType.Limit"/> and <see cref="QuantConnect.Orders.OrderType.StopLimit"/>
/// </summary>
public decimal LimitPrice { get; set; }
/// <summary>
/// Gets or sets the stop price. Only applies to <see cref="QuantConnect.Orders.OrderType.StopLimit"/> and <see cref="QuantConnect.Orders.OrderType.StopMarket"/>
/// </summary>
public decimal StopPrice { get; set; }
/// <summary>
/// Gets or sets an arbitrary tag to be attached to the order
/// </summary>
public string Tag { get; set; }
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
Symbol = GetSymbol(Ticker, SecurityType, Market, Symbol);
var request = new SubmitOrderRequest(OrderType, Symbol.SecurityType, Symbol, Quantity, StopPrice, LimitPrice, DateTime.UtcNow, Tag, algorithm.DefaultOrderProperties);
var ticket = algorithm.SubmitOrderRequest(request);
var response = ticket.GetMostRecentOrderResponse();
var message = Messages.OrderCommand.CommandInfo(OrderType, Symbol, Quantity, response);
if (response.IsError)
{
algorithm.Error(message);
}
else
{
algorithm.Debug(message);
}
return new CommandResultPacket(this, success: !response.IsError);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
Symbol = GetSymbol(Ticker, SecurityType, Market, Symbol);
// delegate to the order request
return new SubmitOrderRequest(OrderType, Symbol.SecurityType, Symbol, Quantity, StopPrice, LimitPrice, DateTime.UtcNow, Tag).ToString();
}
}
}
+31
View File
@@ -0,0 +1,31 @@
/*
* 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.
*/
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command that will terminate the algorithm
/// </summary>
public class QuitCommand : AlgorithmStatusCommand
{
/// <summary>
/// Initializes a new instance of the <see cref="QuitCommand"/>
/// </summary>
public QuitCommand()
: base(AlgorithmStatus.Stopped)
{
}
}
}
+71
View File
@@ -0,0 +1,71 @@
/*
* 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 QuantConnect.Interfaces;
using QuantConnect.Orders;
namespace QuantConnect.Commands
{
/// <summary>
/// Represents a command to update an order by id
/// </summary>
public class UpdateOrderCommand : BaseCommand
{
/// <summary>
/// Gets or sets the id of the order to update
/// </summary>
public int OrderId { get; set; }
/// <summary>
/// Gets or sets the new quantity, specify null to not update the quantity
/// </summary>
public decimal? Quantity { get; set; }
/// <summary>
/// Gets or sets the new limit price, specify null to not update the limit price.
/// This will only be used if the order has a limit price (Limit/StopLimit orders)
/// </summary>
public decimal? LimitPrice { get; set; }
/// <summary>
/// Gets or sets the new stop price, specify null to not update the stop price.
/// This will onky be used if the order has a stop price (StopLimit/StopMarket orders)
/// </summary>
public decimal? StopPrice { get; set; }
/// <summary>
/// Gets or sets the new tag for the order, specify null to not update the tag
/// </summary>
public string Tag { get; set; }
/// <summary>
/// Runs this command against the specified algorithm instance
/// </summary>
/// <param name="algorithm">The algorithm to run this command against</param>
public override CommandResultPacket Run(IAlgorithm algorithm)
{
var ticket = algorithm.Transactions.UpdateOrder(new UpdateOrderRequest(algorithm.UtcTime, OrderId, new UpdateOrderFields
{
Quantity = Quantity,
LimitPrice = LimitPrice,
StopPrice = StopPrice,
Tag = Tag
}));
var response = ticket.GetMostRecentOrderResponse();
return new CommandResultPacket(this, response.IsSuccess);
}
}
}