pybinbot 2.1.19__tar.gz → 2.2.0__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 (92) hide show
  1. {pybinbot-2.1.19/pybinbot.egg-info → pybinbot-2.2.0}/PKG-INFO +1 -14
  2. {pybinbot-2.1.19 → pybinbot-2.2.0}/README.md +0 -13
  3. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/binbot/base.py +0 -93
  4. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/autotrade_settings.py +1 -1
  5. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/bot.py +1 -3
  6. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/bot_base.py +2 -4
  7. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/enums.py +0 -1
  8. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/telegram_delivery.py +48 -76
  9. {pybinbot-2.1.19 → pybinbot-2.2.0/pybinbot.egg-info}/PKG-INFO +1 -14
  10. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot.egg-info/SOURCES.txt +0 -1
  11. {pybinbot-2.1.19 → pybinbot-2.2.0}/pyproject.toml +1 -1
  12. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_binbot_api.py +1 -6
  13. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_telegram_delivery.py +2 -111
  14. pybinbot-2.1.19/tests/test_binbot_read_methods.py +0 -194
  15. {pybinbot-2.1.19 → pybinbot-2.2.0}/LICENSE +0 -0
  16. {pybinbot-2.1.19 → pybinbot-2.2.0}/MANIFEST.in +0 -0
  17. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/__init__.py +0 -0
  18. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/binance/base.py +0 -0
  19. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/binance/exceptions.py +0 -0
  20. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/binbot/exceptions.py +0 -0
  21. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/coingecko.py +0 -0
  22. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/kucoin/base.py +0 -0
  23. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/kucoin/exceptions.py +0 -0
  24. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/kucoin/futures.py +0 -0
  25. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/kucoin/market.py +0 -0
  26. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/kucoin/orders.py +0 -0
  27. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/apis/kucoin/rest.py +0 -0
  28. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/__init__.py +0 -0
  29. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/cvd.py +0 -0
  30. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/deal.py +0 -0
  31. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/derivatives.py +0 -0
  32. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/fastest_movers.py +0 -0
  33. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/futures_market.py +0 -0
  34. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/grid_ladder.py +0 -0
  35. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/order.py +0 -0
  36. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/routes.py +0 -0
  37. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/signals.py +0 -0
  38. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/models/symbol.py +0 -0
  39. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/py.typed +0 -0
  40. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/__init__.py +0 -0
  41. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/beta.py +0 -0
  42. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/breadth.py +0 -0
  43. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/cache.py +0 -0
  44. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/candles.py +0 -0
  45. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/handlers.py +0 -0
  46. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/heikin_ashi.py +0 -0
  47. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/indicators.py +0 -0
  48. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/logging_config.py +0 -0
  49. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/maths.py +0 -0
  50. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/price_crossings.py +0 -0
  51. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/timestamps.py +0 -0
  52. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/types.py +0 -0
  53. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/shared/utils.py +0 -0
  54. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/strategy/beta.py +0 -0
  55. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/strategy/breadth.py +0 -0
  56. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/strategy/price_crossings.py +0 -0
  57. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/strategy/swing_protection.py +0 -0
  58. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/streaming/binance/async_socket_client.py +0 -0
  59. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/streaming/binance/socket_client.py +0 -0
  60. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/streaming/binance/socket_manager.py +0 -0
  61. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
  62. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot.egg-info/dependency_links.txt +0 -0
  63. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot.egg-info/requires.txt +0 -0
  64. {pybinbot-2.1.19 → pybinbot-2.2.0}/pybinbot.egg-info/top_level.txt +0 -0
  65. {pybinbot-2.1.19 → pybinbot-2.2.0}/setup.cfg +0 -0
  66. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_beta.py +0 -0
  67. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_bot_futures_leverage.py +0 -0
  68. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_breadth.py +0 -0
  69. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_candles.py +0 -0
  70. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_closed_bot_status.py +0 -0
  71. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_coingecko.py +0 -0
  72. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_conditional_entry.py +0 -0
  73. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_conditional_futures_orders.py +0 -0
  74. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_cvd_api.py +0 -0
  75. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_deal_model.py +0 -0
  76. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_derivatives_api.py +0 -0
  77. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_fastest_movers.py +0 -0
  78. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_futures_market_api.py +0 -0
  79. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_futures_place_order.py +0 -0
  80. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_grid_ladder.py +0 -0
  81. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_handlers.py +0 -0
  82. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_heikin_ashi.py +0 -0
  83. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_indicators.py +0 -0
  84. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_kucoin_api.py +0 -0
  85. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_logging_config.py +0 -0
  86. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_matching_engine.py +0 -0
  87. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_maths.py +0 -0
  88. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_price_crossings.py +0 -0
  89. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_swing_protection.py +0 -0
  90. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_symbol_model.py +0 -0
  91. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_timestamps.py +0 -0
  92. {pybinbot-2.1.19 → pybinbot-2.2.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.19
3
+ Version: 2.2.0
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -106,19 +106,6 @@ rate-limit retries and optional spacing configured at initialization. Both use
106
106
  HTML formatting and disable link previews. Delivery does not persist messages.
107
107
  The Telegram library is installed as a dependency of pybinbot.
108
108
 
109
- Use `await send_message(message, reply_markup=..., reply_to_message_id=...)`
110
- when the caller needs Telegram's delivered `Message` (including `message_id`) or
111
- must handle delivery errors itself. It shares HTML formatting, preview settings,
112
- spacing and `expires_at` deadlines with `send`, but raises failures and does not
113
- retry rate limits unless `retry_on_rate_limit=True`. Timed-out sends are never
114
- retried because delivery may already have succeeded.
115
-
116
- Pass `bot=existing_bot` and an explicit `chat_id` to reuse an initialized client;
117
- the caller remains responsible for its initialization and shutdown. An explicit
118
- `token` overrides environment configuration, including for dedicated agent bots.
119
- Delivery does not receive callbacks, persist approvals or authorize updates;
120
- those remain application responsibilities.
121
-
122
109
 
123
110
  ## Publishing
124
111
 
@@ -77,19 +77,6 @@ rate-limit retries and optional spacing configured at initialization. Both use
77
77
  HTML formatting and disable link previews. Delivery does not persist messages.
78
78
  The Telegram library is installed as a dependency of pybinbot.
79
79
 
80
- Use `await send_message(message, reply_markup=..., reply_to_message_id=...)`
81
- when the caller needs Telegram's delivered `Message` (including `message_id`) or
82
- must handle delivery errors itself. It shares HTML formatting, preview settings,
83
- spacing and `expires_at` deadlines with `send`, but raises failures and does not
84
- retry rate limits unless `retry_on_rate_limit=True`. Timed-out sends are never
85
- retried because delivery may already have succeeded.
86
-
87
- Pass `bot=existing_bot` and an explicit `chat_id` to reuse an initialized client;
88
- the caller remains responsible for its initialization and shutdown. An explicit
89
- `token` overrides environment configuration, including for dedicated agent bots.
90
- Delivery does not receive callbacks, persist approvals or authorize updates;
91
- those remain application responsibilities.
92
-
93
80
 
94
81
  ## Publishing
95
82
 
@@ -1,7 +1,6 @@
1
1
  import asyncio
2
2
  import logging
3
3
  from typing import Any
4
- from uuid import UUID
5
4
  from aiohttp import ClientSession
6
5
  from requests import Session
7
6
  from pybinbot import (
@@ -32,12 +31,6 @@ from dateutil.parser import parse
32
31
  from pybinbot.models.cvd import CvdAggregateResponse, CvdSymbolResponse
33
32
  from pybinbot.models.fastest_movers import FastestMoversResponse, FastestMoversSnapshot
34
33
  from pybinbot.models.futures_market import FuturesMarketSnapshot
35
- from pybinbot.models.bot import BotListResponse
36
- from pybinbot.models.signals import SignalListRecord, SignalListResponse
37
- from pybinbot.apis.binbot.exceptions import BinbotErrors
38
- from kucoin_universal_sdk.generate.futures.positions.model_get_position_details_resp import (
39
- GetPositionDetailsResp,
40
- )
41
34
 
42
35
  logger = logging.getLogger(__name__)
43
36
 
@@ -87,7 +80,6 @@ class BinbotApi:
87
80
  self.bb_market_breadth_url = f"{bb_base_url}/charts/market-breadth"
88
81
  self.bb_cvd_symbol_url = f"{bb_base_url}/charts/cvd-symbol"
89
82
  self.bb_futures_market_url = f"{bb_base_url}/charts/futures-market"
90
- self.bb_futures_position_url = f"{bb_base_url}/order/kucoin/futures/position"
91
83
  self.bb_cvd_aggregate_url = f"{bb_base_url}/charts/cvd-aggregate"
92
84
  self.bb_gainers_losers_series_url = (
93
85
  f"{bb_base_url}/charts/gainers-losers-series"
@@ -298,91 +290,6 @@ class BinbotApi:
298
290
  response = self.request(url=f"{self.bb_bot_url}/{bot_id}")
299
291
  return BotModel.model_validate(response["data"])
300
292
 
301
- def get_bots(
302
- self,
303
- *,
304
- status: Status | None = None,
305
- include_closed: bool = False,
306
- start_date: int | None = None,
307
- end_date: int | None = None,
308
- bot_name: str | None = None,
309
- page_size: int = 200,
310
- ) -> list[BotModel]:
311
- """Return all matching bots, paging through the API and deduplicating UUIDs."""
312
- if page_size <= 0:
313
- raise ValueError("page_size must be positive")
314
- filters = {
315
- "include_closed": include_closed,
316
- "status": status.value if status is not None else None,
317
- "start_date": start_date,
318
- "end_date": end_date,
319
- "bot_name": bot_name,
320
- }
321
- params = {key: value for key, value in filters.items() if value is not None}
322
- bots: dict[UUID, BotModel] = {}
323
- offset = 0
324
- while True:
325
- payload = self.request(
326
- url=self.bb_bot_url,
327
- params={**params, "limit": page_size, "offset": offset},
328
- timeout=(5, 30),
329
- )
330
- response = BotListResponse.model_validate(payload)
331
- if response.error:
332
- raise BinbotErrors(response.message, response.error)
333
- bots.update((bot.id, bot) for bot in response.data)
334
- if len(response.data) < page_size:
335
- return list(bots.values())
336
- offset += len(response.data)
337
-
338
- def get_futures_position(self, symbol: str) -> GetPositionDetailsResp:
339
- """Read the live KuCoin futures position through binbot's authenticated proxy."""
340
- response = self.request(
341
- url=f"{self.bb_futures_position_url}/{symbol.upper()}",
342
- timeout=(5, 30),
343
- )
344
- if response.get("error"):
345
- raise BinbotErrors(response["message"], response["error"])
346
- return GetPositionDetailsResp.model_validate(response["data"])
347
-
348
- def get_signals(
349
- self,
350
- *,
351
- symbol: str | None = None,
352
- algorithm_name: str | None = None,
353
- current_regime: str | None = None,
354
- autotrade: bool | None = None,
355
- since: datetime | None = None,
356
- until: datetime | None = None,
357
- limit: int = 100,
358
- offset: int = 0,
359
- include_payload: bool = True,
360
- ) -> list[SignalListRecord]:
361
- """Read a typed page of stored signals, including optional indicator payloads."""
362
- if not 1 <= limit <= 1000 or offset < 0:
363
- raise ValueError(
364
- "Signals require limit between 1 and 1000 and a nonnegative offset"
365
- )
366
- filters = {
367
- "symbol": symbol.upper() if symbol is not None else None,
368
- "algorithm_name": algorithm_name,
369
- "current_regime": current_regime,
370
- "autotrade": autotrade,
371
- "since": since.isoformat() if since is not None else None,
372
- "until": until.isoformat() if until is not None else None,
373
- "limit": limit,
374
- "offset": offset,
375
- "include_payload": include_payload,
376
- }
377
- response = self.request(
378
- url=self.bb_signals_url,
379
- params={key: value for key, value in filters.items() if value is not None},
380
- timeout=(5, 30),
381
- )
382
- if response.get("error"):
383
- raise BinbotErrors(response["message"], response["error"])
384
- return SignalListResponse.model_validate(response).data
385
-
386
293
  def get_futures_market(self, symbol: str) -> FuturesMarketSnapshot:
387
294
  """Read live contract, book, trades and candles for one futures symbol.
388
295
 
@@ -12,7 +12,7 @@ from pybinbot.shared.enums import (
12
12
  class AutotradeSettingsSchema(BaseModel):
13
13
  id: AutotradeSettingsDocument = AutotradeSettingsDocument.settings
14
14
  close_condition: CloseConditions = Field(
15
- default=CloseConditions.dynamic_trailing,
15
+ default=CloseConditions.timestamp,
16
16
  )
17
17
  autotrade: bool = Field(default=False)
18
18
  updated_at: float = Field(default_factory=lambda: time() * 1000)
@@ -61,7 +61,6 @@ class BotModel(BotBase):
61
61
  "trailling": "trailing",
62
62
  "trailling_deviation": "trailing_deviation",
63
63
  "trailling_profit": "trailing_profit",
64
- "dynamic_trailling": "dynamic_trailing",
65
64
  }
66
65
  for old, new in renames.items():
67
66
  if old in values and new not in values:
@@ -97,11 +96,10 @@ class BotModel(BotBase):
97
96
  "quote_asset": "USDC",
98
97
  "fiat_order_size": 15,
99
98
  "candlestick_interval": "15m",
100
- "close_condition": "dynamic_trailing",
99
+ "close_condition": "timestamp",
101
100
  "cooldown": 0,
102
101
  "created_at": 1702999999.0,
103
102
  "updated_at": 1702999999.0,
104
- "dynamic_trailing": False,
105
103
  "logs": [],
106
104
  "mode": "manual",
107
105
  "name": "Default bot",
@@ -41,7 +41,7 @@ class BotBase(BaseModel):
41
41
  candlestick_interval: BinanceKlineIntervals = Field(
42
42
  default=BinanceKlineIntervals.fifteen_minutes
43
43
  )
44
- close_condition: CloseConditions = Field(default=CloseConditions.dynamic_trailing)
44
+ close_condition: CloseConditions = Field(default=CloseConditions.timestamp)
45
45
  cooldown: int = Field(
46
46
  default=0,
47
47
  ge=0,
@@ -57,7 +57,6 @@ class BotBase(BaseModel):
57
57
  allow_inf_nan=False,
58
58
  description="Absolute entry deadline in Unix milliseconds; defaults to creation + 15 minutes",
59
59
  )
60
- dynamic_trailing: bool = Field(default=False)
61
60
  dynamic_position_sizing: bool = Field(default=False)
62
61
  logs: list = Field(default=[])
63
62
  mode: str = Field(default="manual")
@@ -93,11 +92,10 @@ class BotBase(BaseModel):
93
92
  "quote_asset": "USDC",
94
93
  "fiat_order_size": 15,
95
94
  "candlestick_interval": "15m",
96
- "close_condition": "dynamic_trailing",
95
+ "close_condition": "timestamp",
97
96
  "cooldown": 0,
98
97
  "created_at": 1702999999.0,
99
98
  "updated_at": 1702999999.0,
100
- "dynamic_trailing": False,
101
99
  "logs": [],
102
100
  "mode": "manual",
103
101
  "market_type": "SPOT",
@@ -14,7 +14,6 @@ class DealType(str, Enum):
14
14
 
15
15
 
16
16
  class CloseConditions(str, Enum):
17
- dynamic_trailing = "dynamic_trailing"
18
17
  # No trailing, standard stop loss
19
18
  timestamp = "timestamp"
20
19
  # binbot-research param (self.market_trend_reversal)
@@ -9,7 +9,7 @@ import time
9
9
 
10
10
  from dotenv import find_dotenv, load_dotenv
11
11
  from requests import post
12
- from telegram import Bot, InlineKeyboardMarkup, LinkPreviewOptions, Message
12
+ from telegram import Bot, LinkPreviewOptions
13
13
  from telegram.constants import ParseMode
14
14
  from telegram.error import RetryAfter, TimedOut
15
15
  from telegram.helpers import escape
@@ -21,21 +21,15 @@ class TelegramDelivery:
21
21
  def __init__(
22
22
  self,
23
23
  token: str | None = None,
24
- chat_id: str | int | None = None,
24
+ chat_id: str | None = None,
25
25
  *,
26
- bot: Bot | None = None,
27
26
  min_send_interval_seconds: float = 0,
28
27
  retry_after_pad_seconds: float = 2,
29
28
  ) -> None:
30
- if token is None and bot is not None:
31
- token = bot.token
32
- if token is None or chat_id is None:
33
- load_dotenv(find_dotenv(usecwd=True))
29
+ load_dotenv(find_dotenv(usecwd=True))
34
30
  self.token = os.getenv("TELEGRAM_BOT_KEY", "") if token is None else token
35
31
  self.chat_id = os.getenv("TELEGRAM_USER_ID", "") if chat_id is None else chat_id
36
- self.bot = bot
37
- if self.bot is None and self.token:
38
- self.bot = Bot(token=self.token)
32
+ self.bot = Bot(token=self.token) if self.token else None
39
33
  self._send_lock = asyncio.Lock()
40
34
  self._min_send_interval_seconds = min_send_interval_seconds
41
35
  self._retry_after_pad_seconds = retry_after_pad_seconds
@@ -99,76 +93,54 @@ class TelegramDelivery:
99
93
  """Deliver within an optional deadline, including time spent waiting to send."""
100
94
  if not self.token or not self.chat_id or self.bot is None:
101
95
  return False
102
- try:
103
- await self.send_message(
104
- message,
105
- expires_at=expires_at,
106
- retry_on_rate_limit=retry_on_rate_limit,
107
- )
108
- return True
109
- except RetryAfter:
110
- logging.warning("Telegram rate limited; skipping one-shot alert")
111
- return False
112
- except TimedOut:
113
- logging.warning("Telegram message timed out; skipping")
96
+ remaining = expires_at.timestamp() - time.time() if expires_at else None
97
+ if remaining is not None and remaining <= 0:
114
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
115
141
  except TimeoutError:
116
142
  logging.info("Telegram alert expired before delivery completed; skipping")
117
143
  return False
118
- except Exception as exc:
119
- logging.warning("Telegram delivery failed (%s)", type(exc).__name__)
120
- return False
121
-
122
- async def send_message(
123
- self,
124
- message: str,
125
- *,
126
- reply_markup: InlineKeyboardMarkup | None = None,
127
- reply_to_message_id: int | None = None,
128
- expires_at: datetime | None = None,
129
- retry_on_rate_limit: bool = False,
130
- ) -> Message:
131
- """Return the delivered message or raise; the caller owns an injected bot.
132
-
133
- A deadline includes queueing, pacing and network time. Only rate-limit
134
- rejections may be retried, when explicitly enabled; ambiguous failures
135
- such as a timed-out send are never retried.
136
- """
137
- if not self.chat_id or self.bot is None:
138
- raise ValueError("Telegram delivery requires a bot and destination chat")
139
- remaining = expires_at.timestamp() - time.time() if expires_at else None
140
- if remaining is not None and remaining <= 0:
141
- raise TimeoutError("Telegram message expired before delivery")
142
- async with asyncio.timeout(remaining):
143
- async with self._send_lock:
144
- while True:
145
- await self._sleep_for_send_interval()
146
- if expires_at is not None and time.time() >= expires_at.timestamp():
147
- raise TimeoutError("Telegram message expired before delivery")
148
- try:
149
- sent = await self.bot.send_message(
150
- chat_id=self.chat_id,
151
- text=self._sanitize_html(message),
152
- parse_mode=ParseMode.HTML,
153
- link_preview_options=LinkPreviewOptions(is_disabled=True),
154
- reply_markup=reply_markup,
155
- reply_to_message_id=reply_to_message_id,
156
- )
157
- except RetryAfter as error:
158
- if not retry_on_rate_limit:
159
- raise
160
- sleep_seconds = (
161
- self._retry_after_seconds(error)
162
- + self._retry_after_pad_seconds
163
- )
164
- logging.warning(
165
- "Telegram flood control active; retrying message in %.1f seconds",
166
- sleep_seconds,
167
- )
168
- await asyncio.sleep(sleep_seconds)
169
- else:
170
- self._last_send_at = time.monotonic()
171
- return sent
172
144
 
173
145
  def send_once(self, message: str) -> bool:
174
146
  """Attempt an ephemeral synchronous delivery, without retries or cooldowns."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.19
3
+ Version: 2.2.0
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -106,19 +106,6 @@ rate-limit retries and optional spacing configured at initialization. Both use
106
106
  HTML formatting and disable link previews. Delivery does not persist messages.
107
107
  The Telegram library is installed as a dependency of pybinbot.
108
108
 
109
- Use `await send_message(message, reply_markup=..., reply_to_message_id=...)`
110
- when the caller needs Telegram's delivered `Message` (including `message_id`) or
111
- must handle delivery errors itself. It shares HTML formatting, preview settings,
112
- spacing and `expires_at` deadlines with `send`, but raises failures and does not
113
- retry rate limits unless `retry_on_rate_limit=True`. Timed-out sends are never
114
- retried because delivery may already have succeeded.
115
-
116
- Pass `bot=existing_bot` and an explicit `chat_id` to reuse an initialized client;
117
- the caller remains responsible for its initialization and shutdown. An explicit
118
- `token` overrides environment configuration, including for dedicated agent bots.
119
- Delivery does not receive callbacks, persist approvals or authorize updates;
120
- those remain application responsibilities.
121
-
122
109
 
123
110
  ## Publishing
124
111
 
@@ -60,7 +60,6 @@ pybinbot/streaming/binance/socket_manager.py
60
60
  pybinbot/streaming/kucoin/kucoin_async_client.py
61
61
  tests/test_beta.py
62
62
  tests/test_binbot_api.py
63
- tests/test_binbot_read_methods.py
64
63
  tests/test_bot_futures_leverage.py
65
64
  tests/test_breadth.py
66
65
  tests/test_candles.py
@@ -23,7 +23,7 @@ build-backend = "setuptools.build_meta"
23
23
 
24
24
  [project]
25
25
  name = "pybinbot"
26
- version = "2.1.19"
26
+ version = "2.2.0"
27
27
  description = "Utility functions for the binbot project."
28
28
  authors = [
29
29
  { name="Carlos Wu", email="carkodw@gmail.com" }
@@ -9,11 +9,7 @@ from unittest.mock import patch
9
9
 
10
10
  from pydantic import BaseModel, ConfigDict, Field, create_model
11
11
 
12
- from pybinbot.models.bot import (
13
- BotModel,
14
- BotListResponse,
15
- BotResponse as ProductionBotResponse,
16
- )
12
+ from pybinbot.models.bot import BotModel, BotResponse as ProductionBotResponse
17
13
  from pybinbot.models.signals import SignalCreate, SignalModel, SignalResponse
18
14
  from pybinbot.shared.enums import ExchangeId
19
15
 
@@ -187,7 +183,6 @@ def load_binbot_api_class():
187
183
 
188
184
  bot_stub = types.ModuleType("pybinbot.models.bot")
189
185
  bot_stub.BotModel = _BotModel
190
- bot_stub.BotListResponse = BotListResponse
191
186
  bot_stub.BotResponse = _BotResponse
192
187
  bot_stub.ErrorsRequestBody = _ErrorsRequestBody
193
188
  bot_stub.BulkDeleteRequest = _BulkDeleteRequest
@@ -1,10 +1,9 @@
1
1
  import asyncio
2
2
  from datetime import UTC, datetime, timedelta
3
- from unittest.mock import AsyncMock, Mock, patch
3
+ from unittest.mock import AsyncMock, patch
4
4
 
5
5
  import pytest
6
- from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Message
7
- from telegram.error import BadRequest, RetryAfter, TimedOut
6
+ from telegram.error import RetryAfter
8
7
 
9
8
  from pybinbot.shared.telegram_delivery import TelegramDelivery
10
9
 
@@ -148,111 +147,3 @@ async def test_delivery_deadline_cancels_a_stalled_request():
148
147
  is False
149
148
  )
150
149
  assert cancelled.is_set()
151
-
152
-
153
- @pytest.mark.asyncio
154
- async def test_message_delivery_reuses_the_callers_bot_and_returns_its_receipt(
155
- monkeypatch,
156
- ):
157
- monkeypatch.setenv("TELEGRAM_BOT_KEY", "signal-token")
158
- sent = Mock(spec=Message, message_id=42)
159
- client = Mock(
160
- spec=Bot,
161
- token="agent-token",
162
- send_message=AsyncMock(return_value=sent),
163
- initialize=AsyncMock(),
164
- shutdown=AsyncMock(),
165
- )
166
- buttons = InlineKeyboardMarkup(
167
- [[InlineKeyboardButton("Approve", callback_data="approve:42")]]
168
- )
169
- with patch("pybinbot.shared.telegram_delivery.Bot") as constructor:
170
- delivery = TelegramDelivery(bot=client, chat_id=123)
171
- receipt = await delivery.send_message(
172
- '<b>Proposal</b> <a href="https://example.com">Dashboard</a> ratio <= 1',
173
- reply_markup=buttons,
174
- reply_to_message_id=17,
175
- )
176
- assert delivery.token == "agent-token"
177
- assert receipt is sent
178
- assert receipt.message_id == 42
179
- constructor.assert_not_called()
180
- client.initialize.assert_not_awaited()
181
- client.shutdown.assert_not_awaited()
182
- client.send_message.assert_awaited_once()
183
- kwargs = client.send_message.await_args.kwargs
184
- assert kwargs["chat_id"] == 123
185
- assert kwargs["reply_markup"] is buttons
186
- assert kwargs["reply_to_message_id"] == 17
187
- assert kwargs["text"] == (
188
- '<b>Proposal</b> <a href="https://example.com">Dashboard</a> ratio &lt;= 1'
189
- )
190
- assert kwargs["parse_mode"] == "HTML"
191
- assert kwargs["link_preview_options"].is_disabled is True
192
-
193
-
194
- def test_explicit_agent_token_overrides_the_signal_bot_environment(monkeypatch):
195
- monkeypatch.setenv("TELEGRAM_BOT_KEY", "signal-token")
196
- with patch("pybinbot.shared.telegram_delivery.Bot") as constructor:
197
- delivery = TelegramDelivery(token="agent-token", chat_id=123)
198
- constructor.assert_called_once_with(token="agent-token")
199
- assert delivery.token == "agent-token"
200
-
201
-
202
- @pytest.mark.asyncio
203
- @pytest.mark.parametrize("error", [RetryAfter(60), TimedOut(), BadRequest("rejected")])
204
- async def test_message_delivery_propagates_failures_without_retrying(error):
205
- client = Mock(
206
- spec=Bot, token="agent-token", send_message=AsyncMock(side_effect=error)
207
- )
208
- delivery = TelegramDelivery(bot=client, chat_id=123)
209
- with pytest.raises(type(error)) as caught:
210
- await delivery.send_message("Proposal")
211
- assert caught.value is error
212
- client.send_message.assert_awaited_once()
213
-
214
-
215
- @pytest.mark.asyncio
216
- async def test_rate_limit_retry_stays_within_the_message_delivery_deadline():
217
- client = Mock(
218
- spec=Bot,
219
- token="agent-token",
220
- send_message=AsyncMock(side_effect=RetryAfter(60)),
221
- )
222
- delivery = TelegramDelivery(bot=client, chat_id=123)
223
- with pytest.raises(TimeoutError):
224
- await delivery.send_message(
225
- "Proposal",
226
- expires_at=datetime.now(UTC) + timedelta(milliseconds=20),
227
- retry_on_rate_limit=True,
228
- )
229
- client.send_message.assert_awaited_once()
230
-
231
-
232
- @pytest.mark.asyncio
233
- async def test_delivery_cancellation_reaches_the_callers_task():
234
- client = Mock(
235
- spec=Bot,
236
- token="agent-token",
237
- send_message=AsyncMock(side_effect=asyncio.CancelledError),
238
- )
239
- delivery = TelegramDelivery(bot=client, chat_id=123)
240
- with pytest.raises(asyncio.CancelledError):
241
- await delivery.send("Signal")
242
- client.send_message.assert_awaited_once()
243
-
244
-
245
- @pytest.mark.asyncio
246
- async def test_boolean_delivery_reports_failure_without_logging_credentials(caplog):
247
- caplog.set_level("WARNING")
248
- client = Mock(
249
- spec=Bot,
250
- token="agent-token",
251
- send_message=AsyncMock(
252
- side_effect=BadRequest("https://api.telegram.org/agent-token")
253
- ),
254
- )
255
- delivery = TelegramDelivery(bot=client, chat_id=123)
256
- assert await delivery.send("Signal") is False
257
- assert "BadRequest" in caplog.text
258
- assert "agent-token" not in caplog.text
@@ -1,194 +0,0 @@
1
- from datetime import UTC, datetime
2
- from unittest.mock import Mock
3
- from uuid import uuid4
4
-
5
- import pytest
6
- from pydantic import ValidationError
7
- from requests import Timeout
8
-
9
- from pybinbot import BinbotApi, BotModel, Status
10
- from pybinbot.apis.binbot.exceptions import BinbotErrors
11
- from pybinbot.models.signals import SignalListRecord
12
- from kucoin_universal_sdk.generate.futures.positions.model_get_position_details_resp import (
13
- GetPositionDetailsResp,
14
- )
15
-
16
-
17
- @pytest.fixture
18
- def api(monkeypatch):
19
- monkeypatch.setattr(BinbotApi, "_login_service_account", Mock())
20
- client = BinbotApi(
21
- "https://production.example", "service@example.test", "test-password"
22
- )
23
- monkeypatch.setattr(client, "request", Mock())
24
- return client
25
-
26
-
27
- def test_get_bots_returns_typed_deduplicated_bots_from_every_page(api):
28
- first = BotModel(id=uuid4(), pair="XBTUSDTM", status=Status.active)
29
- second = BotModel(id=uuid4(), pair="ETHUSDTM", status=Status.active)
30
- third = BotModel(id=uuid4(), pair="SOLUSDTM", status=Status.active)
31
- api.request.side_effect = [
32
- {"message": "Bots found", "data": [bot.model_dump(mode="json") for bot in page]}
33
- for page in ([first, second], [second, third], [])
34
- ]
35
- result = api.get_bots(
36
- status=Status.active,
37
- bot_name="terminal",
38
- start_date=100,
39
- end_date=200,
40
- page_size=2,
41
- )
42
- assert result == [first, second, third]
43
- assert [call.kwargs["params"]["offset"] for call in api.request.call_args_list] == [
44
- 0,
45
- 2,
46
- 4,
47
- ]
48
- for call in api.request.call_args_list:
49
- assert call.kwargs["url"] == "https://production.example/bot"
50
- assert call.kwargs["timeout"] == (5, 30)
51
- assert call.kwargs["params"] == {
52
- "include_closed": False,
53
- "status": "active",
54
- "bot_name": "terminal",
55
- "start_date": 100,
56
- "end_date": 200,
57
- "limit": 2,
58
- "offset": call.kwargs["params"]["offset"],
59
- }
60
-
61
-
62
- def test_get_bots_can_include_closed_bots_without_a_status_filter(api):
63
- api.request.return_value = {"message": "Bots found", "data": []}
64
- assert api.get_bots(include_closed=True) == []
65
- assert api.request.call_args.kwargs["params"] == {
66
- "include_closed": True,
67
- "limit": 200,
68
- "offset": 0,
69
- }
70
-
71
-
72
- @pytest.mark.parametrize("size", [0, -1])
73
- def test_get_bots_rejects_invalid_page_sizes_before_requesting(api, size):
74
- with pytest.raises(ValueError, match="page_size"):
75
- api.get_bots(page_size=size)
76
- api.request.assert_not_called()
77
-
78
-
79
- @pytest.mark.parametrize("quantity", [-17, 0, 12])
80
- def test_get_futures_position_returns_typed_signed_or_flat_positions(api, quantity):
81
- api.request.return_value = {
82
- "message": "Position found",
83
- "data": {"symbol": "FOLKSUSDTM", "current_qty": quantity},
84
- }
85
- result = api.get_futures_position("folksusdtm")
86
- assert isinstance(result, GetPositionDetailsResp)
87
- assert result.symbol == "FOLKSUSDTM"
88
- assert result.current_qty == quantity
89
- api.request.assert_called_once_with(
90
- url="https://production.example/order/kucoin/futures/position/FOLKSUSDTM",
91
- timeout=(5, 30),
92
- )
93
-
94
-
95
- def test_get_signals_sends_typed_filters_and_returns_indicator_payloads(api):
96
- since = datetime(2026, 12, 2, 12, tzinfo=UTC)
97
- until = datetime(2026, 12, 2, 13, tzinfo=UTC)
98
- record = {
99
- "id": 42,
100
- "algorithm_name": "skyfall",
101
- "symbol": "FOLKSUSDTM",
102
- "generated_at": since.isoformat(),
103
- "direction": "short",
104
- "indicators": {"derivatives_positioning": {"timestamp": since.timestamp()}},
105
- }
106
- api.request.return_value = {"message": "Signals found", "data": [record]}
107
- result = api.get_signals(
108
- symbol="folksusdtm",
109
- algorithm_name="skyfall",
110
- current_regime="DOWN",
111
- autotrade=False,
112
- since=since,
113
- until=until,
114
- limit=20,
115
- offset=5,
116
- )
117
- assert len(result) == 1
118
- assert isinstance(result[0], SignalListRecord)
119
- assert result[0].indicators == record["indicators"]
120
- assert result[0].generated_at == since
121
- api.request.assert_called_once_with(
122
- url="https://production.example/signals",
123
- timeout=(5, 30),
124
- params={
125
- "symbol": "FOLKSUSDTM",
126
- "algorithm_name": "skyfall",
127
- "current_regime": "DOWN",
128
- "autotrade": False,
129
- "since": since.isoformat(),
130
- "until": until.isoformat(),
131
- "limit": 20,
132
- "offset": 5,
133
- "include_payload": True,
134
- },
135
- )
136
-
137
-
138
- def test_get_signals_accepts_summary_records_without_optional_payloads(api):
139
- api.request.return_value = {
140
- "message": "Signals found",
141
- "data": [
142
- {
143
- "id": 1,
144
- "algorithm_name": "skyfall",
145
- "symbol": "XBTUSDTM",
146
- "generated_at": "2026-12-02T12:00:00Z",
147
- "direction": "short",
148
- }
149
- ],
150
- }
151
- result = api.get_signals(include_payload=False)
152
- assert result[0].indicators is None
153
- assert api.request.call_args.kwargs["params"] == {
154
- "limit": 100,
155
- "offset": 0,
156
- "include_payload": False,
157
- }
158
-
159
-
160
- @pytest.mark.parametrize("kwargs", [{"limit": 0}, {"limit": 1001}, {"offset": -1}])
161
- def test_get_signals_enforces_the_api_pagination_bounds(api, kwargs):
162
- with pytest.raises(ValueError, match="Signals require"):
163
- api.get_signals(**kwargs)
164
- api.request.assert_not_called()
165
-
166
-
167
- @pytest.mark.parametrize(
168
- "method,args",
169
- [("get_bots", ()), ("get_signals", ()), ("get_futures_position", ("XBTUSDTM",))],
170
- )
171
- def test_typed_reads_reject_error_responses_instead_of_returning_empty_data(
172
- api, method, args
173
- ):
174
- api.request.return_value = {"message": "Read rejected", "error": 1}
175
- with pytest.raises(BinbotErrors):
176
- getattr(api, method)(*args)
177
- api.request.assert_called_once()
178
-
179
-
180
- @pytest.mark.parametrize(
181
- "method,args",
182
- [("get_bots", ()), ("get_signals", ()), ("get_futures_position", ("XBTUSDTM",))],
183
- )
184
- def test_typed_read_timeouts_propagate_without_retries(api, method, args):
185
- api.request.side_effect = Timeout("Unavailable")
186
- with pytest.raises(Timeout):
187
- getattr(api, method)(*args)
188
- api.request.assert_called_once()
189
-
190
-
191
- def test_invalid_signal_rows_cannot_be_returned_as_typed_signals(api):
192
- api.request.return_value = {"message": "Signals found", "data": [{"id": 1}]}
193
- with pytest.raises(ValidationError):
194
- api.get_signals()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes