Skip to content

Commit 62e3890

Browse files
committed
Fix bullish-or-bearish Task
1 parent adc667d commit 62e3890

File tree

3 files changed

+52
-15
lines changed

3 files changed

+52
-15
lines changed

exchange_radar/scheduler/alerts/market_sentiment.py

+47-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from abc import ABC, abstractmethod
23
from collections import defaultdict
34
from datetime import datetime
45

@@ -10,53 +11,79 @@
1011

1112
logger = logging.getLogger(__name__)
1213

13-
alerts_cache = defaultdict(dict)
14+
alerts_cache = defaultdict(lambda: defaultdict(dict))
1415

1516
TASK_LOCK = "MARKET-SENTIMENT-LOCK"
1617

1718

19+
class TaskConfig(ABC):
20+
@property
21+
@abstractmethod
22+
def increase_in_percentage(self) -> float:
23+
pass
24+
25+
@property
26+
@abstractmethod
27+
def frequency_in_minutes(self) -> int:
28+
pass
29+
30+
def __str__(self) -> str:
31+
return self.__class__.__name__
32+
33+
34+
class EachSecondTaskConfig(TaskConfig):
35+
increase_in_percentage = 2.0
36+
frequency_in_minutes = 1
37+
38+
39+
class Each10SecondsTaskConfig(TaskConfig):
40+
increase_in_percentage = 4.0
41+
frequency_in_minutes = 10
42+
43+
1844
def _get_message(
45+
key: str,
1946
coin: str,
2047
currency: str,
2148
increase_in_percentage: float,
2249
frequency_in_minutes: int,
2350
*,
2451
indicator: dict[str, int | float],
2552
) -> str | None:
26-
key, value = next(iter(indicator.items()))
53+
indicator_key, indicator_value = next(iter(indicator.items()))
2754

28-
alerts_cache_coin = alerts_cache[coin]
55+
alerts_cache_coin = alerts_cache[key][coin]
2956

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

34-
ratio = ((value / alerts_cache_coin[key]) - 1) * 100
61+
ratio = ((indicator_value / alerts_cache_coin[indicator_key]) - 1) * 100
3562
ratio_abs = abs(ratio)
3663

3764
if ratio_abs < increase_in_percentage:
3865
logger.info(
39-
f"No new {key.upper()} alerts for coin:{coin}; frequency_in_minutes:{frequency_in_minutes} ratio: {ratio}."
66+
f"No new {indicator_key.upper()} alerts for coin:{coin}; frequency_in_minutes:{frequency_in_minutes} ratio: {ratio}."
4067
)
4168
return None
4269

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

4673

4774
@huey.periodic_task(crontab(minute="*/1"))
4875
@huey.lock_task(TASK_LOCK)
4976
def bullish_or_bearish__1_min():
50-
task(increase_in_percentage=1.0, frequency_in_minutes=1)
77+
task(config=EachSecondTaskConfig())
5178

5279

5380
@huey.periodic_task(crontab(minute="*/10"))
5481
@huey.lock_task(TASK_LOCK)
5582
def bullish_or_bearish__10_min():
56-
task(increase_in_percentage=4.0, frequency_in_minutes=10)
83+
task(config=Each10SecondsTaskConfig())
5784

5885

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

6289
with redis.pipeline() as pipe:
@@ -91,7 +118,9 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
91118
logger.error(f"Error when parsing {coin} dataset: {error}")
92119
break
93120
else:
94-
if coin in alerts_cache:
121+
key = f"{name} {config}"
122+
123+
if key in alerts_cache and coin in alerts_cache[key]:
95124

96125
messages = []
97126

@@ -100,7 +129,12 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
100129
{"price": price},
101130
):
102131
message = _get_message(
103-
coin, currency, increase_in_percentage, frequency_in_minutes, indicator=indicator
132+
key,
133+
coin,
134+
currency,
135+
config.increase_in_percentage,
136+
config.frequency_in_minutes,
137+
indicator=indicator,
104138
)
105139
if message:
106140
logger.info(message)
@@ -110,6 +144,7 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
110144

111145
for message in messages:
112146
Alerts(
147+
name=f"bullish-or-bearish-{config.frequency_in_minutes}",
113148
time_ts=time_ts,
114149
trade_symbol=coin,
115150
price=price,
@@ -120,7 +155,7 @@ def task(*, increase_in_percentage: float, frequency_in_minutes: int):
120155
else:
121156
logger.info("Initializing Alerts...")
122157

123-
alerts_cache[coin] = {
158+
alerts_cache[key][coin] = {
124159
"volume": volume,
125160
"volume_buy_orders": volume_buy_orders,
126161
"volume_sell_orders": volume_sell_orders,

exchange_radar/web/src/models.py

+2
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ def save_or_not(cls, coin: str, category: str, message: dict) -> bool:
106106

107107

108108
class Alerts(JsonModel): # pragma: no cover
109+
name: str
109110
time_ts: int = Field(index=True, sortable=True)
110111
trade_symbol: str = Field(index=True)
111112
price: float
@@ -120,6 +121,7 @@ def rows(cls, trade_symbol: str) -> dict[str, list[str]]:
120121
f"{datetime.fromtimestamp(item.time_ts)} | "
121122
f"{trade_symbol.ljust(4)} | "
122123
f"{f'{item.price:,.8f} {item.currency.rjust(4)}'.rjust(16 + 5, ' ')} | "
124+
f"{item.name.ljust(21)} | "
123125
f"{item.message}"
124126
for item in query
125127
]

exchange_radar/web/templates/alerts.j2

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@
2525
<div class="padded">
2626
<!-- box 1 content -->
2727
<pre>
28-
-----------------------------------------------------------------------------------
29-
<b>DATETIME UTC | COIN | PRICE | ALERT</b>
30-
-----------------------------------------------------------------------------------
28+
-------------------------------------------------------------------------------------------------------------------------------
29+
<b>DATETIME UTC | COIN | PRICE | ALERT | MESSAGE</b>
30+
-------------------------------------------------------------------------------------------------------------------------------
3131
<span id="messages"></span>
3232

3333

0 commit comments

Comments
 (0)