Skip to content

Commit

Permalink
Fix bullish-or-bearish Task
Browse files Browse the repository at this point in the history
  • Loading branch information
pantunes committed Oct 28, 2024
1 parent adc667d commit 62e3890
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 15 deletions.
59 changes: 47 additions & 12 deletions exchange_radar/scheduler/alerts/market_sentiment.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from abc import ABC, abstractmethod
from collections import defaultdict
from datetime import datetime

Expand All @@ -10,53 +11,79 @@

logger = logging.getLogger(__name__)

alerts_cache = defaultdict(dict)
alerts_cache = defaultdict(lambda: defaultdict(dict))

TASK_LOCK = "MARKET-SENTIMENT-LOCK"


class TaskConfig(ABC):
@property
@abstractmethod
def increase_in_percentage(self) -> float:
pass

@property
@abstractmethod
def frequency_in_minutes(self) -> int:
pass

def __str__(self) -> str:
return self.__class__.__name__


class EachSecondTaskConfig(TaskConfig):
increase_in_percentage = 2.0
frequency_in_minutes = 1


class Each10SecondsTaskConfig(TaskConfig):
increase_in_percentage = 4.0
frequency_in_minutes = 10


def _get_message(
key: str,
coin: str,
currency: str,
increase_in_percentage: float,
frequency_in_minutes: int,
*,
indicator: dict[str, int | float],
) -> str | None:
key, value = next(iter(indicator.items()))
indicator_key, indicator_value = next(iter(indicator.items()))

alerts_cache_coin = alerts_cache[coin]
alerts_cache_coin = alerts_cache[key][coin]

if alerts_cache_coin["currency"] != currency:
logger.info(f"Mismatch in Currency: {alerts_cache_coin['currency']} != {currency} for {coin}.")
return None

ratio = ((value / alerts_cache_coin[key]) - 1) * 100
ratio = ((indicator_value / alerts_cache_coin[indicator_key]) - 1) * 100
ratio_abs = abs(ratio)

if ratio_abs < increase_in_percentage:
logger.info(
f"No new {key.upper()} alerts for coin:{coin}; frequency_in_minutes:{frequency_in_minutes} ratio: {ratio}."
f"No new {indicator_key.upper()} alerts for coin:{coin}; frequency_in_minutes:{frequency_in_minutes} ratio: {ratio}."
)
return None

verb = "increased" if ratio > 0 else "decreased"
return f"The {key.upper()} {verb} {ratio_abs:.2f}% in the last {frequency_in_minutes} minute(s)"
return f"The {indicator_key.upper()} {verb} {ratio_abs:.2f}% in the last {frequency_in_minutes} minute(s)"


@huey.periodic_task(crontab(minute="*/1"))
@huey.lock_task(TASK_LOCK)
def bullish_or_bearish__1_min():
task(increase_in_percentage=1.0, frequency_in_minutes=1)
task(config=EachSecondTaskConfig())


@huey.periodic_task(crontab(minute="*/10"))
@huey.lock_task(TASK_LOCK)
def bullish_or_bearish__10_min():
task(increase_in_percentage=4.0, frequency_in_minutes=10)
task(config=Each10SecondsTaskConfig())


def task(*, increase_in_percentage: float, frequency_in_minutes: int):
def task(*, config: TaskConfig):
name = datetime.today().date().strftime("%Y-%m-%d")

with redis.pipeline() as pipe:
Expand Down Expand Up @@ -91,7 +118,9 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
logger.error(f"Error when parsing {coin} dataset: {error}")
break
else:
if coin in alerts_cache:
key = f"{name} {config}"

if key in alerts_cache and coin in alerts_cache[key]:

messages = []

Expand All @@ -100,7 +129,12 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
{"price": price},
):
message = _get_message(
coin, currency, increase_in_percentage, frequency_in_minutes, indicator=indicator
key,
coin,
currency,
config.increase_in_percentage,
config.frequency_in_minutes,
indicator=indicator,
)
if message:
logger.info(message)
Expand All @@ -110,6 +144,7 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):

for message in messages:
Alerts(
name=f"bullish-or-bearish-{config.frequency_in_minutes}",
time_ts=time_ts,
trade_symbol=coin,
price=price,
Expand All @@ -120,7 +155,7 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
else:
logger.info("Initializing Alerts...")

alerts_cache[coin] = {
alerts_cache[key][coin] = {
"volume": volume,
"volume_buy_orders": volume_buy_orders,
"volume_sell_orders": volume_sell_orders,
Expand Down
2 changes: 2 additions & 0 deletions exchange_radar/web/src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ def save_or_not(cls, coin: str, category: str, message: dict) -> bool:


class Alerts(JsonModel): # pragma: no cover
name: str
time_ts: int = Field(index=True, sortable=True)
trade_symbol: str = Field(index=True)
price: float
Expand All @@ -120,6 +121,7 @@ def rows(cls, trade_symbol: str) -> dict[str, list[str]]:
f"{datetime.fromtimestamp(item.time_ts)} | "
f"{trade_symbol.ljust(4)} | "
f"{f'{item.price:,.8f} {item.currency.rjust(4)}'.rjust(16 + 5, ' ')} | "
f"{item.name.ljust(21)} | "
f"{item.message}"
for item in query
]
Expand Down
6 changes: 3 additions & 3 deletions exchange_radar/web/templates/alerts.j2
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
<div class="padded">
<!-- box 1 content -->
<pre>
-----------------------------------------------------------------------------------
<b>DATETIME UTC | COIN | PRICE | ALERT</b>
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------
<b>DATETIME UTC | COIN | PRICE | ALERT | MESSAGE</b>
-------------------------------------------------------------------------------------------------------------------------------
<span id="messages"></span>


Expand Down

0 comments on commit 62e3890

Please sign in to comment.