### Brokerage Class Implementation Example Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/creating-the-brokerage Example of a brokerage class implementing core LEAN interfaces. This structure is a starting point for integrating custom brokerage logic. ```csharp class MyBrokerage : Brokerage, IDataQueueHandler, IDataQueueUniverseProvider { ... } ``` -------------------------------- ### Example CSV Data Format Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models This is an example of the expected chronological order and format for CSV data inputs. ```csv 1997-01-01,905.2,941.4,905.2,939.55,38948210,978.21 1997-01-02,941.95,944,925.05,927.05,49118380,1150.42 1997-01-03,924.3,932.6,919.55,931.65,35263845,866.74 ... 2014-07-24,7796.25,7835.65,7771.65,7830.6,117608370,6271.45 2014-07-25,7828.2,7840.95,7748.6,7790.45,153936037,7827.61 2014-07-28,7792.9,7799.9,7722.65,7748.7,116534670,6107.78 ``` -------------------------------- ### Compile LEAN Solution on Linux Source: https://www.quantconnect.com/docs/v2/lean-engine/getting-started Use this command to compile the LEAN solution on Debian or Ubuntu systems after installing .NET 6. ```bash $ dotnet build QuantConnect.Lean.sln ``` -------------------------------- ### Initialize Map File Provider Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-csharp Initializes the map file provider using a local zip file and a default data provider. This is a setup step for processing data. ```csharp var mapFileProvider = new LocalZipMapFileProvider(); var mapFileProvider.Initialize(new DefaultDataProvider()); ``` -------------------------------- ### Example CSV Data Format Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models This is an example of the expected CSV file format for a custom dataset. The first column is the security identifier, and the second is the point-in-time ticker. ```text A R735QTJ8XC9X,A,17.19,109700,1885743,False,0.9904858,1 AA R735QTJ8XC9X,AA,71.25,513400,36579750,False,0.3992678,0.750075 AAB R735QTJ8XC9X,AAB,16.38,5000,81900,False,0.9902758,1 ... ZSEV R735QTJ8XC9X,ZSEV,10.5,800,8400,False,0.8981684,1 ZTR R735QTJ8XC9X,ZTR,9.56,102300,977988,False,0.0803037,3.97015016 ZVX R735QTJ8XC9X,ZVX,10,15600,156000,False,1,0.666667 ``` -------------------------------- ### Clone LEAN Engine Repository Source: https://www.quantconnect.com/docs/v2/lean-engine/getting-started Clone the LEAN Engine repository to your local machine using Git. This is the first step for local installation. ```bash $ git clone https://github.com/QuantConnect/Lean.git $ cd Lean ``` -------------------------------- ### Clone Data Source SDK Repository Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Clone the template repository to start building your custom data source. Ensure you replace placeholders with your specific dataset and vendor names. ```bash $ git clone https://github.com/username/Lean.DataSource..git ``` -------------------------------- ### Custom Data Point Indicator Implementation Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Implement a custom data point indicator inheriting from `IndicatorBase`. This example includes the `WarmUpPeriod` and `IsReady` properties, and the `ComputeNextValue` and `ValidateAndComputeNextValue` methods. ```C# public class CustomPointIndicator : IndicatorBase, IIndicatorWarmUpPeriodProvider { public int WarmUpPeriod = 2; public override bool IsReady => Samples >= WarmUpPeriod; protected override decimal ComputeNextValue(IndicatorDataPoint input) { return 1m; } protected virtual IndicatorResult ValidateAndComputeNextValue(IndicatorDataPoint input) { var indicatorValue = ComputeNextValue(input); return IsReady ? new IndicatorResult(indicatorValue) : new IndicatorResult(indicatorValue, IndicatorStatus.ValueNotReady); } } ``` -------------------------------- ### Custom Window Data Point Indicator Implementation Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Implement a custom data point indicator inheriting from `WindowIndicator`. This example demonstrates using the `IReadOnlyWindow` to compute values and includes the `ValidateAndComputeNextValue` method. ```C# public class CustomWindowIndicator : WindowIndicator { public int WarmUpPeriod => base.WarmUpPeriod; public override bool IsReady => base.IsReady; protected override decimal ComputeNextValue(IReadOnlyWindow window, IndicatorDataPoint input) { return window.Average(); } protected virtual IndicatorResult ValidateAndComputeNextValue(IndicatorDataPoint input) { var indicatorValue = ComputeNextValue(input); return IsReady ? new IndicatorResult(indicatorValue) : new IndicatorResult(indicatorValue, IndicatorStatus.InvalidInput); } } ``` -------------------------------- ### Build and Run LEAN Engine from Command Line Source: https://www.quantconnect.com/docs/v2/lean-engine/getting-started Build the LEAN Engine solution and run the launcher from the command line. This is an alternative to using an IDE for running the engine. ```bash $ dotnet build QuantConnect.Lean.sln $ cd Lean/Launcher/bin/Debug $ dotnet QuantConnect.Lean.Launcher.dll ``` -------------------------------- ### Build and Run Unit Tests Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/testing-data-models Build the test project and execute unit tests for your demonstration algorithm. This ensures the data model and algorithm logic function correctly. ```bash $ dotnet build tests/Tests.csproj $ dotnet test tests/bin/Debug/net9.0/Tests.dll ``` -------------------------------- ### Run LEAN Launcher on Linux Source: https://www.quantconnect.com/docs/v2/lean-engine/getting-started Navigate to the compiled output directory and run the LEAN Launcher executable on Linux systems. ```bash $ cd Launcher/bin/Debug $ dotnet QuantConnect.Lean.Launcher.dll ``` -------------------------------- ### Clone Brokerage Repository Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/setting-up-your-environment Clone your forked brokerage repository to your local machine to begin development. ```bash $ git clone https://github.com/username/Lean.Brokerages..git ``` -------------------------------- ### Initialize Map File Provider and Data Provider Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-python Create and initialize a map file provider and a default data provider. These are essential for resolving security identifiers and fetching data. ```python map_file_provider = LocalZipMapFileProvider() map_file_provider.Initialize(DefaultDataProvider()) ``` -------------------------------- ### Configure LEAN for C# Algorithm Backtesting Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/testing-data-models Set the algorithm type name, language, and location in the config.json file to backtest a C# demonstration algorithm. ```json "algorithm-type-name": "Algorithm", "algorithm-language": "CSharp", "algorithm-location": "QuantConnect.Algorithm.CSharp.dll" ``` -------------------------------- ### Initialize Map File Provider Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-notebooks Creates and initializes a map file provider using LocalZipMapFileProvider and DefaultDataProvider. This is used for security identifier generation. ```python map_file_provider = LocalZipMapFileProvider() map_file_provider.Initialize(DefaultDataProvider()) ``` -------------------------------- ### Live Brokerage Environment Configuration Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/laying-the-foundation Configure the live trading environment for your brokerage in config.json. Replace 'brokerage-name' and 'BrokerageName' with your specific brokerage details. ```json // defines the 'live-brokerage-name' environment "live-brokerage-name": { "live-mode": true, "live-mode-brokerage": "BrokerageName", "setup-handler": "QuantConnect.Lean.Engine.Setup.BrokerageSetupHandler", "result-handler": "QuantConnect.Lean.Engine.Results.LiveTradingResultHandler", "data-feed-handler": "QuantConnect.Lean.Engine.DataFeeds.LiveTradingDataFeed", "data-queue-handler": [ "QuantConnect.Lean.Engine.DataFeeds.Queues.LiveDataQueue" ], "real-time-handler": "QuantConnect.Lean.Engine.RealTime.LiveTradingRealTimeHandler", "transaction-handler": "QuantConnect.Lean.Engine.TransactionHandlers.BacktestingTransactionHandler" } ``` -------------------------------- ### Instantiate Custom Moving Average Indicator Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Demonstrates how to instantiate a custom moving average indicator and assert its type. This is useful when you need a specific moving average calculation not provided by default. ```csharp indicator = MovingAverageType.CustomMovingAverageEnum.AsIndicator(name, 1); Assert.IsInstanceOf(typeof(CustomMovingAverage), indicator); ``` -------------------------------- ### Configure LEAN for Python Algorithm Backtesting Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/testing-data-models Set the algorithm type name, language, and location in the config.json file to backtest a Python demonstration algorithm. Ensure the algorithm location path is correct relative to the LEAN directory. ```json "algorithm-type-name": "Algorithm", "algorithm-language": "Python", "algorithm-location": "../../../Algorithm.Python/Algorithm.py" ``` -------------------------------- ### Helper Method for Automatic Indicator Registration Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Add a helper method to QCAlgorithm.Indicators.cs to automatically create and register custom indicators. This method calls InitializeIndicator to set up the consolidator and data updates. ```csharp public CustomIndicator CI(Symbol symbol, Resolution? resolution = null, Func selector = null) { var name = CreateIndicatorName(symbol, $"CI()", resolution); var ci = new CustomIndicator(name, symbol); InitializeIndicator(symbol, ci, resolution, selector); return ci; } ``` -------------------------------- ### Stub Brokerage Model Implementation Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/laying-the-foundation Use this stub implementation for a new brokerage model. Replace 'BrokerageName' with your specific brokerage name. ```csharp public class BrokerageNameBrokerageModel : DefaultBrokerageModel { } ``` -------------------------------- ### Define Data Source Class - SupportedResolutions Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the SupportedResolutions method to declare the data resolutions your dataset supports. Universe data must have hour or daily resolution. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override List SupportedResolutions() { return DailyResolution; } } ``` -------------------------------- ### Clone LEAN Repository Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/testing-data-models Clone the LEAN repository if you do not have a local copy. This is a prerequisite for integrating custom data models. ```bash $ git clone https://github.com//Lean.git ``` -------------------------------- ### Run Brokerage Renaming Script Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/setting-up-your-environment Execute the renameBrokerage.sh script to update placeholder text and file names within your new brokerage project. ```bash $ renameBrokerage.sh ``` -------------------------------- ### Define Clone Method Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `Clone` method to create a deep copy of your data instance. Ensure all relevant properties, including custom ones, are copied. ```C# public class VendorNameDatasetName : BaseData { public override BaseData Clone() { return new VendorNameDatasetName { Symbol = Symbol, Time = Time, EndTime = EndTime, SomeCustomProperty = SomeCustomProperty, }; } } ``` -------------------------------- ### Add Test Data File to Project Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Include a CSV file containing third-party testing values in the Lean project. Ensure it's copied to the output directory. ```xml PreserveNewest ``` -------------------------------- ### Define Data Source Class - Clone Method Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the Clone method to create a deep copy of your data instance. This is essential for maintaining data integrity when multiple instances are needed. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override BaseData Clone() { return new VendorNameDatasetName { Symbol = Symbol, Time = Time, EndTime = EndTime, SomeCustomProperty = SomeCustomProperty, }; } } ``` -------------------------------- ### Define Data Source Class - DefaultResolution Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the DefaultResolution method to specify the default resolution for your dataset. Lean uses this when a member does not specify a resolution. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override Resolution DefaultResolution() { return Resolution.Daily; } } ``` -------------------------------- ### Define Supported Resolutions Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `SupportedResolutions` method to declare the data resolutions your dataset supports. `DailyResolution` is a common choice. ```C# public class VendorNameDatasetName : BaseData { public override List SupportedResolutions() { return DailyResolution; } } ``` -------------------------------- ### Run Python Data Processing Script Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-python Execute the Python processing script from the bin directory to populate the output directories. This script transforms raw data into the format expected by Lean. ```bash $ cd DataProcessing/bin/debug/net9.0/ $ python process.py ``` -------------------------------- ### Test IsReady Flag Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Verify that the IsReady flag is correctly set after the indicator receives its first update. ```csharp namespace QuantConnect.Tests.Indicators { [TestFixture] public class CustomIndicatorTests : CommonIndicatorTests { protected override IndicatorBase CreateIndicator() { return new CustomIndicator(); } protected override string TestFileName => "custom_3rd_party_data.csv"; protected override string TestColumnName => "CustomIndicatorValueColumn"; // How do you compare the values protected override Action, double> Assertion { get { return (indicator, expected) => Assert.AreEqual(expected, (double)indicator.Current.Value, 1e-4); } // allow 0.0001 error margin of indicator values } [Test] public void IsReadyAfterPeriodUpdates() { var ci = CreateIndicator(); Assert.IsFalse(ci.IsReady); ci.Update(DateTime.UtcNow, 1m); Assert.IsTrue(ci.IsReady); } [Test] public override void ResetsProperly() { var ci = CreateIndicator(); ci.Update(DateTime.UtcNow, 1m); Assert.IsTrue(ci.IsReady); ci.Reset(); TestHelper.AssertIndicatorIsInDefaultState(ci); } } } ``` -------------------------------- ### Implement Custom Moving Average in AsIndicator Method Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Extend the MovingAverageTypeExtensions.cs file by adding a new case to the AsIndicator methods. This ensures your custom moving average can be instantiated through the abstraction. ```C# namespace QuantConnect.Indicators { public static class MovingAverageTypeExtensions { public static IndicatorBase AsIndicator(this MovingAverageType movingAverageType, int period) { switch (movingAverageType) { ... case MovingAverageType.CustomMovingAverageEnum: return new CustomMovingAverage(period); } } public static IndicatorBase AsIndicator(this MovingAverageType movingAverageType, string name, int period) { switch (movingAverageType) { ... case MovingAverageType.CustomMovingAverageEnum: return new CustomMovingAverage(name, period); } } } } ``` -------------------------------- ### Calculate Market Capacity Dollar Volume (C#) Source: https://www.quantconnect.com/docs/v2/lean-engine/statistics/capacity This snippet calculates the market capacity dollar volume for a security after each order fill. It uses bar data, a trading volume discount factor, and security properties. Ensure the necessary variables like _marketCapacityDollarVolume, _fastTradingVolumeDiscountFactor, conversionRate, and Security.SymbolProperties.ContractMultiplier are defined. ```csharp _marketCapacityDollarVolume += bar.Close * _fastTradingVolumeDiscountFactor * bar.Volume * conversionRate * Security.SymbolProperties.ContractMultiplier; ``` -------------------------------- ### Custom TradeBar Indicator Definition Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Create a custom trade bar indicator by extending TradeBarIndicator and implementing IIndicatorWarmUpPeriodProvider. The IsReady property should check the number of samples against the WarmUpPeriod. ```csharp public class CustomTradeBarIndicator : TradeBarIndicator, IIndicatorWarmUpPeriodProvider { public int WarmUpPeriod = 2; public override bool IsReady => Samples >= WarmUpPeriod; protected override decimal ComputeNextValue(TradeBar input) { return 1m; } protected virtual IndicatorResult ValidateAndComputeNextValue(TradeBar input) { var indicatorValue = ComputeNextValue(input); return IsReady ? new IndicatorResult(indicatorValue) : new IndicatorResult(indicatorValue, IndicatorStatus.ValueNotReady); } } ``` -------------------------------- ### Add Data Using Helper Class (C#) Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Subscribe to a specific data series using its enum member from a helper class. This is preferred over using the raw series code. ```csharp AddData(Fred.LIBOR.OneWeekBasedOnUSD); // Instead of // AddData("USD1WKD156N"); ``` -------------------------------- ### Define GetBrokerageModel Method Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/laying-the-foundation Implement the GetBrokerageModel method in the BrokerageFactory to return an instance of your new brokerage model. ```csharp public override IBrokerageModel GetBrokerageModel(IOrderProvider orderProvider) { return new BrokerageNameBrokerageModel(); } ``` -------------------------------- ### Add Data Using Helper Class (Python) Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Subscribe to a specific data series using its enum member from a helper class in Python. This is preferred over using the raw series code. ```python self.add_data(Fred, Fred.LIBOR.one_week_based_on_usd) # Instead of ``` -------------------------------- ### Compile Data Processing Project Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-python Compile the C# data processing project using dotnet CLI. This step is necessary to generate files used by the CLRImports library. ```bash $ dotnet build .\DataProcessing\DataProcessing.csproj ``` -------------------------------- ### Update LEAN Repository Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/testing-data-models Pull the latest changes to your local copy of the LEAN engine. Ensure you have the most recent version before proceeding with data model integration. ```bash $ git pull upstream master ``` -------------------------------- ### Define ToString Method Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `ToString` method for a custom string representation of your data instance. This is useful for debugging and logging. ```C# public class VendorNameDatasetName : BaseData { public override string ToString() { return $"{Symbol} - {SomeCustomProperty}"; } } ``` -------------------------------- ### Set Brokerage Model for Kraken Source: https://www.quantconnect.com/docs/v2/lean-engine Sets the brokerage model for Kraken, supporting both Cash and Margin account types. This is useful for configuring trading interactions with the Kraken exchange. ```Python SetBrokerageModel(BrokerageName.Kraken, AccountType.Cash); SetBrokerageModel(BrokerageName.Kraken, AccountType.Margin); self.set_brokerage_model(BrokerageName.KRAKEN, AccountType.CASH) self.set_brokerage_model(BrokerageName.KRAKEN, AccountType.MARGIN) ``` -------------------------------- ### Add Test Case for Custom Moving Average Instantiation Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators In MovingAverageTypeExtensionsTests.cs, create a new test case to verify that your custom moving average indicator is correctly instantiated using the AsIndicator methods. ```C# namespace QuantConnect.Tests.Indicators { [TestFixture] public class MovingAverageTypeExtensionsTests { [Test] public void CreatesCorrectAveragingIndicator() { ... var indicator = MovingAverageType.CustomMovingAverageEnum.AsIndicator(1); Assert.IsInstanceOf(typeof(CustomMovingAverage), indicator); ... string name = string.Empty; ... } } } ``` -------------------------------- ### Define Default Resolution Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `DefaultResolution` method to set the default data resolution for your dataset. `Resolution.Daily` is used if no resolution is specified by the user. ```C# public class VendorNameDatasetName : BaseData { public override Resolution DefaultResolution() { return Resolution.Daily; } } ``` -------------------------------- ### Define ToString Method for Custom Universe Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `ToString` method in a custom universe class to provide a meaningful string representation of the data, including symbol and custom properties. This is useful for debugging and logging. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override string ToString() { return $"{Symbol} - {SomeCustomProperty}"; } } ``` -------------------------------- ### IndicatorInfo Dictionary Entry Format Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators This is the standard format for adding an indicator to the `indicators`, `special_indicators`, or `option_indicators` dictionaries in the `IndicatorImageGenerator.py` file. It specifies the Python constructor, C# helper method, and Python helper method for the indicator. ```Python '': IndicatorInfo( (), '()', 'self.()' ), ``` -------------------------------- ### Copy Python Processing Script Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-python Copy the Python processing script to the bin directory of the data processing project. This ensures that LEAN's packages DLLs are correctly loaded for CLRImports. ```bash $ cp process.py DataProcessing/bin/Debug/net9.0 ``` -------------------------------- ### Run Dataset Renaming Script Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Execute the renameDataset.sh script to automatically update placeholder text and file names within your new dataset repository. This script customizes the SDK template for your specific dataset. ```bash $ renameDataset.sh ``` -------------------------------- ### Define Data Source Class - DataTimeZone Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the DataTimeZone method to specify the time zone for your dataset. QuantConnect's TimeZones class provides helpers like TimeZones.Utc or TimeZones.NewYork. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override DateTimeZone DataTimeZone() { return DateTimeZone.Utc; } } ``` -------------------------------- ### Define Data Time Zone Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `DataTimeZone` method to specify the time zone of your dataset. Use `DateTimeZone.Utc` for UTC time. ```C# public class VendorNameDatasetName : BaseData { public override DateTimeZone DataTimeZone() { return DateTimeZone.Utc; } } ``` -------------------------------- ### Set Execute Permissions for Bash Script Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/brokerages/setting-up-your-environment On Linux, grant execute permissions to the renameBrokerage bash script before running it. ```bash $ chmod +x ./renameBrokerage ``` -------------------------------- ### Import CLRImports Library Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-python Import the CLRImports library in your Python processing script. This library provides access to .NET functionalities within Python. ```python from CLRImports import * ``` -------------------------------- ### Define Data Source Class - RequiresMapping Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the RequiresMapping method to indicate whether your dataset requires mapping. This is typically set to true if your dataset uses custom security identifiers. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override bool RequiresMapping() { return true; } } ``` -------------------------------- ### Custom Bar Indicator Definition Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Define a custom bar indicator by inheriting from BarIndicator and implementing IIndicatorWarmUpPeriodProvider. Ensure the IsReady property checks against the WarmUpPeriod. ```csharp public class CustomBarIndicator : BarIndicator, IIndicatorWarmUpPeriodProvider { public int WarmUpPeriod = 2; public override bool IsReady => Samples >= WarmUpPeriod; protected override decimal ComputeNextValue(IBaseDataBar input) { return 1m; } protected virtual IndicatorResult ValidateAndComputeNextValue(IBaseDataBar input) { var indicatorValue = ComputeNextValue(input); return IsReady ? new IndicatorResult(indicatorValue) : new IndicatorResult(indicatorValue, IndicatorStatus.ValueNotReady); } } ``` -------------------------------- ### Generate Equity Security Identifier Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-python Generate an equity security identifier using the SecurityIdentifier class. This requires the point-in-time ticker, market, map file provider, and the CSV date. ```python sid = SecurityIdentifier.generate_equity(point_in_time_ticker, Market.USA, True, map_file_provider, csv_date) ``` -------------------------------- ### Define Data Source Class - IsSparseData Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the IsSparseData method to indicate if your dataset is sparse. Sparse datasets, which are missing data for at least one sample (and are not tick resolution), have logging for missing files disabled. ```csharp public class VendorNameDatasetNameUniverse : BaseData { public override bool IsSparseData() { return true; } } ``` -------------------------------- ### Custom Indicator Test Class Structure Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Define a test class inheriting from CommonIndicatorTests to test custom indicators. Specify the test file name, column name, and assertion logic. ```csharp namespace QuantConnect.Tests.Indicators { [TestFixture] public class CustomIndicatorTests : CommonIndicatorTests { protected override IndicatorBase CreateIndicator() { return new CustomIndicator(); } protected override string TestFileName => "custom_3rd_party_data.csv"; protected override string TestColumnName => "CustomIndicatorValueColumn"; // How do you compare the values protected override Action, double> Assertion { get { return (indicator, expected) => Assert.AreEqual(expected, (double)indicator.Current.Value, 1e-4); } // allow 0.0001 error margin of indicator values } } } ``` -------------------------------- ### Define Requires Mapping Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `RequiresMapping` method to indicate if your dataset requires symbol mapping. Return `true` if mapping is necessary. ```C# public class VendorNameDatasetName : BaseData { public override bool RequiresMapping() { return true; } } ``` -------------------------------- ### Generate Equity Security Identifier Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/rendering-data/rendering-data-with-csharp Generates a security identifier for an equity. This requires the point-in-time ticker, market, map file provider, and the CSV date. ```csharp var sid = SecurityIdentifier.GenerateEquity(pointInIimeTicker, Market.USA, true, mapFileProvider, csvDate) ``` -------------------------------- ### Set Execute Permissions for Bash Script Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models On Linux systems, grant execute permissions to the renameDataset bash script before running it. This is a necessary step for the script to function correctly. ```bash $ chmod +x ./renameDataset ``` -------------------------------- ### Accumulate Sale Volume Source: https://www.quantconnect.com/docs/v2/lean-engine/statistics/capacity Accumulates the weekly sale volume for a security, which is used to scale down weekly snapshot capacity. This is part of the Sale Volume calculation. ```csharp SaleVolume += orderEvent.FillPrice * orderEvent.AbsoluteFillQuantity * Security.SymbolProperties.ContractMultiplier; ``` -------------------------------- ### Define Sparse Data Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/datasets/defining-data-models Implement the `IsSparseData` method to indicate if your dataset is sparse (missing data points). Set to `true` if the dataset is not tick resolution and has missing data. ```C# public class VendorNameDatasetName : BaseData { public override bool IsSparseData() { return true; } } ``` -------------------------------- ### Define Custom Moving Average Enum Member Source: https://www.quantconnect.com/docs/v2/lean-engine/contributions/indicators Add a new enumeration member to the MovingAverageType enum in MovingAverageType.cs. This defines the identifier for your custom moving average. ```C# namespace QuantConnect.Indicators { public enum MovingAverageType { ... /// /// Description of the custom moving average indicator () /// , } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.