diff --git a/api/databases/crud/top_gainers_losers_series_crud.py b/api/databases/crud/top_gainers_losers_series_crud.py index 4f9872ccf..88efb2c64 100644 --- a/api/databases/crud/top_gainers_losers_series_crud.py +++ b/api/databases/crud/top_gainers_losers_series_crud.py @@ -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 @@ -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" @@ -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 ( @@ -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}] #fastest_movers algorithm #{mover.symbol} - Event: entered {side} @@ -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 + - Dashboard trade """ delivery.send_once( "\n".join( diff --git a/api/tests/test_fastest_movers_notifications.py b/api/tests/test_fastest_movers_notifications.py index f4bf45361..063609118 100644 --- a/api/tests/test_fastest_movers_notifications.py +++ b/api/tests/test_fastest_movers_notifications.py @@ -13,6 +13,8 @@ TopGainersLosersSeriesTable, ) +FRONTEND_DOMAIN = "https://terminal.example" + SNAPSHOT_AT = datetime(2026, 11, 27, 12, tzinfo=timezone.utc) @@ -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 @@ -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'Dashboard trade' + in delivery.call_args.args[0] + ) @pytest.mark.parametrize("side,direction", [("rising", 1), ("falling", -1)]) @@ -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: @@ -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] @@ -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() @@ -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() @@ -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() @@ -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() diff --git a/api/tests/test_streaming_lifecycle_strategies.py b/api/tests/test_streaming_lifecycle_strategies.py index 5e84e39fe..affdd5b7e 100644 --- a/api/tests/test_streaming_lifecycle_strategies.py +++ b/api/tests/test_streaming_lifecycle_strategies.py @@ -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 ( @@ -677,14 +678,8 @@ 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, @@ -692,130 +687,108 @@ def _confirmed_lower_high_context() -> LifecycleContext: 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) diff --git a/api/tests/test_swing_protection_feed.py b/api/tests/test_swing_protection_feed.py new file mode 100644 index 000000000..d1dd3f7b1 --- /dev/null +++ b/api/tests/test_swing_protection_feed.py @@ -0,0 +1,127 @@ +from typing import Any +from concurrent.futures import Future +from unittest.mock import Mock + +from pybinbot import Position + +from streaming.swing_protection import SwingProtectionFeed + +NOW_MS = 1_800_000_000_000 + + +def rows(interval, *, wide=False): + highs = [100.0] * 7 + [100, 101, 106.35 if wide else 102, 101, 100] + result = [] + previous_close = highs[0] - 0.1 + for i, high in enumerate(highs): + result.append( + [ + NOW_MS - (12 - i) * interval * 60000, + previous_close, + max(high, previous_close), + min(high - 0.2, previous_close), + high - 0.1, + 10, + NOW_MS - (11 - i) * interval * 60000 - 1, + ] + ) + previous_close = high - 0.1 + return result + + +def feed_with_pending_reads(): + feed = SwingProtectionFeed(Mock()) + feed.close() + feed.executor = Mock() + feed.executor.submit.side_effect = lambda *args, **kwargs: Future() + return feed + + +def resolve(feed, *, symbol="NESUSDTM", wide=True): + return feed.resolve( + candles=rows(15, wide=wide), + symbol=symbol, + position=Position.short, + reference_price=100, + now_ms=NOW_MS, + price_precision=4, + not_before_ms=NOW_MS - 3600000, + max_distance_pct=2.5, + ) + + +def test_valid_fifteen_minute_protection_uses_no_background_requests(): + feed = feed_with_pending_reads() + candidate = resolve(feed, wide=False) + assert candidate is not None and candidate.interval_minutes == 15 + feed.executor.submit.assert_not_called() + + +def test_pending_smaller_candles_return_without_waiting_or_resubmitting(): + feed = feed_with_pending_reads() + assert resolve(feed) is None + assert resolve(feed) is None + assert len(feed.requests) == 1 + feed.executor.submit.assert_called_once() + request = next(iter(feed.requests.values())) + assert not request.done() + request.set_result(rows(5)) + candidate = resolve(feed) + assert candidate is not None and candidate.interval_minutes == 5 + + +def test_refinement_reaches_one_minute_only_after_five_minute_swing_fails(): + feed = feed_with_pending_reads() + assert resolve(feed) is None + next(iter(feed.requests.values())).set_result(rows(5, wide=True)) + assert resolve(feed) is None + feed.requests[("NESUSDTM", 1, NOW_MS // 60000)].set_result(rows(1)) + candidate = resolve(feed) + assert candidate is not None and candidate.interval_minutes == 1 + assert feed.executor.submit.call_count == 2 + + +def test_exchange_failure_does_not_block_protection_or_retry_every_tick(): + feed = feed_with_pending_reads() + assert resolve(feed) is None + next(iter(feed.requests.values())).set_exception( + RuntimeError("exchange unavailable") + ) + assert resolve(feed) is None + assert resolve(feed) is None + assert ( + feed.executor.submit.call_count == 1 + ) # Failed 5m cached; keep existing protection. + + +def test_multiple_bots_cannot_queue_unbounded_exchange_requests(): + feed = feed_with_pending_reads() + assert resolve(feed, symbol="AUSDTM") is None + assert resolve(feed, symbol="BUSDTM") is None + assert resolve(feed, symbol="CUSDTM") is None + assert feed.executor.submit.call_count == 2 + + +def test_gapped_one_minute_history_returns_a_bounded_coarser_stop(): + feed = feed_with_pending_reads() + coarse, five, fine = rows(15), rows(5), rows(1) + coarse[9][3] = five[9][3] = 95 + fine.pop(-4) + kwargs: dict[str, Any] = dict( + candles=coarse, + symbol="NESUSDTM", + position=Position.short, + reference_price=100, + now_ms=NOW_MS, + price_precision=4, + not_before_ms=NOW_MS - 3600000, + max_distance_pct=2.5, + ) + assert feed.resolve(**kwargs) is None + feed.requests[("NESUSDTM", 5, NOW_MS // 300000)].set_result(five) + assert feed.resolve(**kwargs) is None + feed.requests[("NESUSDTM", 1, NOW_MS // 60000)].set_result(fine) + candidate = feed.resolve(**kwargs) + assert candidate is not None + assert candidate.interval_minutes == 5 + assert 0 < candidate.distance_pct <= 2.5 diff --git a/docs/fastest-movers.md b/docs/fastest-movers.md index 9f15ae762..1ea01ea10 100644 --- a/docs/fastest-movers.md +++ b/docs/fastest-movers.md @@ -27,3 +27,6 @@ ranking list, provided the three-hour move is at least +3% for gainers or at mos in the same list does not trigger a later alert merely by crossing this threshold. The threshold filters notifications; dashboard rankings retain all qualifying one-hour movers. + +Each alert includes a Dashboard trade link to `/bots/futures/new/`, +using the configured `FRONTEND_DOMAIN`, matching Binquant strategy alerts. diff --git a/pyproject.toml b/pyproject.toml index 0a7b6e7ba..ebe6b1a33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,7 +19,7 @@ dependencies = [ "numpy==2.5.4", "pandas==3.1.1", "websockets>=17.4", - "pybinbot>=2.1.7", + "pybinbot>=2.1.12", ] [project.urls] diff --git a/streaming/base.py b/streaming/base.py index ab4141546..8f9ff1938 100644 --- a/streaming/base.py +++ b/streaming/base.py @@ -22,6 +22,7 @@ from api.databases.utils import get_db_session from api.tools.config import Config from streaming.kucoin_rate_limiter import KucoinRateLimiter +from streaming.swing_protection import SwingProtectionFeed class BaseStreaming: @@ -46,6 +47,7 @@ def __init__(self) -> None: passphrase=self.config.kucoin_passphrase, ) self.kucoin_rate_limiter = KucoinRateLimiter() + self.swing_protection_feed = SwingProtectionFeed(self.kucoin_futures_api) for api in (self.kucoin_api, self.kucoin_futures_api): transport_option = getattr(api, "http_transport_option", None) if transport_option is not None: diff --git a/streaming/lifecycle.py b/streaming/lifecycle.py index 9d3a45a13..7613c1daa 100644 --- a/streaming/lifecycle.py +++ b/streaming/lifecycle.py @@ -131,6 +131,27 @@ def _evaluate_strategy( bot_profit: float, now_ms: int, ) -> LifecycleEvaluation: + protection = None + bot = self.execution.active_bot + feed = getattr(self.base_streaming, "swing_protection_feed", None) + if ( + feed is not None + and bot.name == "top_gainer_short" + and bot.market_type == MarketType.FUTURES + and bot.trailing + and current_price > 0 + and bot.trailing_profit > 0.85 + ): + protection = feed.resolve( + candles=completed_candles, + symbol=bot.pair, + position=bot.position, + reference_price=current_price, + now_ms=now_ms, + price_precision=self.execution.price_precision, + not_before_ms=bot.deal.opening_timestamp + 1, + max_distance_pct=min(2.5, bot.trailing_profit - 0.35), + ) context = LifecycleContext( bot=self.execution.active_bot, current_price=current_price, @@ -144,6 +165,7 @@ def _evaluate_strategy( bot_profit=bot_profit, market_breadth=None, price_precision=self.execution.price_precision, + swing_protection=protection, ) return self.context_evaluator.evaluate(context) diff --git a/streaming/main.py b/streaming/main.py index e81f47533..e280007f3 100644 --- a/streaming/main.py +++ b/streaming/main.py @@ -38,22 +38,28 @@ def run_positions(stop: Event) -> None: from streaming.position_manager import BaseStreaming, PositionManager bs = BaseStreaming() - while not stop.is_set(): - sweep_started_at = monotonic() - for symbol in tuple(bs.active_bot_pairs): + try: + while not stop.is_set(): + sweep_started_at = monotonic() + for symbol in tuple(bs.active_bot_pairs): + if stop.is_set(): + return + manager = PositionManager(bs, symbol) + manager.process_deal() + with get_db_session() as session: + GridLadderLifecycle(bs, session).process_symbol(symbol) + touch_heartbeat() + if stop.is_set(): return - manager = PositionManager(bs, symbol) - manager.process_deal() - with get_db_session() as session: - GridLadderLifecycle(bs, session).process_symbol(symbol) + bs.get_all_active_pairs() touch_heartbeat() + stop.wait( + max(0.0, SWEEP_INTERVAL_SECONDS - (monotonic() - sweep_started_at)) + ) - if stop.is_set(): - return - bs.get_all_active_pairs() - touch_heartbeat() - stop.wait(max(0.0, SWEEP_INTERVAL_SECONDS - (monotonic() - sweep_started_at))) + finally: + bs.swing_protection_feed.close() async def supervise_cvd(stop: asyncio.Event) -> None: diff --git a/streaming/strategies/base.py b/streaming/strategies/base.py index 799c48b6d..0d79f51e6 100644 --- a/streaming/strategies/base.py +++ b/streaming/strategies/base.py @@ -4,6 +4,7 @@ from pandas import DataFrame from pybinbot import BinanceKlineIntervals, BotModel, MarketBreadthSeries, Position +from pybinbot.strategy.swing_protection import SwingProtection @dataclass(frozen=True) @@ -68,6 +69,7 @@ class LifecycleContext: bot_profit: float market_breadth: MarketBreadthSeries | None = None price_precision: int = 8 + swing_protection: SwingProtection | None = None class LifecycleStrategy(Protocol): diff --git a/streaming/strategies/top_gainer_short.py b/streaming/strategies/top_gainer_short.py index 390ddcb52..e1721d7f2 100644 --- a/streaming/strategies/top_gainer_short.py +++ b/streaming/strategies/top_gainer_short.py @@ -1,9 +1,7 @@ -from decimal import ROUND_CEILING, Decimal -from math import isfinite -from typing import ClassVar, NamedTuple +from typing import ClassVar from pybinbot import BinanceKlineIntervals, Position -from pybinbot.shared.price_crossings import price_crossings_six_hours +from pybinbot.strategy.price_crossings import price_crossings_six_hours from streaming.strategies.base import ( LifecycleContext, @@ -16,13 +14,6 @@ from streaming.strategies.default import DefaultLifecycleStrategy -class LowerHighSwing(NamedTuple): - """Confirmed lower-high peak and the candle swing range that led into it.""" - - peak: float - swing_range_pct: float - - class TopGainerShortLifecycleStrategy(DefaultLifecycleStrategy): """Manage an open top-gainer short with standard protection. @@ -35,13 +26,6 @@ class TopGainerShortLifecycleStrategy(DefaultLifecycleStrategy): MAX_STOP_LOSS = 2.5 PRICE_CROSSING_EXIT_THRESHOLD = 3 MIN_CROSSING_EXIT_HOLD_MS = 6 * 60 * 60 * 1000 - LOWER_HIGH_LOOKBACK_BARS = 40 - LOWER_HIGH_FRACTAL_WING = 2 - LOWER_HIGH_MIN_RISE_PCT = 2.0 - LOWER_HIGH_MIN_DROP_PCT = 2.5 - # trailing_profit - trailing_deviation equals the candle swing range, so the - # deviation never drops below this floor on very large swings. - MIN_TRAILING_DEVIATION_PCT = 0.5 # Structural trailing only applies to positions opened after the # 2026-11-01 16:00 UTC rollout boundary. STRUCTURAL_TRAIL_MIN_ENTRY_TIMESTAMP_MS = 1_793_548_800_000 @@ -55,62 +39,6 @@ class TopGainerShortLifecycleStrategy(DefaultLifecycleStrategy): strategy_exit_before_sizing=True, ) - @classmethod - def latest_lower_high(cls, context: LifecycleContext) -> LowerHighSwing | None: - """Match binquant's confirmed 15m lower-high structure on closed bars. - - The swing range is the rise from the preceding swing low to the first - peak, as binquant's lower-high pattern reports it. - """ - candles = context.completed_candles[-cls.LOWER_HIGH_LOOKBACK_BARS :] - if len(candles) < cls.LOWER_HIGH_LOOKBACK_BARS: - return None - try: - timestamps = [int(candle[0]) for candle in candles] - highs = [float(candle[2]) for candle in candles] - lows = [float(candle[3]) for candle in candles] - except IndexError, TypeError, ValueError: - return None - if any( - later - earlier != context.interval_ms - for earlier, later in zip(timestamps, timestamps[1:]) - ) or any( - not isfinite(high) or not isfinite(low) or high <= 0 or low <= 0 - for high, low in zip(highs, lows) - ): - return None - - wing = cls.LOWER_HIGH_FRACTAL_WING - swing_highs = [ - index - for index in range(wing, len(highs) - wing) - if highs[index] == max(highs[index - wing : index + wing + 1]) - and highs[index - wing : index + wing + 1].count(highs[index]) == 1 - ] - if len(swing_highs) < 2: - return None - earlier, later = swing_highs[-2:] - if timestamps[later] <= context.bot.deal.opening_timestamp: - return None - swing_lows = [ - index - for index in range(wing, earlier) - if lows[index] == min(lows[index - wing : index + wing + 1]) - and lows[index - wing : index + wing + 1].count(lows[index]) == 1 - ] - if not swing_lows: - return None - earlier_high = highs[earlier] - later_high = highs[later] - swing_low = lows[swing_lows[-1]] - swing_range_pct = (earlier_high / swing_low - 1) * 100 - if ( - swing_range_pct < cls.LOWER_HIGH_MIN_RISE_PCT - or (1 - later_high / earlier_high) * 100 < cls.LOWER_HIGH_MIN_DROP_PCT - ): - return None - return LowerHighSwing(peak=later_high, swing_range_pct=swing_range_pct) - def signal(self, context: LifecycleContext) -> LifecycleSignal: opening_timestamp = context.bot.deal.opening_timestamp if ( @@ -138,8 +66,13 @@ def signal(self, context: LifecycleContext) -> LifecycleSignal: ), ) ) - default_signal = super().signal(context) bot = context.bot + structural_protection = ( + bot.deal.opening_timestamp >= self.STRUCTURAL_TRAIL_MIN_ENTRY_TIMESTAMP_MS + ) + default_signal = ( + LifecycleSignal() if structural_protection else super().signal(context) + ) if ( default_signal.parameter_update is None and bot.stop_loss > self.MAX_STOP_LOSS @@ -165,50 +98,39 @@ def signal(self, context: LifecycleContext) -> LifecycleSignal: ): return default_signal - lower_high = self.latest_lower_high(context) - if lower_high is None: + protection = context.swing_protection + if protection is None: return default_signal - stop_price = float( - Decimal(str(lower_high.peak)).quantize( - Decimal(1).scaleb(-context.price_precision), rounding=ROUND_CEILING - ) - ) + stop_price = protection.stop_price current_stop = ( bot.deal.trailing_stop_loss_price if bot.deal.trailing_stop_loss_price > 0 else bot.deal.stop_loss_price ) - # For a short, a lower stop protects more profit. Never arm a trail - # above entry or replace an existing tighter exchange stop. if ( stop_price <= context.current_price or stop_price >= bot.deal.opening_price or (current_stop > 0 and stop_price >= current_stop) + or protection.swing_open_time_ms <= bot.deal.opening_timestamp + or not 0 + <= context.now_ms - protection.swing_open_time_ms + <= 3 * 60 * 60 * 1000 + or not 0.5 + <= protection.distance_pct + <= min(2.5, bot.trailing_profit - 0.35) ): return default_signal - # Keep the deviation below trailing profit by the candle swing range - # instead of the peak-to-price distance, which can exceed 4%. - trailing_deviation = float( - max( - Decimal(str(bot.trailing_profit)) - - Decimal(str(lower_high.swing_range_pct)), - Decimal(str(self.MIN_TRAILING_DEVIATION_PCT)), - ).quantize(Decimal("0.0001"), rounding=ROUND_CEILING) - ) - if not 0 < trailing_deviation < 100: - return default_signal return LifecycleSignal( parameter_update=LifecycleParameterUpdate( stop_loss=bot.stop_loss, trailing_profit=bot.trailing_profit, - trailing_deviation=trailing_deviation, + trailing_deviation=protection.distance_pct, trailing_stop_price=stop_price, ), log_messages=( - f"[top_gainer_short] Confirmed lower-high peak {stop_price} is " - "below entry; tightening the exchange trailing stop with " - f"{trailing_deviation}% deviation (trailing profit " - f"{bot.trailing_profit}% minus {lower_high.swing_range_pct:.4f}% " - "candle swing range).", + f"[top_gainer_short] Tightening the full-position trailing stop " + f"to {stop_price} on a confirmed {protection.interval_minutes}m " + f"swing at {protection.swing_open_time_ms}, with " + f"{protection.distance_pct:.4f}% deviation; maximum swing age three hours.", ), ) diff --git a/streaming/swing_protection.py b/streaming/swing_protection.py new file mode 100644 index 000000000..e672f49d4 --- /dev/null +++ b/streaming/swing_protection.py @@ -0,0 +1,83 @@ +"""Nonblocking candle refinement for live structural protection.""" + +from concurrent.futures import Future, ThreadPoolExecutor + +from pybinbot import KucoinFutures, Position +from pybinbot.strategy.swing_protection import ( + PROTECTION_LOOKBACK_MS, + SwingProtection, + refine_swing_protection, +) + + +class SwingProtectionFeed: + """Poll bounded background reads while normal lifecycle exits continue. + + Cache each symbol/timeframe until its next candle boundary. Permit at + most two outstanding exchange requests, including queued work. Failure + or missing history leaves protection with the caller's existing orders. + """ + + def __init__(self, api: KucoinFutures) -> None: + self.api = api + self.executor = ThreadPoolExecutor( + max_workers=2, thread_name_prefix="protection-candles" + ) + self.requests: dict[tuple[str, int, int], Future[list]] = {} + + def resolve( + self, + *, + candles: list, + symbol: str, + position: Position, + reference_price: float, + now_ms: int, + price_precision: int, + not_before_ms: int, + max_distance_pct: float, + ) -> SwingProtection | None: + history = {15: candles} + while True: + selection = refine_swing_protection( + history, + position=position, + reference_price=reference_price, + now_ms=now_ms, + price_precision=price_precision, + buffer_pct=0.1, + min_distance_pct=0.5, + max_distance_pct=max_distance_pct, + not_before_ms=not_before_ms, + ) + interval = selection.required_interval_minutes + if interval is None: + return selection.protection + interval_ms = interval * 60000 + key = (symbol, interval, now_ms // interval_ms) + for stale, future in list(self.requests.items()): + if stale[2] != now_ms // (stale[1] * 60000) and future.done(): + del self.requests[stale] + if key not in self.requests: + if sum(not future.done() for future in self.requests.values()) >= 2: + return None + self.requests[key] = self.executor.submit( + self.api.get_klines, + symbol=symbol, + interval=f"{interval}min", + limit=PROTECTION_LOOKBACK_MS // interval_ms + 1, + start_time=now_ms - PROTECTION_LOOKBACK_MS, + end_time=now_ms, + ) + request = self.requests[key] + if not request.done(): + return None + try: + history[interval] = request.result() + except Exception: + # An unavailable finer feed falls back through the shared + # decision. A pending request keeps existing protection. + history[interval] = [] + + def close(self) -> None: + self.executor.shutdown(wait=False, cancel_futures=True) diff --git a/uv.lock b/uv.lock index ffe921385..7e6437074 100644 --- a/uv.lock +++ b/uv.lock @@ -294,7 +294,7 @@ requires-dist = [ { name = "psycopg2-binary", specifier = ">=2.9.12" }, { name = "py3cw", specifier = ">=0.0.39" }, { name = "py4j", specifier = ">=0.10.9" }, - { name = "pybinbot", specifier = ">=2.1.7" }, + { name = "pybinbot", specifier = ">=2.1.12" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=9.0.2" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=1.3.0" }, { name = "pytest-vcr", marker = "extra == 'dev'", specifier = ">=1.0.2" }, @@ -1450,7 +1450,7 @@ wheels = [ [[package]] name = "pybinbot" -version = "2.1.7" +version = "2.1.12" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiohttp" }, @@ -1465,9 +1465,9 @@ dependencies = [ { name = "requests" }, { name = "websocket-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/6c/14/fe54b49ad75356d00868bb0c4fcf987fc9c181634d0deb1de5d734774e34/pybinbot-2.1.7.tar.gz", hash = "sha256:a7327f4c28da15f0dca3e8989413d95dfa8353cb5907c486f82941b396de8f69", size = 101851, upload-time = "2026-11-27T21:24:09.498Z" } +sdist = { url = "https://files.pythonhosted.org/packages/79/07/a4648919cc800775aa43445189d9a5a43db041358c06db75764f8800afe4/pybinbot-2.1.12.tar.gz", hash = "sha256:027907cbd8a7a2630497679c2fac933e81345846834fc75afacad47df7143d0f", size = 109397, upload-time = "2026-11-29T12:13:14.816Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/27/2ca2d69b100b36b627cb681609411ff2a1578858e425f26652fefca5e9b1/pybinbot-2.1.7-py3-none-any.whl", hash = "sha256:7d9bc13614815a89864f667a90f4d58c2797750336c3e187746c9573edcd2014", size = 86330, upload-time = "2026-11-27T21:24:08.076Z" }, + { url = "https://files.pythonhosted.org/packages/20/7b/005ce440b5d556dfab279eb3fdb674dd73c326abd3e0a999f68657ef748f/pybinbot-2.1.12-py3-none-any.whl", hash = "sha256:39d888957ef1c8373ed6acc68220c4f6015b9fd455d5d8f5eac3687352263172", size = 91609, upload-time = "2026-11-29T12:13:13.092Z" }, ] [[package]] @@ -2156,15 +2156,15 @@ wheels = [ [[package]] name = "uvicorn" -version = "0.54.0" +version = "0.55.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click" }, { name = "h11" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +sdist = { url = "https://files.pythonhosted.org/packages/60/32/ed1b49f4eca183639f1048bc48494c8e24386c865dce1357cd108d5871ea/uvicorn-0.55.0.tar.gz", hash = "sha256:b65ae5f0f30cdcbc26a104b93d7d19723aa5f46fec3915a6c247d5795449331c", size = 114540, upload-time = "2026-11-28T13:03:51.048Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, + { url = "https://files.pythonhosted.org/packages/d2/05/3f8e143f2180eb21ed5e28b3c319143960c797c68852744c4d9116480928/uvicorn-0.55.0-py3-none-any.whl", hash = "sha256:bee604c5af6e15fb0584913c632b222c09db1048c26fc05053203207c4b9e37d", size = 87457, upload-time = "2026-11-28T13:03:49.635Z" }, ] [package.optional-dependencies]