pybinbot 2.1.5__tar.gz → 2.1.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. {pybinbot-2.1.5/pybinbot.egg-info → pybinbot-2.1.9}/PKG-INFO +37 -1
  2. {pybinbot-2.1.5 → pybinbot-2.1.9}/README.md +36 -0
  3. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/__init__.py +10 -2
  4. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/binbot/base.py +9 -0
  5. pybinbot-2.1.9/pybinbot/models/fastest_movers.py +26 -0
  6. pybinbot-2.1.9/pybinbot/shared/beta.py +13 -0
  7. pybinbot-2.1.9/pybinbot/shared/breadth.py +21 -0
  8. pybinbot-2.1.9/pybinbot/shared/price_crossings.py +15 -0
  9. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/telegram_delivery.py +57 -28
  10. pybinbot-2.1.9/pybinbot/strategy/swing_protection.py +167 -0
  11. {pybinbot-2.1.5 → pybinbot-2.1.9/pybinbot.egg-info}/PKG-INFO +37 -1
  12. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot.egg-info/SOURCES.txt +7 -0
  13. {pybinbot-2.1.5 → pybinbot-2.1.9}/pyproject.toml +2 -1
  14. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_beta.py +1 -1
  15. pybinbot-2.1.9/tests/test_fastest_movers.py +89 -0
  16. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_price_crossings.py +1 -1
  17. pybinbot-2.1.9/tests/test_swing_protection.py +153 -0
  18. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_telegram_delivery.py +62 -0
  19. {pybinbot-2.1.5 → pybinbot-2.1.9}/LICENSE +0 -0
  20. {pybinbot-2.1.5 → pybinbot-2.1.9}/MANIFEST.in +0 -0
  21. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/binance/base.py +0 -0
  22. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/binance/exceptions.py +0 -0
  23. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/binbot/exceptions.py +0 -0
  24. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/coingecko.py +0 -0
  25. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/kucoin/base.py +0 -0
  26. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/kucoin/exceptions.py +0 -0
  27. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/kucoin/futures.py +0 -0
  28. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/kucoin/market.py +0 -0
  29. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/kucoin/orders.py +0 -0
  30. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/apis/kucoin/rest.py +0 -0
  31. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/__init__.py +0 -0
  32. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/autotrade_settings.py +0 -0
  33. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/bot.py +0 -0
  34. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/bot_base.py +0 -0
  35. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/cvd.py +0 -0
  36. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/deal.py +0 -0
  37. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/derivatives.py +0 -0
  38. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/grid_ladder.py +0 -0
  39. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/order.py +0 -0
  40. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/routes.py +0 -0
  41. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/signals.py +0 -0
  42. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/models/symbol.py +0 -0
  43. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/py.typed +0 -0
  44. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/__init__.py +0 -0
  45. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/cache.py +0 -0
  46. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/candles.py +0 -0
  47. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/enums.py +0 -0
  48. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/handlers.py +0 -0
  49. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/heikin_ashi.py +0 -0
  50. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/indicators.py +0 -0
  51. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/logging_config.py +0 -0
  52. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/maths.py +0 -0
  53. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/timestamps.py +0 -0
  54. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/types.py +0 -0
  55. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/shared/utils.py +0 -0
  56. {pybinbot-2.1.5/pybinbot/shared → pybinbot-2.1.9/pybinbot/strategy}/beta.py +0 -0
  57. {pybinbot-2.1.5/pybinbot/shared → pybinbot-2.1.9/pybinbot/strategy}/breadth.py +0 -0
  58. {pybinbot-2.1.5/pybinbot/shared → pybinbot-2.1.9/pybinbot/strategy}/price_crossings.py +0 -0
  59. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/streaming/binance/async_socket_client.py +0 -0
  60. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/streaming/binance/socket_client.py +0 -0
  61. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/streaming/binance/socket_manager.py +0 -0
  62. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
  63. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot.egg-info/dependency_links.txt +0 -0
  64. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot.egg-info/requires.txt +0 -0
  65. {pybinbot-2.1.5 → pybinbot-2.1.9}/pybinbot.egg-info/top_level.txt +0 -0
  66. {pybinbot-2.1.5 → pybinbot-2.1.9}/setup.cfg +0 -0
  67. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_binbot_api.py +0 -0
  68. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_bot_futures_leverage.py +0 -0
  69. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_breadth.py +0 -0
  70. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_candles.py +0 -0
  71. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_closed_bot_status.py +0 -0
  72. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_coingecko.py +0 -0
  73. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_conditional_entry.py +0 -0
  74. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_conditional_futures_orders.py +0 -0
  75. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_cvd_api.py +0 -0
  76. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_deal_model.py +0 -0
  77. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_derivatives_api.py +0 -0
  78. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_futures_place_order.py +0 -0
  79. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_grid_ladder.py +0 -0
  80. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_handlers.py +0 -0
  81. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_heikin_ashi.py +0 -0
  82. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_indicators.py +0 -0
  83. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_kucoin_api.py +0 -0
  84. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_logging_config.py +0 -0
  85. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_matching_engine.py +0 -0
  86. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_maths.py +0 -0
  87. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_symbol_model.py +0 -0
  88. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_timestamps.py +0 -0
  89. {pybinbot-2.1.5 → pybinbot-2.1.9}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.5
3
+ Version: 2.1.9
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -136,3 +136,39 @@ make tag
136
136
 
137
137
 
138
138
  For further commands take a look at the `Makefile` such as testing `make test`
139
+
140
+ ## Strategy calculations
141
+
142
+ Reusable pattern detection, signal gates and strategy risk calculations live in
143
+ `pybinbot.strategy`:
144
+
145
+ - `price_crossings`: six-hour candle-range and gap crossings for chop gates.
146
+ - `swing_protection`: recent confirmed swings for bounded protective prices.
147
+ - `beta`: rolling and latest return beta against BTC.
148
+ - `breadth`: breadth-momentum reversals and BTC-trend confirmation.
149
+
150
+ Import directly from the relevant module, for example:
151
+
152
+ ```python
153
+ from pybinbot.strategy.beta import rolling_beta
154
+ from pybinbot.strategy.price_crossings import price_crossings_six_hours
155
+ from pybinbot.strategy.swing_protection import recent_swing_protection
156
+ ```
157
+
158
+ The published `pybinbot.shared.beta`, `pybinbot.shared.breadth` and
159
+ `pybinbot.shared.price_crossings` paths remain as import aliases. Existing
160
+ package-level beta and breadth exports also remain available. General candle
161
+ processing, indicators, timestamps, exchange types and delivery utilities remain
162
+ in `pybinbot.shared`. New reusable strategy calculations belong in
163
+ `pybinbot.strategy`.
164
+
165
+ ## Recent swing protection
166
+
167
+ `pybinbot.strategy.swing_protection.recent_swing_protection` evaluates the latest
168
+ confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
169
+ that order when a candidate is unsuitable. The maximum search window is three
170
+ hours, optionally narrowed to one hour or to the start of the current setup.
171
+ The selector rejects swing candles wider than 3% and stop distances over 2.5%
172
+ after the buffer and outward tick rounding. It never clips a distant swing or
173
+ searches older swings to force a result. Entry callers skip when all timeframes
174
+ fail; live callers retain existing protection and only apply tighter stops.
@@ -107,3 +107,39 @@ make tag
107
107
 
108
108
 
109
109
  For further commands take a look at the `Makefile` such as testing `make test`
110
+
111
+ ## Strategy calculations
112
+
113
+ Reusable pattern detection, signal gates and strategy risk calculations live in
114
+ `pybinbot.strategy`:
115
+
116
+ - `price_crossings`: six-hour candle-range and gap crossings for chop gates.
117
+ - `swing_protection`: recent confirmed swings for bounded protective prices.
118
+ - `beta`: rolling and latest return beta against BTC.
119
+ - `breadth`: breadth-momentum reversals and BTC-trend confirmation.
120
+
121
+ Import directly from the relevant module, for example:
122
+
123
+ ```python
124
+ from pybinbot.strategy.beta import rolling_beta
125
+ from pybinbot.strategy.price_crossings import price_crossings_six_hours
126
+ from pybinbot.strategy.swing_protection import recent_swing_protection
127
+ ```
128
+
129
+ The published `pybinbot.shared.beta`, `pybinbot.shared.breadth` and
130
+ `pybinbot.shared.price_crossings` paths remain as import aliases. Existing
131
+ package-level beta and breadth exports also remain available. General candle
132
+ processing, indicators, timestamps, exchange types and delivery utilities remain
133
+ in `pybinbot.shared`. New reusable strategy calculations belong in
134
+ `pybinbot.strategy`.
135
+
136
+ ## Recent swing protection
137
+
138
+ `pybinbot.strategy.swing_protection.recent_swing_protection` evaluates the latest
139
+ confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
140
+ that order when a candidate is unsuitable. The maximum search window is three
141
+ hours, optionally narrowed to one hour or to the start of the current setup.
142
+ The selector rejects swing candles wider than 3% and stop distances over 2.5%
143
+ after the buffer and outward tick rounding. It never clips a distant swing or
144
+ searches older swings to force a result. Entry callers skip when all timeframes
145
+ fail; live callers retain existing protection and only apply tighter stops.
@@ -56,8 +56,8 @@ from pybinbot.shared.enums import (
56
56
  AutotradeSettingsDocument,
57
57
  )
58
58
  from pybinbot.shared.indicators import Indicators
59
- from pybinbot.shared.breadth import breadth_momentum_reversal, btc_trend_confirms
60
- from pybinbot.shared.beta import latest_beta, rolling_beta
59
+ from pybinbot.strategy.breadth import breadth_momentum_reversal, btc_trend_confirms
60
+ from pybinbot.strategy.beta import latest_beta, rolling_beta
61
61
  from pybinbot.shared.candles import Candles
62
62
  from pybinbot.shared.heikin_ashi import HeikinAshi
63
63
  from pybinbot.shared.logging_config import configure_logging
@@ -121,6 +121,11 @@ from pybinbot.models.signals import (
121
121
  )
122
122
  from pybinbot.models.symbol import SymbolModel
123
123
  from pybinbot.models.cvd import CvdAggregateResponse, CvdPoint, CvdSymbolResponse
124
+ from pybinbot.models.fastest_movers import (
125
+ FastestMoverEntry,
126
+ FastestMoversResponse,
127
+ FastestMoversSnapshot,
128
+ )
124
129
  from pybinbot.models.routes import (
125
130
  GainerLoserEntry,
126
131
  GainersLosersSeriesResponse,
@@ -211,6 +216,9 @@ __all__ = [
211
216
  "GainerLoserEntry",
212
217
  "GainersLosersSeriesResponse",
213
218
  "GainersLosersSnapshot",
219
+ "FastestMoverEntry",
220
+ "FastestMoversResponse",
221
+ "FastestMoversSnapshot",
214
222
  "MarketBreadthSeries",
215
223
  "MarketBreadthSeriesResponse",
216
224
  "CvdPoint",
@@ -29,6 +29,7 @@ from pybinbot import (
29
29
  from datetime import datetime, timezone
30
30
  from dateutil.parser import parse
31
31
  from pybinbot.models.cvd import CvdAggregateResponse, CvdSymbolResponse
32
+ from pybinbot.models.fastest_movers import FastestMoversResponse, FastestMoversSnapshot
32
33
 
33
34
  logger = logging.getLogger(__name__)
34
35
 
@@ -81,6 +82,7 @@ class BinbotApi:
81
82
  self.bb_gainers_losers_series_url = (
82
83
  f"{bb_base_url}/charts/gainers-losers-series"
83
84
  )
85
+ self.bb_fastest_movers_url = f"{bb_base_url}/charts/fastest_movers"
84
86
  self.bb_signals_url = f"{bb_base_url}/signals"
85
87
  self.bb_grid_ladders_url = f"{bb_base_url}/grid-ladders"
86
88
  self.bb_grid_ladder_calculate_url = f"{bb_base_url}/grid-ladders/calculate"
@@ -306,6 +308,13 @@ class BinbotApi:
306
308
  return []
307
309
  return GainersLosersSeriesResponse.model_validate(response).data
308
310
 
311
+ async def get_fastest_movers(self, limit: int = 10) -> FastestMoversSnapshot:
312
+ """Return one-hour price-move rankings with three-hour and 24h context."""
313
+ response = await self.fetch(
314
+ url=self.bb_fastest_movers_url, params={"limit": limit}
315
+ )
316
+ return FastestMoversResponse.model_validate(response).data
317
+
309
318
  async def get_cvd_symbol(self, symbol: str, limit: int = 15) -> CvdSymbolResponse:
310
319
  """Read oldest-first one-minute contract CVD, including coverage flags.
311
320
 
@@ -0,0 +1,26 @@
1
+ """One-hour KuCoin futures rankings served by Binbot's charts API."""
2
+
3
+ from pydantic import AwareDatetime, BaseModel
4
+
5
+ from pybinbot.models.routes import StandardResponse
6
+
7
+
8
+ class FastestMoverEntry(BaseModel):
9
+ symbol: str
10
+ price_change_1h_percent: float
11
+ price_change_3h_percent: float | None = None
12
+ price_change_percent: float
13
+ last_price: float
14
+ turnover_24h: float
15
+
16
+
17
+ class FastestMoversSnapshot(BaseModel):
18
+ source: str
19
+ recorded_at: AwareDatetime | None
20
+ comparison_at: AwareDatetime | None
21
+ gainers: list[FastestMoverEntry]
22
+ losers: list[FastestMoverEntry]
23
+
24
+
25
+ class FastestMoversResponse(StandardResponse):
26
+ data: FastestMoversSnapshot
@@ -0,0 +1,13 @@
1
+ """Compatibility exports; import strategy calculations from pybinbot.strategy.beta."""
2
+
3
+ from pybinbot.strategy.beta import (
4
+ DEFAULT_MIN_BETA_PERIODS,
5
+ latest_beta,
6
+ rolling_beta,
7
+ )
8
+
9
+ __all__ = [
10
+ "DEFAULT_MIN_BETA_PERIODS",
11
+ "latest_beta",
12
+ "rolling_beta",
13
+ ]
@@ -0,0 +1,21 @@
1
+ """Compatibility exports; import strategy calculations from pybinbot.strategy.breadth."""
2
+
3
+ from pybinbot.strategy.breadth import (
4
+ DEFAULT_BREADTH_EXTENSION_THRESHOLD,
5
+ DEFAULT_BREADTH_FAST_EMA_SPAN,
6
+ DEFAULT_MIN_BREADTH_HISTORY,
7
+ DEFAULT_MIN_TREND_HISTORY,
8
+ DEFAULT_TREND_EMA_SPAN,
9
+ breadth_momentum_reversal,
10
+ btc_trend_confirms,
11
+ )
12
+
13
+ __all__ = [
14
+ "DEFAULT_BREADTH_EXTENSION_THRESHOLD",
15
+ "DEFAULT_BREADTH_FAST_EMA_SPAN",
16
+ "DEFAULT_MIN_BREADTH_HISTORY",
17
+ "DEFAULT_MIN_TREND_HISTORY",
18
+ "DEFAULT_TREND_EMA_SPAN",
19
+ "breadth_momentum_reversal",
20
+ "btc_trend_confirms",
21
+ ]
@@ -0,0 +1,15 @@
1
+ """Compatibility exports; import strategy calculations from pybinbot.strategy.price_crossings."""
2
+
3
+ from pybinbot.strategy.price_crossings import (
4
+ CHOP_CROSSING_SCORE_PENALTY,
5
+ CHOP_CROSSING_THRESHOLD,
6
+ CHOP_LOOKBACK_HOURS,
7
+ price_crossings_six_hours,
8
+ )
9
+
10
+ __all__ = [
11
+ "CHOP_CROSSING_SCORE_PENALTY",
12
+ "CHOP_CROSSING_THRESHOLD",
13
+ "CHOP_LOOKBACK_HOURS",
14
+ "price_crossings_six_hours",
15
+ ]
@@ -1,7 +1,7 @@
1
1
  """Telegram delivery shared by synchronous trading and asynchronous analytics."""
2
2
 
3
3
  import asyncio
4
- from datetime import timedelta
4
+ from datetime import datetime, timedelta
5
5
  import logging
6
6
  import os
7
7
  import re
@@ -83,35 +83,64 @@ class TelegramDelivery:
83
83
  return retry_after.total_seconds()
84
84
  return float(retry_after)
85
85
 
86
- async def send(self, message: str) -> bool:
86
+ async def send(
87
+ self,
88
+ message: str,
89
+ *,
90
+ expires_at: datetime | None = None,
91
+ retry_on_rate_limit: bool = True,
92
+ ) -> bool:
93
+ """Deliver within an optional deadline, including time spent waiting to send."""
87
94
  if not self.token or not self.chat_id or self.bot is None:
88
95
  return False
89
- async with self._send_lock:
90
- while True:
91
- await self._sleep_for_send_interval()
92
- try:
93
- await self.bot.send_message(
94
- self.chat_id,
95
- text=self._sanitize_html(message),
96
- parse_mode=ParseMode.HTML,
97
- link_preview_options=LinkPreviewOptions(is_disabled=True),
98
- )
99
- self._last_send_at = time.monotonic()
100
- return True
101
- except RetryAfter as e:
102
- retry_after = self._retry_after_seconds(e)
103
- sleep_seconds = retry_after + self._retry_after_pad_seconds
104
- logging.warning(
105
- "Telegram flood control active; retrying message in %.1f seconds",
106
- sleep_seconds,
107
- )
108
- await asyncio.sleep(sleep_seconds)
109
- except TimedOut:
110
- logging.warning("Telegram message timed out; skipping")
111
- return False
112
- except Exception as exc:
113
- logging.warning("Telegram delivery failed (%s)", type(exc).__name__)
114
- return False
96
+ remaining = expires_at.timestamp() - time.time() if expires_at else None
97
+ if remaining is not None and remaining <= 0:
98
+ return False
99
+ try:
100
+ async with asyncio.timeout(remaining):
101
+ async with self._send_lock:
102
+ while True:
103
+ await self._sleep_for_send_interval()
104
+ if (
105
+ expires_at is not None
106
+ and time.time() >= expires_at.timestamp()
107
+ ):
108
+ return False
109
+ try:
110
+ await self.bot.send_message(
111
+ self.chat_id,
112
+ text=self._sanitize_html(message),
113
+ parse_mode=ParseMode.HTML,
114
+ link_preview_options=LinkPreviewOptions(
115
+ is_disabled=True
116
+ ),
117
+ )
118
+ self._last_send_at = time.monotonic()
119
+ return True
120
+ except RetryAfter as e:
121
+ if not retry_on_rate_limit:
122
+ logging.warning(
123
+ "Telegram rate limited; skipping one-shot alert"
124
+ )
125
+ return False
126
+ retry_after = self._retry_after_seconds(e)
127
+ sleep_seconds = retry_after + self._retry_after_pad_seconds
128
+ logging.warning(
129
+ "Telegram flood control active; retrying message in %.1f seconds",
130
+ sleep_seconds,
131
+ )
132
+ await asyncio.sleep(sleep_seconds)
133
+ except TimedOut:
134
+ logging.warning("Telegram message timed out; skipping")
135
+ return False
136
+ except Exception as exc:
137
+ logging.warning(
138
+ "Telegram delivery failed (%s)", type(exc).__name__
139
+ )
140
+ return False
141
+ except TimeoutError:
142
+ logging.info("Telegram alert expired before delivery completed; skipping")
143
+ return False
115
144
 
116
145
  def send_once(self, message: str) -> bool:
117
146
  """Attempt an ephemeral synchronous delivery, without retries or cooldowns."""
@@ -0,0 +1,167 @@
1
+ """Choose recent structural protection without clipping a distant swing."""
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from decimal import ROUND_CEILING, ROUND_FLOOR, Decimal
6
+ from math import isfinite
7
+
8
+ from pybinbot.shared.enums import Position
9
+
10
+
11
+ PROTECTION_INTERVALS_MINUTES = (15, 5, 1)
12
+ PROTECTION_LOOKBACK_MS = 3 * 60 * 60 * 1000
13
+ MAX_PROTECTION_DISTANCE_PCT = 2.5
14
+ MAX_PROTECTION_CANDLE_RANGE_PCT = 3.0
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SwingProtection:
19
+ interval_minutes: int
20
+ swing_open_time_ms: int
21
+ confirmation_time_ms: int
22
+ stop_price: float
23
+ distance_pct: float
24
+ candle_range_pct: float
25
+
26
+
27
+ def recent_swing_protection(
28
+ candles: Sequence[Sequence[float]],
29
+ *,
30
+ position: Position,
31
+ reference_price: float,
32
+ now_ms: int,
33
+ interval_minutes: int,
34
+ price_precision: int,
35
+ buffer_pct: float = 0.1,
36
+ max_distance_pct: float = MAX_PROTECTION_DISTANCE_PCT,
37
+ min_distance_pct: float = 0.0,
38
+ max_candle_range_pct: float = MAX_PROTECTION_CANDLE_RANGE_PCT,
39
+ lookback_ms: int = PROTECTION_LOOKBACK_MS,
40
+ not_before_ms: int = 0,
41
+ fractal_wing: int = 2,
42
+ ) -> SwingProtection | None:
43
+ """Evaluate only the latest confirmed swing in a bounded completed window.
44
+
45
+ Input rows use Binance-compatible millisecond OHLCV timestamps. Reject
46
+ incomplete, stale, gapped or invalid history. The swing and all bars used
47
+ to confirm it must be inside the lookback. Never search older swings when
48
+ the latest one is broken, too wide or on the wrong side of the reference.
49
+ Distances include the buffer and outward exchange-tick rounding.
50
+
51
+ Call with 15m, then 5m, then 1m candles until a candidate is returned.
52
+ Entry callers use the intended entry as reference; live trailing callers
53
+ use the current favorable price and separately enforce tightening only.
54
+ """
55
+ if (
56
+ position not in (Position.long, Position.short)
57
+ or interval_minutes not in PROTECTION_INTERVALS_MINUTES
58
+ or lookback_ms <= 0
59
+ or lookback_ms > PROTECTION_LOOKBACK_MS
60
+ or fractal_wing < 1
61
+ or price_precision < 0
62
+ or not all(
63
+ isfinite(value)
64
+ for value in (
65
+ reference_price,
66
+ buffer_pct,
67
+ max_distance_pct,
68
+ min_distance_pct,
69
+ max_candle_range_pct,
70
+ )
71
+ )
72
+ or reference_price <= 0
73
+ or not 0 <= buffer_pct < 100
74
+ or not 0 <= min_distance_pct < max_distance_pct <= 3
75
+ or not 0 < max_candle_range_pct <= 3
76
+ ):
77
+ return None
78
+ interval_ms = interval_minutes * 60 * 1000
79
+ window_end = now_ms // interval_ms * interval_ms
80
+ window_start = now_ms - lookback_ms
81
+ rows: list[tuple[int, float, float, float, float]] = []
82
+ try:
83
+ for candle in candles:
84
+ timestamp = float(candle[0])
85
+ if not isfinite(timestamp):
86
+ return None
87
+ if timestamp < window_start or timestamp >= window_end:
88
+ continue
89
+ if timestamp != int(timestamp) or int(timestamp) % interval_ms:
90
+ return None
91
+ opening, high, low, close = map(float, candle[1:5])
92
+ if (
93
+ not all(
94
+ isfinite(value) and value > 0
95
+ for value in (opening, high, low, close)
96
+ )
97
+ or not low <= min(opening, close) <= max(opening, close) <= high
98
+ or len(candle) < 7
99
+ or not timestamp <= float(candle[6]) < timestamp + interval_ms
100
+ ):
101
+ return None
102
+ rows.append((int(timestamp), opening, high, low, close))
103
+ except IndexError, TypeError, ValueError, OverflowError:
104
+ return None
105
+ rows.sort()
106
+ if (
107
+ len(rows) < 2 * fractal_wing + 1
108
+ or rows[-1][0] != window_end - interval_ms
109
+ or any(
110
+ later[0] - earlier[0] != interval_ms
111
+ for earlier, later in zip(rows, rows[1:])
112
+ )
113
+ ):
114
+ return None
115
+
116
+ short = position == Position.short
117
+ value_column = 2 if short else 3
118
+ swing_index = next(
119
+ (
120
+ index
121
+ for index in range(len(rows) - fractal_wing - 1, fractal_wing - 1, -1)
122
+ if rows[index][0] >= not_before_ms
123
+ and all(
124
+ (rows[index][value_column] > rows[neighbor][value_column])
125
+ if short
126
+ else (rows[index][value_column] < rows[neighbor][value_column])
127
+ for neighbor in range(index - fractal_wing, index + fractal_wing + 1)
128
+ if neighbor != index
129
+ )
130
+ ),
131
+ None,
132
+ )
133
+ if swing_index is None:
134
+ return None
135
+ timestamp, _opening, high, low, _close = rows[swing_index]
136
+ swing_price = high if short else low
137
+ if any(
138
+ row[value_column] >= swing_price if short else row[value_column] <= swing_price
139
+ for row in rows[swing_index + 1 :]
140
+ ):
141
+ return None
142
+ candle_range = (Decimal(str(high)) / Decimal(str(low)) - 1) * 100
143
+ if candle_range > Decimal(str(max_candle_range_pct)):
144
+ return None
145
+ direction = Decimal(1 if short else -1)
146
+ stop = (
147
+ Decimal(str(swing_price)) * (1 + direction * Decimal(str(buffer_pct)) / 100)
148
+ ).quantize(
149
+ Decimal(1).scaleb(-price_precision),
150
+ rounding=ROUND_CEILING if short else ROUND_FLOOR,
151
+ )
152
+ distance = direction * (stop / Decimal(str(reference_price)) - 1) * 100
153
+ if (
154
+ stop <= 0
155
+ or distance <= 0
156
+ or distance < Decimal(str(min_distance_pct))
157
+ or distance > Decimal(str(max_distance_pct))
158
+ ):
159
+ return None
160
+ return SwingProtection(
161
+ interval_minutes=interval_minutes,
162
+ swing_open_time_ms=timestamp,
163
+ confirmation_time_ms=rows[swing_index + fractal_wing][0] + interval_ms - 1,
164
+ stop_price=float(stop),
165
+ distance_pct=float(distance),
166
+ candle_range_pct=float(candle_range),
167
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.5
3
+ Version: 2.1.9
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -136,3 +136,39 @@ make tag
136
136
 
137
137
 
138
138
  For further commands take a look at the `Makefile` such as testing `make test`
139
+
140
+ ## Strategy calculations
141
+
142
+ Reusable pattern detection, signal gates and strategy risk calculations live in
143
+ `pybinbot.strategy`:
144
+
145
+ - `price_crossings`: six-hour candle-range and gap crossings for chop gates.
146
+ - `swing_protection`: recent confirmed swings for bounded protective prices.
147
+ - `beta`: rolling and latest return beta against BTC.
148
+ - `breadth`: breadth-momentum reversals and BTC-trend confirmation.
149
+
150
+ Import directly from the relevant module, for example:
151
+
152
+ ```python
153
+ from pybinbot.strategy.beta import rolling_beta
154
+ from pybinbot.strategy.price_crossings import price_crossings_six_hours
155
+ from pybinbot.strategy.swing_protection import recent_swing_protection
156
+ ```
157
+
158
+ The published `pybinbot.shared.beta`, `pybinbot.shared.breadth` and
159
+ `pybinbot.shared.price_crossings` paths remain as import aliases. Existing
160
+ package-level beta and breadth exports also remain available. General candle
161
+ processing, indicators, timestamps, exchange types and delivery utilities remain
162
+ in `pybinbot.shared`. New reusable strategy calculations belong in
163
+ `pybinbot.strategy`.
164
+
165
+ ## Recent swing protection
166
+
167
+ `pybinbot.strategy.swing_protection.recent_swing_protection` evaluates the latest
168
+ confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
169
+ that order when a candidate is unsuitable. The maximum search window is three
170
+ hours, optionally narrowed to one hour or to the start of the current setup.
171
+ The selector rejects swing candles wider than 3% and stop distances over 2.5%
172
+ after the buffer and outward tick rounding. It never clips a distant swing or
173
+ searches older swings to force a result. Entry callers skip when all timeframes
174
+ fail; live callers retain existing protection and only apply tighter stops.
@@ -27,6 +27,7 @@ pybinbot/models/bot_base.py
27
27
  pybinbot/models/cvd.py
28
28
  pybinbot/models/deal.py
29
29
  pybinbot/models/derivatives.py
30
+ pybinbot/models/fastest_movers.py
30
31
  pybinbot/models/grid_ladder.py
31
32
  pybinbot/models/order.py
32
33
  pybinbot/models/routes.py
@@ -48,6 +49,10 @@ pybinbot/shared/telegram_delivery.py
48
49
  pybinbot/shared/timestamps.py
49
50
  pybinbot/shared/types.py
50
51
  pybinbot/shared/utils.py
52
+ pybinbot/strategy/beta.py
53
+ pybinbot/strategy/breadth.py
54
+ pybinbot/strategy/price_crossings.py
55
+ pybinbot/strategy/swing_protection.py
51
56
  pybinbot/streaming/binance/async_socket_client.py
52
57
  pybinbot/streaming/binance/socket_client.py
53
58
  pybinbot/streaming/binance/socket_manager.py
@@ -64,6 +69,7 @@ tests/test_conditional_futures_orders.py
64
69
  tests/test_cvd_api.py
65
70
  tests/test_deal_model.py
66
71
  tests/test_derivatives_api.py
72
+ tests/test_fastest_movers.py
67
73
  tests/test_futures_place_order.py
68
74
  tests/test_grid_ladder.py
69
75
  tests/test_handlers.py
@@ -74,6 +80,7 @@ tests/test_logging_config.py
74
80
  tests/test_matching_engine.py
75
81
  tests/test_maths.py
76
82
  tests/test_price_crossings.py
83
+ tests/test_swing_protection.py
77
84
  tests/test_symbol_model.py
78
85
  tests/test_telegram_delivery.py
79
86
  tests/test_timestamps.py
@@ -2,6 +2,7 @@
2
2
  packages = [
3
3
  "pybinbot",
4
4
  "pybinbot.shared",
5
+ "pybinbot.strategy",
5
6
  "pybinbot.models",
6
7
  "pybinbot.apis",
7
8
  "pybinbot.apis.binance",
@@ -22,7 +23,7 @@ build-backend = "setuptools.build_meta"
22
23
 
23
24
  [project]
24
25
  name = "pybinbot"
25
- version = "2.1.5"
26
+ version = "2.1.9"
26
27
  description = "Utility functions for the binbot project."
27
28
  authors = [
28
29
  { name="Carlos Wu", email="carkodw@gmail.com" }
@@ -1,7 +1,7 @@
1
1
  import pandas as pd
2
2
  import pytest
3
3
 
4
- from pybinbot.shared import beta
4
+ from pybinbot.strategy import beta
5
5
 
6
6
  # From the illustrative example: the token consistently moves 1.5x BTC.
7
7
  BTC_RETURNS = [0.01, -0.02, 0.02, -0.01]
@@ -0,0 +1,89 @@
1
+ from datetime import UTC, datetime
2
+ from unittest.mock import AsyncMock, patch
3
+
4
+ import pytest
5
+ from pydantic import ValidationError
6
+
7
+ from pybinbot import BinbotApi, FastestMoversSnapshot
8
+
9
+
10
+ @pytest.fixture
11
+ def api() -> BinbotApi:
12
+ with patch.object(BinbotApi, "_login_service_account"):
13
+ return BinbotApi("https://example.com", "service@example.com", "password")
14
+
15
+
16
+ @pytest.mark.asyncio
17
+ async def test_fastest_movers_client_returns_typed_rankings_and_context(api: BinbotApi):
18
+ payload = {
19
+ "source": "kucoin_futures",
20
+ "recorded_at": "2026-11-27T12:00:00Z",
21
+ "comparison_at": "2026-11-27T11:00:00Z",
22
+ "gainers": [
23
+ {
24
+ "symbol": "SOLUSDTM",
25
+ "price_change_1h_percent": 4.2,
26
+ "price_change_3h_percent": 7.8,
27
+ "price_change_percent": 12.1,
28
+ "last_price": 150,
29
+ "turnover_24h": 1000000,
30
+ }
31
+ ],
32
+ "losers": [],
33
+ }
34
+ with patch.object(
35
+ api, "fetch", new=AsyncMock(return_value={"message": "OK", "data": payload})
36
+ ) as fetch:
37
+ snapshot = await api.get_fastest_movers(limit=5)
38
+
39
+ fetch.assert_awaited_once_with(
40
+ url="https://example.com/charts/fastest_movers", params={"limit": 5}
41
+ )
42
+ assert isinstance(snapshot, FastestMoversSnapshot)
43
+ assert snapshot.recorded_at == datetime(2026, 11, 27, 12, tzinfo=UTC)
44
+ assert snapshot.gainers[0].price_change_3h_percent == 7.8
45
+ assert snapshot.gainers[0].price_change_percent == 12.1
46
+
47
+
48
+ @pytest.mark.asyncio
49
+ async def test_fastest_movers_preserves_waiting_for_history_state(api: BinbotApi):
50
+ with patch.object(
51
+ api,
52
+ "fetch",
53
+ new=AsyncMock(
54
+ return_value={
55
+ "message": "OK",
56
+ "data": {
57
+ "source": "kucoin_futures",
58
+ "recorded_at": None,
59
+ "comparison_at": None,
60
+ "gainers": [],
61
+ "losers": [],
62
+ },
63
+ }
64
+ ),
65
+ ):
66
+ snapshot = await api.get_fastest_movers()
67
+ assert snapshot.recorded_at is None
68
+ assert snapshot.comparison_at is None
69
+ assert snapshot.gainers == []
70
+
71
+
72
+ @pytest.mark.asyncio
73
+ async def test_fastest_movers_does_not_turn_api_failure_into_empty_membership(
74
+ api: BinbotApi,
75
+ ):
76
+ with patch.object(api, "fetch", new=AsyncMock(return_value={"data": None})):
77
+ with pytest.raises(ValidationError):
78
+ await api.get_fastest_movers()
79
+
80
+
81
+ def test_fastest_movers_rejects_ambiguous_snapshot_timezone():
82
+ with pytest.raises(ValidationError):
83
+ FastestMoversSnapshot(
84
+ source="kucoin_futures",
85
+ recorded_at=datetime(2026, 11, 27, 12),
86
+ comparison_at=None,
87
+ gainers=[],
88
+ losers=[],
89
+ )
@@ -1,7 +1,7 @@
1
1
  import pytest
2
2
  from pandas import DataFrame
3
3
 
4
- from pybinbot.shared.price_crossings import price_crossings_six_hours
4
+ from pybinbot.strategy.price_crossings import price_crossings_six_hours
5
5
 
6
6
  INTERVAL_MS = 15 * 60 * 1000
7
7
  NOW_MS = 1_800_000_000_000 // INTERVAL_MS * INTERVAL_MS + 30_000
@@ -0,0 +1,153 @@
1
+ from copy import deepcopy
2
+
3
+ import pytest
4
+
5
+ from pybinbot import Position
6
+ from pybinbot.strategy.swing_protection import recent_swing_protection
7
+
8
+
9
+ NOW_MS = 1_800_000_000_000
10
+
11
+
12
+ def candles(interval=15, *, high=102.0, count=12):
13
+ interval_ms = interval * 60_000
14
+ highs = [100.0] * (count - 5) + [100, 101, high, 101, 100]
15
+ return [
16
+ [
17
+ NOW_MS - (count - index) * interval_ms,
18
+ value - 0.1,
19
+ value,
20
+ value - 0.2,
21
+ value - 0.1,
22
+ 10,
23
+ NOW_MS - (count - index - 1) * interval_ms - 1,
24
+ ]
25
+ for index, value in enumerate(highs)
26
+ ]
27
+
28
+
29
+ def resolve(rows, *, interval=15, position=Position.short, **kwargs):
30
+ return recent_swing_protection(
31
+ rows,
32
+ position=position,
33
+ reference_price=100,
34
+ now_ms=NOW_MS,
35
+ interval_minutes=interval,
36
+ price_precision=4,
37
+ **kwargs,
38
+ )
39
+
40
+
41
+ @pytest.mark.parametrize("interval", [15, 5, 1])
42
+ @pytest.mark.parametrize("position", [Position.long, Position.short])
43
+ def test_recent_confirmed_swing_protects_each_direction_at_each_timeframe(
44
+ interval, position
45
+ ):
46
+ rows = candles(interval)
47
+ if position == Position.long:
48
+ rows = [
49
+ [t, 200 - o, 200 - low, 200 - high, 200 - c, v, end]
50
+ for t, o, high, low, c, v, end in rows
51
+ ]
52
+
53
+ result = resolve(rows, interval=interval, position=position)
54
+
55
+ assert result is not None
56
+ assert result.interval_minutes == interval
57
+ assert result.swing_open_time_ms == NOW_MS - 3 * interval * 60_000
58
+ assert result.confirmation_time_ms == NOW_MS - 1
59
+ assert 2 < result.distance_pct < 2.5
60
+ assert (
61
+ result.stop_price > 100
62
+ if position == Position.short
63
+ else result.stop_price < 100
64
+ )
65
+
66
+
67
+ def test_six_percent_candle_requires_a_smaller_timeframe_even_with_a_nearby_peak():
68
+ rows = candles()
69
+ rows[-3][3] = 95
70
+
71
+ assert resolve(rows) is None
72
+ assert resolve(candles(5), interval=5) is not None
73
+
74
+
75
+ def test_tiny_candles_cannot_hide_a_stop_more_than_two_and_a_half_percent_away():
76
+ assert resolve(candles(high=106.35)) is None
77
+
78
+
79
+ def test_stop_distance_includes_buffer_and_outward_tick_rounding():
80
+ assert resolve(candles(), buffer_pct=0.5) is None
81
+ result = resolve(candles(high=101.99991))
82
+ assert result is not None
83
+ assert result.stop_price == 102.102
84
+ assert result.distance_pct == pytest.approx(2.102)
85
+
86
+
87
+ @pytest.mark.parametrize("high,qualifies", [(102.5, True), (102.5001, False)])
88
+ def test_stop_distance_cap_is_inclusive_without_clipping(high, qualifies):
89
+ assert (resolve(candles(high=high), buffer_pct=0) is not None) is qualifies
90
+
91
+
92
+ def test_unclosed_candle_cannot_confirm_a_swing():
93
+ rows = candles()
94
+ rows[-1][0] += 15 * 60_000
95
+ rows[-1][6] += 15 * 60_000
96
+ assert resolve(rows) is None
97
+
98
+
99
+ @pytest.mark.parametrize("problem", ["stale", "gap", "duplicate", "nan", "ohlc"])
100
+ def test_invalid_or_incomplete_history_cannot_place_protection(problem):
101
+ rows = candles()
102
+ if problem == "stale":
103
+ rows.pop()
104
+ elif problem == "gap":
105
+ rows.pop(-4)
106
+ elif problem == "duplicate":
107
+ rows.append(deepcopy(rows[-1]))
108
+ elif problem == "nan":
109
+ rows[-4][2] = float("nan")
110
+ else:
111
+ rows[-4][3] = rows[-4][2] + 1
112
+ assert resolve(rows) is None
113
+
114
+
115
+ def test_cannot_resurrect_a_swing_older_than_three_hours():
116
+ rows = candles(count=24)
117
+ for row in rows:
118
+ row[0] -= 3 * 60 * 60_000
119
+ row[6] -= 3 * 60 * 60_000
120
+ rows.extend(
121
+ [
122
+ [
123
+ NOW_MS - (12 - i) * 900_000,
124
+ 100,
125
+ 100.1,
126
+ 99.9,
127
+ 100,
128
+ 10,
129
+ NOW_MS - (11 - i) * 900_000 - 1,
130
+ ]
131
+ for i in range(12)
132
+ ]
133
+ )
134
+ assert resolve(rows) is None
135
+
136
+
137
+ def test_swing_window_can_be_restricted_to_one_hour_or_the_current_setup():
138
+ rows = candles()
139
+ assert resolve(rows, lookback_ms=60 * 60_000) is None # Only four 15m bars.
140
+ assert resolve(rows, not_before_ms=NOW_MS - 30 * 60_000) is None
141
+ assert resolve(rows, lookback_ms=4 * 60 * 60_000) is None
142
+
143
+
144
+ def test_latest_unconfirmed_break_invalidates_the_old_peak():
145
+ rows = candles(count=14)
146
+ rows[-1][2] = 103
147
+ assert resolve(rows) is None
148
+
149
+
150
+ def test_latest_wide_swing_does_not_fall_back_to_an_arbitrary_older_peak():
151
+ rows = candles(high=106.35)
152
+ rows[3][2] = 101
153
+ assert resolve(rows) is None
@@ -1,3 +1,5 @@
1
+ import asyncio
2
+ from datetime import UTC, datetime, timedelta
1
3
  from unittest.mock import AsyncMock, patch
2
4
 
3
5
  import pytest
@@ -85,3 +87,63 @@ async def test_async_delivery_keeps_binquant_flood_control_retry():
85
87
  )
86
88
  assert await delivery.send("Signal") is True
87
89
  assert bot.return_value.send_message.await_count == 2
90
+
91
+
92
+ @pytest.mark.asyncio
93
+ async def test_one_shot_alert_does_not_retry_rate_limited_send():
94
+ with patch("pybinbot.shared.telegram_delivery.Bot") as bot:
95
+ bot.return_value.send_message = AsyncMock(side_effect=RetryAfter(60))
96
+ delivery = TelegramDelivery(token="test-token", chat_id="test-chat")
97
+ assert await delivery.send("Signal", retry_on_rate_limit=False) is False
98
+ bot.return_value.send_message.assert_awaited_once()
99
+
100
+
101
+ @pytest.mark.asyncio
102
+ async def test_expired_alert_is_never_submitted_to_telegram():
103
+ with patch("pybinbot.shared.telegram_delivery.Bot") as bot:
104
+ bot.return_value.send_message = AsyncMock()
105
+ delivery = TelegramDelivery(token="test-token", chat_id="test-chat")
106
+ assert (
107
+ await delivery.send(
108
+ "Signal", expires_at=datetime.now(UTC) - timedelta(seconds=1)
109
+ )
110
+ is False
111
+ )
112
+ bot.return_value.send_message.assert_not_awaited()
113
+
114
+
115
+ @pytest.mark.asyncio
116
+ async def test_alert_expires_while_waiting_for_another_send():
117
+ with patch("pybinbot.shared.telegram_delivery.Bot") as bot:
118
+ bot.return_value.send_message = AsyncMock()
119
+ delivery = TelegramDelivery(token="test-token", chat_id="test-chat")
120
+ async with delivery._send_lock:
121
+ assert (
122
+ await delivery.send(
123
+ "Signal", expires_at=datetime.now(UTC) + timedelta(milliseconds=20)
124
+ )
125
+ is False
126
+ )
127
+ bot.return_value.send_message.assert_not_awaited()
128
+
129
+
130
+ @pytest.mark.asyncio
131
+ async def test_delivery_deadline_cancels_a_stalled_request():
132
+ with patch("pybinbot.shared.telegram_delivery.Bot") as bot:
133
+ cancelled = asyncio.Event()
134
+
135
+ async def stalled_send(*args, **kwargs):
136
+ try:
137
+ await asyncio.Event().wait()
138
+ finally:
139
+ cancelled.set()
140
+
141
+ bot.return_value.send_message = AsyncMock(side_effect=stalled_send)
142
+ delivery = TelegramDelivery(token="test-token", chat_id="test-chat")
143
+ assert (
144
+ await delivery.send(
145
+ "Signal", expires_at=datetime.now(UTC) + timedelta(milliseconds=20)
146
+ )
147
+ is False
148
+ )
149
+ assert cancelled.is_set()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes