diff --git a/Algorithm/QCAlgorithm.cs b/Algorithm/QCAlgorithm.cs index 7c965df2bdc5..a4cc9d795fcf 100644 --- a/Algorithm/QCAlgorithm.cs +++ b/Algorithm/QCAlgorithm.cs @@ -3367,5 +3367,15 @@ public void SetStatisticsService(IStatisticsService statisticsService) _statisticsService = statisticsService; } } + + /// + /// Handles the error event in the algorithm + /// + /// The statistics service instance + public void OnError(Exception exception) + { + DebugMessages.Enqueue(exception.ToString()); + Liquidate(); + } } } diff --git a/AlgorithmFactory/Python/Wrappers/AlgorithmPythonWrapper.cs b/AlgorithmFactory/Python/Wrappers/AlgorithmPythonWrapper.cs index 68681ac269f7..343824f95188 100644 --- a/AlgorithmFactory/Python/Wrappers/AlgorithmPythonWrapper.cs +++ b/AlgorithmFactory/Python/Wrappers/AlgorithmPythonWrapper.cs @@ -65,6 +65,7 @@ public class AlgorithmPythonWrapper : BasePythonWrapper, IAlgorithm private dynamic _onAssignmentOrderEvent; private dynamic _onSecuritiesChanged; private dynamic _onFrameworkSecuritiesChanged; + private dynamic _onError; /// /// True if the underlying python algorithm implements "OnEndOfDay" @@ -120,6 +121,7 @@ public AlgorithmPythonWrapper(string moduleName) // determines whether OnData method was defined or inherits from QCAlgorithm // If it is not, OnData from the base class will not be called _onData = _algorithm.GetPythonMethod("OnData"); + _onError = _algorithm.GetPythonMethod("OnError"); _onMarginCall = _algorithm.GetPythonMethod("OnMarginCall"); @@ -1242,5 +1244,25 @@ public void SetTags(HashSet tags) { _baseAlgorithm.SetTags(tags); } + + /// + /// Handles exceptions thrown during the execution of the algorithm. + /// + /// The exception that was thrown + public void OnError(Exception exception) + { + if (_onError != null) + { + using (Py.GIL()) + { + _onError(exception); + } + } + else + { + // Default error handling if no custom OnError method is defined + Console.WriteLine($"Unhandled exception: {exception}"); + } + } } } diff --git a/Common/Interfaces/IAlgorithm.cs b/Common/Interfaces/IAlgorithm.cs index b1d37fe867ca..d115cc2014d0 100644 --- a/Common/Interfaces/IAlgorithm.cs +++ b/Common/Interfaces/IAlgorithm.cs @@ -919,5 +919,12 @@ Security AddSecurity(Symbol symbol, Resolution? resolution = null, bool fillForw /// /// The tags void SetTags(HashSet tags); + + /// + /// Method to handle runtime errors. + /// + /// The exception that occurred. + void OnError(Exception exception); + } }