Skip to content

Commit

Permalink
Resolve "self.close doesn't get called properly on exit"
Browse files Browse the repository at this point in the history
  • Loading branch information
btschwertfeger committed Jan 6, 2025
1 parent 821fac2 commit 3666164
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 35 deletions.
70 changes: 37 additions & 33 deletions src/kraken_infinity_grid/gridbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,42 +366,48 @@ async def __main(self: Self) -> None:
self.configuration.update({"last_price_time": datetime.now()})

# ======================================================================
# Main Loop: Run until any unexpected exception occur
# Main Loop: Run until interruption
##

# That is still the way to go, python-kraken-sdk will notify like this
# about failing connections.
while not self.exception_occur:
try:
conf = self.configuration.get()
last_hour = datetime.now() - timedelta(hours=1)

if self.init_done and (
not conf["last_price_time"]
or not conf["last_telegram_update"]
or conf["last_telegram_update"] < last_hour
):
# Send Update once per hour to Telegram
self.t.send_bot_update()

if conf["last_price_time"] < last_hour:
# Exit if no price update for a long time (6 minutes)
try:
# 'self.exception_occur' is how the python-kraken-sdk notifies about
# exceptions in the websocket connection.
while not self.exception_occur:
try:
conf = self.configuration.get()
now = datetime.now()
last_hour = now - timedelta(hours=1)

if self.init_done and (
not conf["last_price_time"]
or not conf["last_telegram_update"]
or conf["last_telegram_update"] < last_hour
):
# Send update once per hour to Telegram
self.t.send_bot_update()

if conf["last_price_time"] + timedelta(seconds=600) < now:
# Exit if no price update for a long time (10 minutes).
self.save_exit(
reason="No price update for a long time, exit!",
)

except (
Exception # pylint: disable=broad-exception-caught # noqa: BLE001
) as exc:
self.save_exit(
reason="No price update for a long time, exit!",
reason=f"Exception in main: {exc} {traceback.format_exc()}",
)

except (
Exception # pylint: disable=broad-exception-caught # noqa: BLE001
) as exc:
self.save_exit(
reason=f"Exception in main: {exc} {traceback.format_exc()}",
)

await asyncio.sleep(6)
await asyncio.sleep(6)

self.save_exit(
reason="The websocket connection encountered an exception!",
)
except asyncio.CancelledError:
await self.stop() # Stops the websocket connections
await self.async_close() # Stops the aiohttp session
self.save_exit("The algorithm was interrupted!")
else:
self.save_exit(
reason="The websocket connection encountered an exception!",
)

def save_exit(self: Self, reason: str = "") -> None:
"""Save exit triggered, saving data and exit the program."""
Expand All @@ -417,8 +423,6 @@ def save_exit(self: Self, reason: str = "") -> None:
LOG.warning("%s", message)
LOG.error("FIXME: look at this: %s: %s", exc, traceback.format_exc())

# FIXME: self.close must be called, but must be async which is not
# possible in this function.
sys.exit(1)

def __check_kraken_status(self: Self, tries: int = 0) -> None:
Expand Down
1 change: 1 addition & 0 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,5 @@ async def instance(config: dict, db_config: dict) -> KrakenInfinityGridBot:
},
}
yield instance
await instance.stop()
await instance.async_close()
6 changes: 4 additions & 2 deletions tests/test_gridbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def config() -> dict:


@pytest_asyncio.fixture
async def instance( # noqa: RUF029
async def instance(
config: dict,
db_config: dict,
) -> KrakenInfinityGridBot:
Expand All @@ -62,7 +62,9 @@ async def instance( # noqa: RUF029
instance.sm = mock.MagicMock(spec=SetupManager)
instance.om = mock.MagicMock(spec=OrderManager)
instance.unsold_buy_order_txids = mock.Mock(spec=UnsoldBuyOrderTXIDs)
return instance
yield instance
await instance.async_close()
await instance.stop()


# ==============================================================================
Expand Down

0 comments on commit 3666164

Please sign in to comment.