Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion api/databases/crud/top_gainers_losers_series_crud.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from datetime import datetime, timedelta, timezone
from html import escape
import logging
from typing import Any, Iterable, cast
from urllib.parse import quote

from pybinbot import ExchangeId, KucoinFutures
from pybinbot.shared.telegram_delivery import TelegramDelivery
Expand Down Expand Up @@ -161,7 +163,9 @@ def ingest(self, top: int = 10) -> list[TopGainersLosersSeriesTable]:
current_movers = FastestMoversSnapshot.model_validate(
self.query_fastest_movers(limit=top, as_of=recorded_at)
)
self.notify_fastest_movers(previous_movers, current_movers, config.env)
self.notify_fastest_movers(
previous_movers, current_movers, config.env, config.frontend_domain
)
except Exception:
logging.exception(
"Fastest-mover notification failed; ingestion is committed"
Expand All @@ -173,6 +177,7 @@ def notify_fastest_movers(
previous: FastestMoversSnapshot,
current: FastestMoversSnapshot,
environment: str,
frontend_domain: str,
) -> None:
"""Alert fresh ranking entries with a matching three-hour move of at least 3%."""
if (
Expand Down Expand Up @@ -206,6 +211,10 @@ def notify_fastest_movers(
return
if delivery is None:
delivery = TelegramDelivery()
dashboard_url = (
f"{frontend_domain.rstrip('/')}/bots/futures/new/"
f"{quote(mover.symbol, safe='')}"
)
message = f"""
- [{environment}] <strong>#fastest_movers algorithm</strong> #{mover.symbol}
- Event: entered {side}
Expand All @@ -216,6 +225,7 @@ def notify_fastest_movers(
- Current price: {mover.last_price}
- Snapshot time: {current.recorded_at.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")}
- Autotrade: disabled, notification only
- <a href="{escape(dashboard_url, quote=True)}">Dashboard trade</a>
"""
delivery.send_once(
"\n".join(
Expand Down
60 changes: 52 additions & 8 deletions api/tests/test_fastest_movers_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
TopGainersLosersSeriesTable,
)

FRONTEND_DOMAIN = "https://terminal.example"

SNAPSHOT_AT = datetime(2026, 11, 27, 12, tzinfo=timezone.utc)


Expand Down Expand Up @@ -61,14 +63,18 @@ def entries(symbols, change):
def test_unchanged_membership_is_quiet_even_when_ranks_change(delivery):
previous = snapshot(SNAPSHOT_AT - timedelta(minutes=30), ("A", "B"), ("C",))
current = snapshot(rising=("B", "A"), falling=("C",))
TopGainersLosersSeriesCrud.notify_fastest_movers(previous, current, "test")
TopGainersLosersSeriesCrud.notify_fastest_movers(
previous, current, "test", FRONTEND_DOMAIN
)
delivery.assert_not_called()


def test_only_new_rising_and_falling_members_are_notified(delivery):
previous = snapshot(SNAPSHOT_AT - timedelta(minutes=30), ("A",), ("C",))
current = snapshot(rising=("A", "B"), falling=("C", "D"))
TopGainersLosersSeriesCrud.notify_fastest_movers(previous, current, "test")
TopGainersLosersSeriesCrud.notify_fastest_movers(
previous, current, "test", FRONTEND_DOMAIN
)
assert delivery.call_count == 2
rising, falling = [call.args[0] for call in delivery.call_args_list]
assert "#B" in rising
Expand All @@ -78,6 +84,33 @@ def test_only_new_rising_and_falling_members_are_notified(delivery):
assert "3h price change: +10.00%" in rising
assert "#D" in falling
assert "Event: entered Falling" in falling
assert f'href="{FRONTEND_DOMAIN}/bots/futures/new/B"' in rising
assert f'href="{FRONTEND_DOMAIN}/bots/futures/new/D"' in falling


@pytest.mark.parametrize(
"frontend_domain",
[
"https://terminal.example",
"https://terminal.example/",
"https://terminal.example/dashboard/",
],
)
def test_notification_links_to_the_configured_futures_trade_page(
frontend_domain, delivery
):
TopGainersLosersSeriesCrud.notify_fastest_movers(
snapshot(SNAPSHOT_AT - timedelta(minutes=30)),
snapshot(rising=("NESUSDTM",)),
"test",
frontend_domain,
)

delivery.assert_called_once()
assert (
f'<a href="{frontend_domain.rstrip("/")}/bots/futures/new/NESUSDTM">Dashboard trade</a>'
in delivery.call_args.args[0]
)


@pytest.mark.parametrize("side,direction", [("rising", 1), ("falling", -1)])
Expand All @@ -103,7 +136,9 @@ def test_alert_requires_at_least_three_percent_over_three_hours_in_its_direction
change_3h * direction if change_3h is not None else None
)

TopGainersLosersSeriesCrud.notify_fastest_movers(previous, current, "test")
TopGainersLosersSeriesCrud.notify_fastest_movers(
previous, current, "test", FRONTEND_DOMAIN
)

assert delivery.call_count == int(should_notify)
if should_notify:
Expand All @@ -116,7 +151,7 @@ def test_alert_requires_at_least_three_percent_over_three_hours_in_its_direction
def test_switching_sides_is_a_new_entry(delivery):
previous = snapshot(SNAPSHOT_AT - timedelta(minutes=30), rising=("A",))
TopGainersLosersSeriesCrud.notify_fastest_movers(
previous, snapshot(falling=("A",)), "test"
previous, snapshot(falling=("A",)), "test", FRONTEND_DOMAIN
)
delivery.assert_called_once()
assert "entered Falling" in delivery.call_args.args[0]
Expand All @@ -125,7 +160,7 @@ def test_switching_sides_is_a_new_entry(delivery):
def test_reentry_notifies_after_a_snapshot_outside_the_list(delivery):
outside = snapshot(SNAPSHOT_AT - timedelta(minutes=30))
TopGainersLosersSeriesCrud.notify_fastest_movers(
outside, snapshot(rising=("A",)), "test"
outside, snapshot(rising=("A",)), "test", FRONTEND_DOMAIN
)
delivery.assert_called_once()

Expand All @@ -136,7 +171,10 @@ def test_reentry_notifies_after_a_snapshot_outside_the_list(delivery):
def test_only_alerts_inside_the_fifteen_minute_window_are_sent(age, clock, delivery):
clock.now.return_value = SNAPSHOT_AT + age
TopGainersLosersSeriesCrud.notify_fastest_movers(
snapshot(SNAPSHOT_AT - timedelta(minutes=30)), snapshot(rising=("A",)), "test"
snapshot(SNAPSHOT_AT - timedelta(minutes=30)),
snapshot(rising=("A",)),
"test",
FRONTEND_DOMAIN,
)
delivery.assert_not_called()

Expand All @@ -150,6 +188,7 @@ def test_expiry_is_checked_before_each_send(clock, delivery):
snapshot(SNAPSHOT_AT - timedelta(minutes=30)),
snapshot(rising=("A", "B")),
"test",
FRONTEND_DOMAIN,
)
delivery.assert_called_once()

Expand All @@ -162,13 +201,18 @@ def test_waits_for_valid_hourly_rankings(missing_comparison, delivery):
previous.comparison_at = None
else:
current.comparison_at = None
TopGainersLosersSeriesCrud.notify_fastest_movers(previous, current, "test")
TopGainersLosersSeriesCrud.notify_fastest_movers(
previous, current, "test", FRONTEND_DOMAIN
)
delivery.assert_not_called()


def test_missing_ingestion_slot_establishes_a_quiet_baseline(delivery):
TopGainersLosersSeriesCrud.notify_fastest_movers(
snapshot(SNAPSHOT_AT - timedelta(hours=1)), snapshot(rising=("A",)), "test"
snapshot(SNAPSHOT_AT - timedelta(hours=1)),
snapshot(rising=("A",)),
"test",
FRONTEND_DOMAIN,
)
delivery.assert_not_called()

Expand Down
145 changes: 59 additions & 86 deletions api/tests/test_streaming_lifecycle_strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@
from streaming.strategies.mean_reversion_fade import (
MeanReversionFadeLifecycleStrategy,
)
from pybinbot.strategy.swing_protection import SwingProtection

from streaming.strategies.top_gainer_short import (
LowerHighSwing,
TopGainerShortLifecycleStrategy,
)
from streaming.strategies.top_gainer_early_momentum import (
Expand Down Expand Up @@ -677,145 +678,117 @@ def test_top_gainer_short_lifecycle_uses_15m_candles_when_default_is_5m() -> Non


def _confirmed_lower_high_context() -> LifecycleContext:
highs = [80.0 + index * 0.5 for index in range(30)]
highs.extend([110.0, 102.0, 95.0, 90.0, 94.0, 96.0, 97.0, 99.0, 95.0, 93.0])
lows = [high - 1.0 for high in highs]
lows[20] = 80.0
candles = _candles(count=40, start=1_793_550_000_000)
for index, candle in enumerate(candles):
candle[2] = highs[index]
candle[3] = lows[index]
now_ms = candles[-1][6] + 1
context = _context(
name="top_gainer_short",
position=Position.short,
klines=candles,
completed_candles=candles,
current_price=95.0,
opening_timestamp=candles[32][0],
now_ms=candles[-1][6] + 1,
now_ms=now_ms,
)
context.bot.deal.stop_loss_price = 102.0
context.bot.trailing_deviation = 4.5
context.bot.trailing_profit = 4.5
return replace(context, price_precision=2)
return replace(
context,
price_precision=2,
swing_protection=SwingProtection(
interval_minutes=5,
swing_open_time_ms=now_ms - 15 * 60000,
confirmation_time_ms=now_ms - 1,
stop_price=97.0,
distance_pct=(97 / 95 - 1) * 100,
candle_range_pct=1.0,
),
)


def test_top_gainer_short_arms_native_trail_at_latest_confirmed_lower_high() -> None:
def test_top_gainer_short_arms_native_trail_at_recent_refined_swing() -> None:
context = _confirmed_lower_high_context()

signal = TopGainerShortLifecycleStrategy().signal(context)

assert signal.parameter_update is not None
assert signal.parameter_update.trailing_stop_price == 99.0
# The 37.5% swing exceeds trailing profit, so the deviation floors.
assert (
signal.parameter_update.trailing_deviation
== TopGainerShortLifecycleStrategy.MIN_TRAILING_DEVIATION_PCT
assert signal.parameter_update.trailing_stop_price == 97.0
assert signal.parameter_update.trailing_deviation == pytest.approx(
(97 / 95 - 1) * 100
)
assert signal.parameter_update.trailing_profit == 4.5
assert not signal.parameter_update.allow_stop_loss_widening


def test_top_gainer_short_trailing_gap_equals_candle_swing_range(monkeypatch) -> None:
@pytest.mark.parametrize("stop", [100.0, 102.0, 94.0])
def test_refined_trail_must_be_profitable_and_on_the_protective_side(stop):
context = _confirmed_lower_high_context()
monkeypatch.setattr(
TopGainerShortLifecycleStrategy,
"latest_lower_high",
classmethod(lambda cls, _context: LowerHighSwing(99.0, 3.0)),
)

signal = TopGainerShortLifecycleStrategy().signal(context)

assert signal.parameter_update is not None
assert signal.parameter_update.trailing_stop_price == 99.0
assert signal.parameter_update.trailing_deviation == 1.5
assert context.swing_protection is not None
candidate = replace(context.swing_protection, stop_price=stop)
assert (
signal.parameter_update.trailing_profit
- signal.parameter_update.trailing_deviation
== 3.0
TopGainerShortLifecycleStrategy()
.signal(replace(context, swing_protection=candidate))
.parameter_update
is None
)


def test_top_gainer_short_rounds_low_price_pattern_stop_above_candle_high() -> None:
context = _confirmed_lower_high_context()
for candle in context.completed_candles:
candle[2] *= 0.00004
candle[3] *= 0.00004
context.completed_candles[37][2] = 0.0039601
context.bot.deal.opening_price = 0.004
context.bot.deal.stop_loss_price = 0.00408
context = replace(context, current_price=0.0038, price_precision=6)

signal = TopGainerShortLifecycleStrategy().signal(context)

assert signal.parameter_update is not None
assert signal.parameter_update.trailing_stop_price == 0.003961


def test_top_gainer_short_does_not_arm_unprofitable_or_looser_pattern_stop() -> None:
def test_refined_swing_never_loosens_an_existing_trail():
context = _confirmed_lower_high_context()
context.bot.deal.opening_price = 98.0
assert TopGainerShortLifecycleStrategy().signal(context).parameter_update is None

context.bot.deal.opening_price = 100.0
context.bot.deal.trailing_stop_loss_price = 98.0
context.bot.deal.trailing_stop_loss_price = 96.0
assert TopGainerShortLifecycleStrategy().signal(context).parameter_update is None


def test_top_gainer_short_waits_for_confirmed_completed_pattern() -> None:
@pytest.mark.parametrize("problem", ["missing", "old", "before_entry", "too_wide"])
def test_missing_or_unsafe_refined_swing_keeps_existing_protection(problem):
context = _confirmed_lower_high_context()

signal = TopGainerShortLifecycleStrategy().signal(
replace(context, completed_candles=context.completed_candles[:-1])
candidate = context.swing_protection
assert candidate is not None
if problem == "missing":
candidate = None
elif problem == "old":
candidate = replace(candidate, swing_open_time_ms=context.now_ms - 10800001)
elif problem == "before_entry":
candidate = replace(
candidate, swing_open_time_ms=context.bot.deal.opening_timestamp
)
else:
candidate = replace(candidate, distance_pct=3.1)
assert (
TopGainerShortLifecycleStrategy()
.signal(replace(context, swing_protection=candidate))
.parameter_update
is None
)

assert signal.parameter_update is None


def test_top_gainer_short_does_not_reuse_a_pattern_from_before_entry() -> None:
context = _confirmed_lower_high_context()
context.bot.deal.opening_timestamp = context.completed_candles[38][0]

assert TopGainerShortLifecycleStrategy().signal(context).parameter_update is None


def test_top_gainer_short_keeps_existing_positions_on_their_original_stop_policy() -> (
None
):
def test_top_gainer_short_keeps_existing_positions_on_their_original_stop_policy():
context = _confirmed_lower_high_context()
context.bot.deal.opening_timestamp = (
TopGainerShortLifecycleStrategy.STRUCTURAL_TRAIL_MIN_ENTRY_TIMESTAMP_MS - 1
)

assert TopGainerShortLifecycleStrategy().signal(context).parameter_update is None


def test_top_gainer_short_places_structural_stop_through_native_exchange_path() -> None:
def test_top_gainer_short_places_refined_stop_through_native_exchange_path():
context = _confirmed_lower_high_context()
signal = TopGainerShortLifecycleStrategy().signal(context)
place_trailing_stop_loss = Mock()
place = Mock()
save = Mock()
update_parameters = Mock(return_value=context.bot)
update = Mock(return_value=context.bot)
lifecycle = cast(Any, Lifecycle.__new__(Lifecycle))
lifecycle.execution = types.SimpleNamespace(
active_bot=context.bot,
update_parameters=update_parameters,
place_trailing_stop_loss=place_trailing_stop_loss,
update_parameters=update,
place_trailing_stop_loss=place,
controller=types.SimpleNamespace(save=save),
)

lifecycle._apply_strategy_signal(
LifecycleEvaluation(
policy=TopGainerShortLifecycleStrategy.policy, signal=signal
)
)

assert context.bot.deal.trailing_stop_loss_price == 99.0
assert (
context.bot.trailing_deviation
== TopGainerShortLifecycleStrategy.MIN_TRAILING_DEVIATION_PCT
)
update_parameters.assert_called_once_with(allow_stop_loss_widening=False)
place_trailing_stop_loss.assert_called_once_with()
assert context.bot.deal.trailing_stop_loss_price == 97.0
update.assert_called_once_with(allow_stop_loss_widening=False)
place.assert_called_once_with()
save.assert_called_once_with(context.bot)


Expand Down
Loading