/// <summary> /// Gets all possible combinations for the given parameters /// </summary> /// <param name="args">ctor arguments to create combinations with</param> /// <param name="conditionalParameters">contains info for the conditional parameters</param> /// <param name="conditionalIndex">index of conditional parameter to be used for iterations</param> private void GetAllIterations(object[] args, Tuple <int, string, string>[] conditionalParameters, int conditionalIndex) { try { // get index of parameter to be incremented int index = conditionalParameters[conditionalIndex].Item1; // Get end value for the parameter decimal endPoint; if (!decimal.TryParse(conditionalParameters[conditionalIndex].Item2, out endPoint)) { return; } // Get increment value to be used decimal increment; if (!decimal.TryParse(conditionalParameters[conditionalIndex].Item3, out increment)) { return; } // Get Orignal Value decimal orignalValue = Convert.ToDecimal(args[index]); // Iterate through all combinations for (decimal i = 0; ; i += increment) { // Modify parameter value var parameter = orignalValue + i; if (parameter > endPoint) { break; } // Convert string value to required format var value = LoadCustomStrategy.GetParametereValue(parameter.ToString(), _parmatersDetails[index].ParameterType.Name); // Update arguments array args[index] = value; // Check if the combination is already present if (!ValueAdded(args, _ctorArguments, index)) { // Add the updated arguments to local map _ctorArguments.Add(args.Clone() as object[]); // Get further iterations if if (conditionalIndex > 0) { GetAllIterations(args.Clone() as object[], conditionalParameters, conditionalIndex - 1); } } } } catch (Exception exception) { _asyncClassLogger.Error(exception, _type.FullName, "IterateParameters"); } }
/// <summary> /// Loads user strategy and extracts constructor parameters /// </summary> private void LoadUserStrategy(LoadStrategy loadStrategy) { try { if (_asyncClassLogger.IsInfoEnabled) { _asyncClassLogger.Info("Trying to load user defined strategy from: " + loadStrategy.StrategyAssembly.FullName.Substring(0, loadStrategy.StrategyAssembly.FullName.IndexOf(",", System.StringComparison.Ordinal)), _type.FullName, "LoadUserStrategy"); } var strategyDetails = LoadCustomStrategy.GetConstructorDetails(loadStrategy.StrategyAssembly); if (strategyDetails != null) { if (_asyncClassLogger.IsInfoEnabled) { _asyncClassLogger.Info("Successfully loaded custom strategy: " + strategyDetails.Item1.Name, _type.Name, "LoadUserStrategy"); } // Create new Strategy Constructor Info object StrategyConstructorInfo strategyConstructorInfo = new StrategyConstructorInfo( strategyDetails.Item2, strategyDetails.Item1); // Publish Event to Notify Listener. EventSystem.Publish <StrategyConstructorInfo>(strategyConstructorInfo); } } catch (Exception exception) { _asyncClassLogger.Error(exception, _type.FullName, "LoadUserStrategy"); } }
/// <summary> /// Initializes necessary fields and parameters /// </summary> /// <param name="strategyType">User Strategy Type</param> /// <param name="ctorArguments">Constructor arguments to initialize strategy</param> private void Initialize(Type strategyType, object[] ctorArguments) { _manualReset = new ManualResetEvent(false); _logger = new AsyncClassLogger("StrategyExecutorGeneticAlgo"); // Save Strategy Type _strategyType = strategyType; //Save Arguments _ctorArguments = ctorArguments; // Set Logging levels _logger.SetLoggingLevel(); // Get new strategy instance var strategyInstance = LoadCustomStrategy.CreateStrategyInstance(_strategyType, _ctorArguments); if (strategyInstance != null) { // Cast to TradeHubStrategy Instance _tradeHubStrategy = strategyInstance as TradeHubStrategy; InitializeStrategyListeners(); OverrideMarketRequestCalls(); OverrideOrderRequestCalls(); } }
/// <summary> /// Verifies the selected arguments to initialize the strategy /// </summary> /// <param name="selectedArgs">Constructor Arguments</param> private object[] VerfiySelectedArguments(object[] selectedArgs) { try { object[] ctrArgs = new object[selectedArgs.Length]; foreach (ParameterInfo parameterInfo in _parmatersInfo) { object value; // Convert string value to required format value = LoadCustomStrategy.GetParametereValue(selectedArgs[parameterInfo.Position].ToString(), parameterInfo.ParameterType.Name); if (value == null) { if (Logger.IsInfoEnabled) { Logger.Info("Parameter was not in the correct format. Rquired: " + parameterInfo.ParameterType.Name + " Provided value: " + selectedArgs[parameterInfo.Position], _type.FullName, "VerfiySelectedArguments"); } return(null); } // Add to value to arguments array ctrArgs[parameterInfo.Position] = value; } // Return verified arguments return(ctrArgs); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "VerfiySelectedArguments"); return(null); } }
/// <summary> /// Starts custom strategy execution /// </summary> public void ExecuteStrategy() { try { // Verify Strategy Instance if (_tradeHubStrategy == null) { //create DB strategy Strategy strategy = new Strategy(); strategy.Name = _strategyType.Name; strategy.StartDateTime = DateTime.Now; // Get new strategy instance var strategyInstance = LoadCustomStrategy.CreateStrategyInstance(_strategyType, CtorArguments); if (strategyInstance != null) { // Cast to TradeHubStrategy Instance _tradeHubStrategy = strategyInstance as TradeHubStrategy; } if (_tradeHubStrategy == null) { if (_asyncClassLogger.IsInfoEnabled) { _asyncClassLogger.Info("Unable to initialize Custom Strategy: " + _strategyType.FullName, _type.FullName, "ExecuteStrategy"); } // Skip execution of further actions return; } // Set Strategy Name _tradeHubStrategy.StrategyName = LoadCustomStrategy.GetCustomClassSummary(_strategyType); // Register Events _tradeHubStrategy.OnStrategyStatusChanged += OnStrategyStatusChanged; _tradeHubStrategy.OnNewExecutionReceived += OnNewExecutionReceived; } if (_asyncClassLogger.IsInfoEnabled) { _asyncClassLogger.Info("Executing user strategy: " + _strategyType.FullName, _type.FullName, "ExecuteStrategy"); } //Overriding if running on simulated exchange ManageBackTestingStrategy(); // Start Executing the strategy _tradeHubStrategy.Run(); } catch (Exception exception) { _asyncClassLogger.Error(exception, _type.FullName, "ExecuteStrategy"); } }
/// <summary> /// Sets up the strategy to be executed /// </summary> /// <param name="initializeStrategy">Holds info to initialize the given strategy</param> private void InitializeUserStrategy(InitializeStrategy initializeStrategy) { try { if (_asyncClassLogger.IsInfoEnabled) { _asyncClassLogger.Info("Setting up user strategy to run: " + initializeStrategy.StrategyType.FullName, _type.FullName, "InitializeUserStrategy"); } // Get new Key. string key = ApplicationIdGenerator.NextId(); // Save Strategy details in new Strategy Executor object StrategyExecutor strategyExecutor = new StrategyExecutor(key, initializeStrategy.StrategyType, initializeStrategy.CtorArguments); // Add to local map _strategiesCollection.AddOrUpdate(key, strategyExecutor, (ky, value) => strategyExecutor); //Register Event strategyExecutor.StatusChanged += OnStatusChanged; strategyExecutor.ExecutionReceived += OnExecutionArrived; // Save Brief info of constructor parameters StringBuilder briefInfo = new StringBuilder(); // Add Strategy Description briefInfo.Append(LoadCustomStrategy.GetCustomClassSummary(initializeStrategy.StrategyType)); briefInfo.Append(" :: "); // Add Parameters Description foreach (object ctorArgument in initializeStrategy.CtorArguments) { briefInfo.Append(ctorArgument.ToString()); briefInfo.Append("|"); } // Create object to add to AddStrattegy.cs object SelectedStrategy selectedStrategy = new SelectedStrategy { Key = key, Symbol = initializeStrategy.CtorArguments[3].ToString(), BriefInfo = briefInfo.ToString() }; // Create object to pass to event aggregator. AddStrategy addStrategy = new AddStrategy(selectedStrategy); // Publish event to notify listeners. EventSystem.Publish <AddStrategy>(addStrategy); } catch (Exception exception) { _asyncClassLogger.Error(exception, _type.FullName, "InitializeUserStrategy"); } }
/// <summary> /// Verifies the arguments on selected index to initialize the strategy /// </summary> /// <param name="index">Index of the arguments to verify</param> private object[] VerfiySelectedArgumentsOnGivenIndex(int index) { try { string[] parameters; if (_selectedConstuctorParameters.TryGetValue(index, out parameters)) { object[] ctrArgs = new object[parameters.Length]; foreach (ParameterInfo parameterInfo in _parmatersInfo) { object value; // Convert string value to required format value = LoadCustomStrategy.GetParametereValue(parameters[parameterInfo.Position], parameterInfo.ParameterType.Name); if (value == null) { if (Logger.IsInfoEnabled) { Logger.Info("Parameter was not in the correct format. Rquired: " + parameterInfo.ParameterType.Name + " Provided value: " + parameters[parameterInfo.Position], _type.FullName, "VerfiySelectedArgumentsOnGivenIndex"); } return(null); } // Add to value to arguments array ctrArgs[parameterInfo.Position] = value; } // Return verified arguments return(ctrArgs); } if (Logger.IsInfoEnabled) { Logger.Info("Specified parameters could not be found.", _type.FullName, "VerfiySelectedParameterValues"); } return(null); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "VerfiySelectedArgumentsOnGivenIndex"); return(null); } }
/// <summary> /// Displays the selected strategy parameters /// </summary> /// <param name="optimizeStrategy">Contains info regarding the strategy to be optimized</param> private void DisplaySelectedStrategy(OptimizationParametersBruteForce optimizeStrategy) { try { if (Logger.IsDebugEnabled) { Logger.Debug("Displaying the strategy parameters", _type.FullName, "DisplaySelectedStrategy"); } _parameters.Clear(); // Get Strategy Info StrategyInfo = LoadCustomStrategy.GetCustomClassSummary(optimizeStrategy.StrategyType); // Save Ctor Arguments _ctorArguments = optimizeStrategy.CtorArguments; // Save Custom Strategy Type _strategyType = optimizeStrategy.StrategyType; // Save Parameters Details _parmatersDetails = optimizeStrategy.ParameterDetails; // Get all parameters for (int i = 0; i < optimizeStrategy.CtorArguments.Length; i++) { ParameterInfo parameterInfo = new ParameterInfo { Index = i, Parameter = optimizeStrategy.ParameterDetails[i].Name, Value = optimizeStrategy.CtorArguments[i].ToString() }; _currentDispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { // Add to collection _parameters.Add(parameterInfo); })); } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "DisplaySelectedStrategy"); } }
/// <summary> /// Returns Custom attributes used in the user strategy /// </summary> private Dictionary <int, Tuple <string, Type> > GetCustomAttributes(Type strategyType) { try { // Contains custom defined attributes in the given assembly Dictionary <int, Tuple <string, Type> > customAttributes = null; // Get Custom Attributes if (strategyType != null) { // Get custom attributes from the given assembly customAttributes = LoadCustomStrategy.GetCustomAttributes(strategyType); } return(customAttributes); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "GetCustomAttributes"); return(null); } }
public void GetCustomAttributesTestCase() { // Load Assembly file from the selected file Assembly assembly = Assembly.LoadFrom(_assemblyName); // Contains custom defined attributes in the given assembly Dictionary <int, Tuple <string, Type> > customAttributes = null; // Get Constructor information for the given assembly var strategyDetails = LoadCustomStrategy.GetConstructorDetails(assembly); if (strategyDetails != null) { // Get Strategy Type var strategyType = strategyDetails.Item1; // Get custom attributes from the given assembly customAttributes = LoadCustomStrategy.GetCustomAttributes(strategyType); } Assert.IsNotNull(strategyDetails, "Constructor Information for the given assembly was not found."); Assert.IsNotNull(customAttributes, "Custom attributes were not found in the given assembly."); Assert.AreEqual(3, customAttributes.Count, "Count of read custom attributes was not equal to expected value."); }
static void Main(string[] args) { //IList<string> namesOfFiles = new List<string>(); //DateTime startTime = new DateTime(2013,8,25); //DateTime endTime = new DateTime(2013,8,30); //string specificFolder = @"C:\aurora\ATS\Saved Data"; //string providerName = "InteractiveBrokers"; //string[] directoryNames = new string[3]; //// Get possible directory path for bars created with BID Price //directoryNames[0] = specificFolder + "\\" + providerName + "\\" + "AAPL" + "\\Bar\\" + // TradeHubConstants.BarFormat.TIME + "\\" + TradeHubConstants.BarPriceType.BID; //// Get possible directory path for bars created with ASK Price //directoryNames[1] = specificFolder + "\\" + providerName + "\\" + "AAPL" + "\\Bar\\" + // TradeHubConstants.BarFormat.TIME + "\\" + TradeHubConstants.BarPriceType.ASK; //// Get possible directory path for bars created with LAST Price //directoryNames[2] = specificFolder + "\\" + providerName + "\\" + "AAPL" + "\\Bar\\" + // TradeHubConstants.BarFormat.TIME + "\\" + TradeHubConstants.BarPriceType.LAST; //// Traverse all possible directories //foreach (string directoryName in directoryNames) //{ // var directory = new DirectoryInfo(directoryName); // // Find required files if the path exists // if (directory.Exists) // { // // Find all possible subfolders in the given directory // IEnumerable<string> subFolders = directory.GetDirectories().Select(subDirectory => subDirectory.Name); // // Use all sub-directories to find files with required info // foreach (string subFolder in subFolders) // { // DateTime tempStartTime = new DateTime(startTime.Ticks); // while (tempStartTime.Date <= endTime.Date) // { // var filename = tempStartTime.ToString("yyyyMMdd") + ".txt"; // // Get the File paths of required date. // string[] path = Directory.GetFiles(directoryName + "\\" + subFolder, // filename, SearchOption.AllDirectories); // if (path.Any()) // { // namesOfFiles.Add(path[0]); // } // tempStartTime = tempStartTime.AddDays(1); // } // } // } //} //foreach (string namesOfFile in namesOfFiles) //{ // System.Console.WriteLine(namesOfFile); //} var strategyDetails = LoadCustomStrategy.GetConstructorDetails("TradeHub.StrategyRunner.SampleStrategy.dll"); if (strategyDetails != null) { var strategyType = strategyDetails.Item1; var ctorDetails = strategyDetails.Item2; object[] ctrArgs = new object[ctorDetails.Length]; foreach (ParameterInfo parameterInfo in ctorDetails) { object value; do { System.Console.WriteLine("Enter " + parameterInfo.ParameterType.Name + " value for: " + parameterInfo.Name); var input = System.Console.ReadLine(); value = LoadCustomStrategy.GetParametereValue(input, parameterInfo.ParameterType.Name); } while (value == null); ctrArgs[parameterInfo.Position] = value; } LoadCustomStrategy.CreateStrategyInstance(strategyType, ctrArgs); } while (true) { } }
/// <summary> /// Returns Parameters details i.e Parameter names with there Types /// </summary> /// <returns></returns> public static Dictionary <string, Type> GetParameterDetails(Type assemblyType) { return(LoadCustomStrategy.GetParameterDetails(assemblyType)); }
/// <summary> /// Get class summary /// </summary> /// <param name="type"></param> /// <returns></returns> public static string GetCustomClassSummary(Type type) { return(LoadCustomStrategy.GetCustomClassSummary(type)); }
/// <summary> /// Gets Tradehub strategy Class Type /// </summary> /// <param name="assemblyPath">assemblyPath</param> public static Type GetStrategyClassType(string assemblyPath) { return(LoadCustomStrategy.GetStrategyClassType(assemblyPath)); }
/// <summary> /// Get custom attributes of type /// </summary> /// <param name="type"></param> /// <returns></returns> public static Dictionary <int, Tuple <string, Type> > GetCustomAttributes(Type type) { return(LoadCustomStrategy.GetCustomAttributes(type)); }
/// <summary> /// Create instance of strategy /// </summary> /// <param name="type"></param> /// <param name="ctrArgs"></param> /// <returns></returns> public static object CreateStrategyInstance(Type type, object[] ctrArgs) { return(LoadCustomStrategy.CreateStrategyInstance(type, ctrArgs)); }
/// <summary> /// Get constructor details /// </summary> /// <param name="assemblyName"></param> /// <returns></returns> public static Tuple <Type, ParameterInfo[]> GetConstructorDetails(string assemblyName) { return(LoadCustomStrategy.GetConstructorDetails(assemblyName)); }
/// <summary> /// Vealidate startegy dll /// </summary> /// <param name="assemblyPath">Path of the assembly</param> /// <returns></returns> public static bool ValidateStrategy(string assemblyPath) { return(LoadCustomStrategy.VerifyStrategy(assemblyPath)); }
/// <summary> /// Get parameter values /// </summary> /// <param name="input"></param> /// <param name="type"></param> /// <returns></returns> public static object GetParametereValue(string input, string type) { return(LoadCustomStrategy.GetParametereValue(input, type)); }
/// <summary> /// Displays available parameters for genetic optimization /// </summary> private void DisplayGeneticParameters(OptimizationParametersGeneticAlgo optimizeStrategyGeneticAlgo) { try { if (Logger.IsDebugEnabled) { Logger.Debug("Displaying the strategy parameters", _type.FullName, "DisplaySelectedStrategy"); } _parameters.Clear(); // Get Strategy Info GaStrategyInfo = LoadCustomStrategy.GetCustomClassSummary(optimizeStrategyGeneticAlgo.StrategyType); // Save Ctor Arguments _ctorArguments = optimizeStrategyGeneticAlgo.CtorArguments; // Save Custom Strategy Type _strategyType = optimizeStrategyGeneticAlgo.StrategyType; int i = 0; // Get all parameters foreach (var parameters in optimizeStrategyGeneticAlgo.GeneticAlgoParameters) { double start = 0; double end = 0; if (i == 0) { start = 1; end = 5; } else if (i == 1) { start = 0.0001; end = 0.011; } else if (i == 2) { start = 0.2; end = 10; } else if (i == 3) { start = 0.002; end = 0.01; } GeneticAlgoParameters parameterInfo = new GeneticAlgoParameters { Index = parameters.Key, Description = parameters.Value.Item1, StartValue = start, EndValue = end, }; i++; // Update UI Element _currentDispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { // Add to collection _parameters.Add(parameterInfo); })); } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "DisplayGeneticParameters"); } }