Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache expensive strategy methods #174

Merged
merged 1 commit into from
Apr 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions jesse/strategies/Strategy.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
from functools import cache
from time import sleep
from typing import List

Expand Down Expand Up @@ -58,6 +59,7 @@ def __init__(self) -> None:
self.position: Position = None
self.broker = None

self._cached_methods = {}
self._cached_metrics = {}

def _init_objects(self) -> None:
Expand Down Expand Up @@ -822,6 +824,7 @@ def _execute(self) -> None:
self.before()
self._check()
self.after()
self._clear_cached_methods()

self._is_executing = False
self.index += 1
Expand Down Expand Up @@ -873,6 +876,10 @@ def watch_list(self) -> list:
"""
return []

def _clear_cached_methods(self) -> None:
for m in self._cached_methods.values():
m.cache_clear()

@property
def current_candle(self) -> np.ndarray:
"""
Expand Down Expand Up @@ -1191,3 +1198,13 @@ def leverage(self) -> int:
return self.position.exchange.futures_leverage
else:
raise ValueError('exchange type not supported!')


def cached(method):
def decorated(self, *args, **kwargs):
cached_method = self._cached_methods.get(method)
if cached_method is None:
cached_method = cache(method)
self._cached_methods[method] = cached_method
return cached_method(self, *args, **kwargs)
return decorated
2 changes: 1 addition & 1 deletion jesse/strategies/__init__.py
@@ -1 +1 @@
from .Strategy import Strategy
from .Strategy import cached, Strategy