In an effort to increase backtesting speed, I would like to convert my custom Python indicator to C#, just like how the built-in indicators are in C#. While I'm able to write the custom indicator in C# no problem, I can't find any documentation or community discussions on how to register and use it in a Python strategy. Is this supported and how can I do it? Thanks!
Mia Alissi
To integrate a custom C# indicator into a Python strategy on QuantConnect, follow these steps:
Develop the C# Indicator: Write your custom indicator in C#. It should inherit from an appropriate base class such as
IndicatorBase<IndicatorDataPoint>
or any other specific indicator base class if applicable.Compile the C# Indicator: Use an IDE, like Visual Studio, to create a Class Library project. Add your C# indicator code to this project and compile it to produce a DLL file. Ensure your indicator's logic is correct, such as using a method to compute averages over the
RollingWindow
, as shown here:Upload the DLL to QuantConnect: After compiling, upload the DLL file to your QuantConnect project. Use the "Add Existing File" feature in the QuantConnect IDE to upload it.
Import C# Namespace in Python: In your Python strategy, use
clr.AddReference
to load your DLL and import the namespace containing your indicator:Initialize and Register the Indicator in Python:
After importing, create an instance of your C# indicator in your Python algorithm and use the
register_indicator
method to attach the indicator to a data stream. Specify the resolution or use a selector to customize the data the indicator receives.By following these steps, you can effectively use a custom C# indicator in your QuantConnect Python strategy, benefiting from both the performance of C# and the flexibility of using Python for strategy development.
Sources: Custom Indicators - QuantConnect.com, Custom Indicators - QuantConnect.com, Combining Indicators - QuantConnect.com, Custom Indicator Algorithm, Indicator Suite Algorithm
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Lance Kersey
Thanks. I was able to compile a DLL in Visual Studio called CSharpIndicators.dll with namespace QuantConnect.Indicators and an internal Indicator class called HigherHighLowerLow. I added the DLL to my project's root path (Right Click in the workspace explorer ->Upload…), then used the following lines to import
Unfortunately this results in the below error, where it cannot find the CSharpIndicators file. Do you have any suggestions to resolve this error? The only examples of clr.AddReference() I can find are referencing LEAN libraries. If I add a statement such as clr.AddReference("QuantConnect.Algorithm") it works fine, so I suspect AddReference isn't looking in the correct location for my custom library and I somehow need to tell it to look in my project's workspace. Do you know how I can do that?
Algorithm.Initialize() Error: During the algorithm initialization, the following exception has occurred: Loader.TryCreatePythonAlgorithm(): Unable to import python module ./cache/algorithm/project/main.pyc. AlgorithmPythonWrapper(): Could not load file or assembly 'CSharpIndicators, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
at <module>
clr.AddReference("CSharpIndicators")
in main.py: line 12
Could not load file or assembly 'CSharpIndicators, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
Stack Trace: During the algorithm initialization, the following exception has occurred: Loader.TryCreatePythonAlgorithm(): Unable to import python module ./cache/algorithm/project/main.pyc. AlgorithmPythonWrapper(): Could not load file or assembly 'CSharpIndicators, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
at <module>
clr.AddReference("CSharpIndicators")
in main.py: line 12
Could not load file or assembly 'CSharpIndicators, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
Lance Kersey
An interesting observation is that when I upload the DLL file to the QuantConnect workspace, if I close and re-open the project the file is no longer there. This issue does not occur with Python files. I'm starting to suspect importing custom libraries (or possibly any file not listed under the Supported File Types) isn't supported in the cloud IDE, and maybe this will only work locally.
Lance Kersey
Note: I tried importing the DLL locally for a local backtest and it also didn't work. I put the DLL folder in the system path, tried using sys.path.append() in the code, tried putting the DLL in the project root folder as well as the QuantConnect workspace folder. Nothing worked. I supposed it's possible something is wrong or incompatible with the DLL, but in that case the error message “The system cannot find the file specified” is very misleading.
At this point I've wasted nearly the whole day on this so I'll probably just live with the performance hit of Python custom indicators. If anyone figures this out, please let me know.
Lance Kersey
It looks like the import works for local backtests (but not cloud backtests) if I take one of the LEAN dll's (ex QuantConnect.Indicators.dll), rename it to CSharpIndicators.dll, and put it in the root folder of the project. Then the statement like this works:
clr.AddReference("CSharpIndicators")
It doesn't seem to work in subdirectories, even if added to the PATH. In any case, this likely confirms some issue with how my custom DLL is compiled, rather than an issue with importing. But it also seems to confirm this can't be done with cloud backtests anyways, which means I can't see any of the custom graphs without porting all that over to a local solution. Too bad
If anyone wants to know how I created the DLL, I installed Visual Studio (ie not Visual Studio Code), selected desktop C# during the install, created a Class Library project targeting .NET 9.0 as that's what LEAN uses, copied an existing C# indicator source file just as a test, compiled, and imported the dll output under bin\Debug. If anyone knows what I might have missed that made the DLL not work properly with LEAN, please let me know.
Hopefully these notes save someone else some time in the future. If you are reading this, good luck!
Lance Kersey
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!