Search Framework:
Strategy
Namespace: WealthLab.Backtest
Parent: Object

The Strategy class contains a WealthLab Strategy's code or rules, metadata, backtest configuration, optimization settings, and compiled StrategyBase instance. The Backtester exposes the Strategy being tested through Backtester.Strategy, which can be useful for inspecting settings such as PositionSize, Benchmark, DataSetName, Scale, and DataRange.

Warning: Strategy settings should generally be treated as read-only from Strategy execution code. Changing them while a backtest is running can produce unexpected results.

Backtest Configuration
Benchmark
public string Benchmark

Gets or sets the symbol used for the benchmark backtest. The default benchmark is determined by StrategyFactory when the Strategy is initialized.

Example Code
using WealthLab.Backtest;
using WealthLab.Core;
namespace WealthScript
{
    public class BenchmarkExample : UserStrategyBase
    {
        public override void Initialize(BarHistory bars)
        {
            string benchmark = Backtester.Strategy.Benchmark;
            DrawHeaderText(
                "Benchmark is " + benchmark,
                WLColor.Red,
                14);
        }
        public override void Execute(BarHistory bars, int idx)
        {
        }
    }
}

DataRange
public DataRange DataRange

Gets or sets the DataRange used for the Strategy's backtests.


DataSetName
public string DataSetName

Gets or sets the name of the DataSet selected for portfolio backtests.

Example Code
using WealthLab.Backtest;
using WealthLab.Core;
namespace WealthScript
{
    public class DataSetExample : UserStrategyBase
    {
        public override void Initialize(BarHistory bars)
        {
            Strategy strategy = Backtester.Strategy;
            if (strategy.SingleSymbolMode)
            {
                DrawHeaderText(
                    "Single Symbol: " + strategy.SingleSymbol,
                    WLColor.Red,
                    14);
            }
            else
            {
                DrawHeaderText(
                    "DataSet: " + strategy.DataSetName,
                    WLColor.Red,
                    14);
            }
        }
        public override void Execute(BarHistory bars, int idx)
        {
        }
    }
}

GetBacktestSettings
public BacktestSettings GetBacktestSettings()

Returns a BacktestSettings instance representing the Strategy's backtest-related settings. The returned instance is cloned from the global BacktestSettings and updated with the Strategy's RetainNSF and GranularLimitStopScale settings.


GranularLimitStopScale
public HistoryScale GranularLimitStopScale

Gets or sets the intraday scale used for granular processing of limit and stop orders. A Daily scale indicates that granular processing is disabled. See also UpdateGranularData.


PositionSize
public PositionSize PositionSize

Gets or sets the PositionSize configuration used for the Strategy's backtests.


RetainNSF
public bool RetainNSF

Gets or sets whether the Strategy retains Positions that receive NSF, or Not Sufficient Funds, status. The default value is true.


Scale
public HistoryScale Scale

Gets or sets the HistoryScale used for the Strategy's backtests.


SingleSymbol
public string SingleSymbol

Gets or sets the symbol used when SingleSymbolMode is true.


SingleSymbolMode
public bool SingleSymbolMode

Gets or sets whether the Strategy is configured for a single-symbol backtest. When false, the Strategy is configured for a DataSet portfolio backtest.


UpdateGranularData
public bool UpdateGranularData

Gets or sets whether granular intraday data should be updated during the backtest. See also GranularLimitStopScale.


UseSelectedDataSetOnly
public bool UseSelectedDataSetOnly

Gets or sets whether the Strategy should use only its selected DataSet. The default value is false.



Compilation
CanChart
public bool CanChart

Returns true if the StrategyType supports being opened or dropped onto a streaming chart.


CompiledStrategy
public StrategyBase CompiledStrategy

Gets or sets the compiled StrategyBase instance associated with this Strategy. Assigning a non-null instance also updates CouldOptimize based on CanOptimize.


CompiledStrategyTypeName
public string CompiledStrategyTypeName

Gets or sets the type name associated with a compiled Strategy. When CompiledStrategy is available and StrategyType is Compiled, the property's getter returns the runtime type name of CompiledStrategy.


CompilerErrors
public List<CompilerError> CompilerErrors

Gets or sets the list of compiler or Strategy validation errors generated when creating the executable Strategy instance.


CreateCompiledStrategyInstance
public void CreateCompiledStrategyInstance()

Creates the CompiledStrategy instance for a Strategy whose StrategyType is StrategyType.Compiled. If StrategyData is not empty, it is parsed into the newly created StrategyBase instance.


CreateInstance
public StrategyBase CreateInstance()

Creates and returns the compiled StrategyBase instance represented by this Strategy. The behavior depends on StrategyType:

  • Compiled - Creates the corresponding compiled Strategy instance.
  • Rotation - Creates a RotationStrategy.
  • TradeHistory - Creates a TradeHistoryStrategy.
  • MetaStrategy - Creates a MetaStrategy.
  • Code - Compiles the C# source in StrategyData.
  • BuildingBlock - Generates C# code from the Building Block Strategy and compiles it. Compiler and parameter validation errors are placed in CompilerErrors.

CreateNewInstance
public UserStrategyBase CreateNewInstance()

Creates and returns a new UserStrategyBase instance having the same runtime type as the Strategy's compiled UserStrategyBase. Returns null if a suitable compiled UserStrategyBase cannot be obtained.


DefaultTemplateCode
public static string DefaultTemplateCode

Gets or sets the default C# source code used when creating a new Code Strategy. WealthLab first attempts to load the template from DefaultTemplateCode.txt in the WealthLab data folder. If the file is not present, the built-in Strategy template is used. Assigning a non-empty value updates the template and writes it to the template file.


GetExecutableInstance
public StrategyBase GetExecutableInstance()

Returns an executable StrategyBase instance. For a UserStrategyBase-derived Strategy, WealthLab creates a fresh UserStrategyBase instance and wraps it in a UserStrategyExecutor. For other StrategyBase types, CreateInstance is used. Returns null if no CompiledStrategy is available.


IsRunningInEvolver
public bool IsRunningInEvolver

Gets or sets whether the Strategy is being compiled for use by the Strategy Evolver.



Constructors
Strategy
public Strategy()
public Strategy(bool newlyCreated)
public Strategy(StrategyType mt)

Creates a Strategy. The parameterless constructor initializes the Strategy using the current StrategyFactory defaults and sets IsNewlyCreated to false. The second overload initializes the Strategy and sets IsNewlyCreated to the value of newlyCreated. The StrategyType overload creates a newly created Strategy of the specified type. For a Code Strategy, StrategyData is initialized with DefaultTemplateCode. For a Building Block Strategy, StrategyData is initialized with a new Building Block Strategy definition.



Copying Settings
AssignSettingsFrom
public void AssignSettingsFrom(Strategy s)

Copies backtest-related settings from Strategy s into this Strategy. The copied settings include:

  • PositionSize
  • DataRange
  • SingleSymbol
  • SingleSymbolMode
  • Benchmark
  • Scale
  • DataSetName
  • RetainNSF
  • UpdateGranularData
  • GranularLimitStopScale
  • PreferredValues PositionSize, DataRange, Scale, and PreferredValueList instances are cloned where appropriate.

Clone
public Strategy Clone(
bool preserveWLDownloadFlag)

Creates and returns a copy of the Strategy. The preserveWLDownloadFlag parameter determines whether WealthLab.com publication and user Strategy flags are preserved.


CopyFrom
public void CopyFrom(
Strategy source,
bool preserveWLDownloadFlag,
bool copySettingsOnly)

Copies information from source into this Strategy. When copySettingsOnly is false, Strategy identity, metadata, StrategyData, compiled Strategy information, and settings are copied. When copySettingsOnly is true, the operation primarily copies Strategy configuration while preserving the receiving Strategy's identity and Strategy definition. The preserveWLDownloadFlag parameter determines whether WealthLab.com-related Strategy flags are copied.



File and Read-Only State
FileName
public string FileName

Returns the full file name used by the current XML Strategy persistence format. The file extension is .xml.


FileNameLegacy
public string FileNameLegacy

Returns the full file name used by the legacy Strategy persistence format. The file extension is .txt.


IsLinkedToExternalFile
public bool IsLinkedToExternalFile

Gets or sets whether a C# Strategy is linked to an external source file.


IsNewlyCreated
public bool IsNewlyCreated

Gets or sets whether the Strategy has been newly created.


IsReadOnly
public bool IsReadOnly

Returns true if the Strategy is read-only. A Strategy is considered read-only if either IsWLComPublishedStrategy or MarkedReadOnly is true.


IsWLComPublishedStrategy
public bool IsWLComPublishedStrategy

Gets or sets whether the Strategy represents a published Strategy obtained from WealthLab.com.


IsWLComUserStrategy
public bool IsWLComUserStrategy

Gets or sets whether the Strategy represents a user's WealthLab.com Strategy.


LinkedFileName
public string LinkedFileName

Gets or sets the name of the external source file associated with the Strategy when IsLinkedToExternalFile is true.


MarkedReadOnly
public bool MarkedReadOnly

Gets or sets whether the Strategy has been explicitly marked read-only by the user.



Identity and Metadata
Author
public string Author

Gets or sets the WealthLab username of the Strategy's author.


CreationDate
public DateTime CreationDate

Gets or sets the date and time when the Strategy was created.


Description
public string Description

Gets or sets the Strategy description.


FolderName
public string FolderName

Gets or sets the name of the folder in which the Strategy is saved.


GlyphName
public string GlyphName

Returns the glyph resource associated with the Strategy's StrategyType. The returned glyph differs for Building Block, C# Code, Rotation, MetaStrategy, Compiled, and Trade History Strategies.


LastSaveDate
public DateTime LastSaveDate

Returns the Strategy's last save date. For non-compiled Strategies, WealthLab returns the last-write time of the Strategy file when available. Otherwise, the Strategy's CreationDate is returned.


LibraryName
public string LibraryName

Gets or sets the name of the assembly containing a compiled Strategy.


Name
public string Name

Gets or sets the Strategy name.


QualifiedName
public string QualifiedName

Returns the Strategy's qualified name. If FolderName is empty, this is simply Name. Otherwise, it is returned in the form:

FolderName\Name

Size
public int Size

Returns the length of StrategyData.


StrategyData
public string StrategyData

Gets or sets the serialized Strategy definition. For a C# Strategy, this contains the Strategy source code. For other Strategy types, it contains the persisted rules or configuration appropriate for that type.


StrategyType
public StrategyType StrategyType

Gets or sets the type of Strategy.


ToString
public override string ToString()

Returns the Strategy's QualifiedName.



Optimization
AssignParameterDefaults
public void AssignParameterDefaults(
List<double> values)

Assigns new default values to the Strategy's optimizable Parameters. The method updates the appropriate persisted Strategy representation according to StrategyType and assigns the supplied values to the compiled Strategy Parameters.


CanOptimize
public bool CanOptimize

Returns true if the Strategy can currently be optimized. The property returns true when PositionSize contains optimizable settings. Otherwise, the StrategyType must support optimization and the Strategy must contain one or more compiled Strategy Parameters.


CouldOptimize
public bool CouldOptimize

Gets or sets a persisted indication that the Strategy was capable of optimization.


GetOptimizedParameters
public ParameterList GetOptimizedParameters()

Returns a ParameterList containing the Strategy Parameters and any PositionSize Parameters that participate in optimization. If CompiledStrategy is null, an empty ParameterList is returned.


ParameterNames
public List<string> ParameterNames

Gets or sets the list of Strategy parameter names used when tracking optimization parameter state.


ParametersEnabled
public List<string> ParametersEnabled

Gets or sets the list of parameters that were enabled, or checked, for optimization.


ParameterValues
public List<double> ParameterValues

Contains persisted values for the compiled Strategy Parameters. This collection is used by the XML persistence mechanism to restore parameter values.


PreferredValues
public SerializableDictionary<string, PreferredValueList> PreferredValues

Contains the Preferred Values saved for the Strategy. The Dictionary is keyed by symbol.


RunWithPreferredValues
public bool RunWithPreferredValues

Gets or sets whether the Strategy should run using its saved Preferred Values.


RunWithWFOParameters
public bool RunWithWFOParameters

Gets or sets whether the Strategy should run using its saved Walk-Forward Optimization Parameters.


WFOParameters
public WFOParametersList WFOParameters

Gets or sets the saved Walk-Forward Optimization Parameters associated with the Strategy.



Persistence
Parse
public void Parse(string s)

Restores this Strategy from a string previously created by the legacy Persist method. The method restores Strategy metadata, StrategyData, DataSet and symbol settings, PositionSize, benchmark, optimization settings, granular processing settings, Preferred Values, external-file linkage, and other persisted state. For a compiled Strategy, the appropriate compiled Strategy instance is also created.


ParseXML
public static Strategy ParseXML(string xml)

Creates and returns a Strategy from its XML representation. The PositionSize's serialized advanced PositionSizer information is restored, and a compiled Strategy instance is created when appropriate.


Persist
public string Persist()

Returns the Strategy encoded using WealthLab's legacy tokenized persistence format. The persisted information includes Strategy metadata, StrategyData, backtest settings, PositionSize, symbol and DataSet configuration, optimization settings, Preferred Values, granular processing settings, external-file linkage, and parameter state.


PersistXML
public string PersistXML()

Returns an XML representation of the Strategy. Before serialization, the current compiled Strategy Parameter values are copied into ParameterValues, and PositionSize prepares any advanced PositionSizer information for XML serialization.


StateString
public string StateString

Returns the Strategy's current XML-persisted state as a trimmed string.