Skip to content

Commit

Permalink
feat(Strategy): implement price caching during execution for consistency
Browse files Browse the repository at this point in the history
- Added a caching mechanism for the current price during strategy execution to ensure consistent price retrieval.
- Introduced a new attribute `_cached_price` to store the price at the start of execution and return it during execution cycles.
- Cleared the cached price after execution to maintain state integrity.
  • Loading branch information
saleh-mir committed Dec 23, 2024
1 parent 615e355 commit 7a406e4
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion jesse/strategies/Strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ def __init__(self) -> None:
self._cached_methods = {}
self._cached_metrics = {}

# Add cached price
self._cached_price = None

def add_line_to_candle_chart(self, title: str, value: float, color=None) -> None:
# validate value's type
if not isinstance(value, (int, float)):
Expand Down Expand Up @@ -967,12 +970,17 @@ def _execute(self) -> None:
return

self._is_executing = True


# Cache the current price at the start of execution
self._cached_price = self.close

self.before()
self._check()
self.after()
self._clear_cached_methods()

# Clear the cached price
self._cached_price = None
self._is_executing = False
self.index += 1

Expand Down Expand Up @@ -1070,10 +1078,15 @@ def close(self) -> float:
def price(self) -> float:
"""
Same as self.close, except in livetrade, this is rounded as the exchanges require it.
During strategy execution cycles, returns cached price to ensure consistency.
Returns:
[float] -- the current trading candle's current(close) price
"""
# Return cached price if we're executing
if self._is_executing and self._cached_price is not None:
return self._cached_price

return self.close

@property
Expand Down

0 comments on commit 7a406e4

Please sign in to comment.