QuantConnect / Lean

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)
https://lean.io
Apache License 2.0
9.46k stars 3.21k forks source link

Adds Algorithm Exception Handler #8239

Open AlexCatarino opened 1 month ago

AlexCatarino commented 1 month ago

Expected Behavior

Be able to take action when a runtime exception is raised.

Actual Behavior

If a runtime error occurs, we cannot take actions such as close positions and open orders.

Potential Solution

Add IAlgorithm.OnError method.

Reproducing the Problem

from AlgorithmImports import *
class FormalFluorescentYellowPenguin(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2024, 6, 30)
        self.add_crypto("BTCUSD")
    def on_data(self, data):
        x=1/0
    def on_end_of_algorithm(self):
        self.liquidate()

In this case, on_end_of_algorithm is not called, so we cannot close positions and open orders if we want to.

Checklist

keshavdalmia10 commented 3 weeks ago

Hi @AlexCatarino, @Martin-Molinero I have raised the pull request for this issue.

AlexCatarino commented 2 weeks ago

Hi @keshavdalmia10, Before you work on an issue, I suggest adding comments to show that you understand what needs to be done and what you will do, then wait for feedback. When someone (e.g. me) opens a GitHub issue for a feature request, they may not know what needs to be done or the best way to do it.

By the way, your https://github.com/QuantConnect/Lean/pull/8266 doesn't have a unit and/or a regression test to show it solves the issue.

keshavdalmia10 commented 2 weeks ago

Hi @keshavdalmia10, Before you work on an issue, I suggest adding comments to show that you understand what needs to be done and what you will do, then wait for feedback. When someone (e.g. me) opens a GitHub issue for a feature request, they may not know what needs to be done or the best way to do it.

By the way, your #8266 doesn't have a unit and/or a regression test to show it solves the issue.

I had pinged you on Discord for it.

keshavdalmia10 commented 2 weeks ago

Hi @Martin-Molinero , can you guide a little over here on how to make the test case for it?