pybinbot 2.1.14__tar.gz → 2.1.17__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.
- {pybinbot-2.1.14/pybinbot.egg-info → pybinbot-2.1.17}/PKG-INFO +14 -1
- {pybinbot-2.1.14 → pybinbot-2.1.17}/README.md +13 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/__init__.py +3 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/binbot/base.py +34 -0
- pybinbot-2.1.17/pybinbot/models/futures_market.py +21 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/telegram_delivery.py +76 -48
- {pybinbot-2.1.14 → pybinbot-2.1.17/pybinbot.egg-info}/PKG-INFO +14 -1
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot.egg-info/SOURCES.txt +2 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pyproject.toml +1 -1
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_binbot_api.py +40 -0
- pybinbot-2.1.17/tests/test_futures_market_api.py +61 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_telegram_delivery.py +111 -2
- {pybinbot-2.1.14 → pybinbot-2.1.17}/LICENSE +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/MANIFEST.in +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/binance/base.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/binance/exceptions.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/binbot/exceptions.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/coingecko.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/kucoin/base.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/kucoin/exceptions.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/kucoin/futures.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/kucoin/market.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/kucoin/orders.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/apis/kucoin/rest.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/__init__.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/autotrade_settings.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/bot.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/bot_base.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/cvd.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/deal.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/derivatives.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/fastest_movers.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/grid_ladder.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/order.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/routes.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/signals.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/models/symbol.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/py.typed +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/__init__.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/beta.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/breadth.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/cache.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/candles.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/enums.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/handlers.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/heikin_ashi.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/indicators.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/logging_config.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/maths.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/price_crossings.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/timestamps.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/types.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/shared/utils.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/strategy/beta.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/strategy/breadth.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/strategy/price_crossings.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/strategy/swing_protection.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/streaming/binance/async_socket_client.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/streaming/binance/socket_client.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/streaming/binance/socket_manager.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot.egg-info/dependency_links.txt +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot.egg-info/requires.txt +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/pybinbot.egg-info/top_level.txt +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/setup.cfg +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_beta.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_bot_futures_leverage.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_breadth.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_candles.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_closed_bot_status.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_coingecko.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_conditional_entry.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_conditional_futures_orders.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_cvd_api.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_deal_model.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_derivatives_api.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_fastest_movers.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_futures_place_order.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_grid_ladder.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_handlers.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_heikin_ashi.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_indicators.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_kucoin_api.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_logging_config.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_matching_engine.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_maths.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_price_crossings.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_swing_protection.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_symbol_model.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_timestamps.py +0 -0
- {pybinbot-2.1.14 → pybinbot-2.1.17}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pybinbot
|
|
3
|
-
Version: 2.1.
|
|
3
|
+
Version: 2.1.17
|
|
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,6 +106,19 @@ 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
|
+
|
|
109
122
|
|
|
110
123
|
## Publishing
|
|
111
124
|
|
|
@@ -77,6 +77,19 @@ 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
|
+
|
|
80
93
|
|
|
81
94
|
## Publishing
|
|
82
95
|
|
|
@@ -121,6 +121,7 @@ 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.futures_market import FuturesMarketSnapshot, MarketObservation
|
|
124
125
|
from pybinbot.models.fastest_movers import (
|
|
125
126
|
FastestMoverEntry,
|
|
126
127
|
FastestMoversResponse,
|
|
@@ -224,6 +225,8 @@ __all__ = [
|
|
|
224
225
|
"CvdPoint",
|
|
225
226
|
"CvdAggregateResponse",
|
|
226
227
|
"CvdSymbolResponse",
|
|
228
|
+
"FuturesMarketSnapshot",
|
|
229
|
+
"MarketObservation",
|
|
227
230
|
"AutotradeSettings",
|
|
228
231
|
"AutotradeSettingsResponse",
|
|
229
232
|
"AutotradeSettingsSchema",
|
|
@@ -30,6 +30,7 @@ from datetime import datetime, timezone
|
|
|
30
30
|
from dateutil.parser import parse
|
|
31
31
|
from pybinbot.models.cvd import CvdAggregateResponse, CvdSymbolResponse
|
|
32
32
|
from pybinbot.models.fastest_movers import FastestMoversResponse, FastestMoversSnapshot
|
|
33
|
+
from pybinbot.models.futures_market import FuturesMarketSnapshot
|
|
33
34
|
|
|
34
35
|
logger = logging.getLogger(__name__)
|
|
35
36
|
|
|
@@ -78,6 +79,7 @@ class BinbotApi:
|
|
|
78
79
|
self.bb_timeseries_url = f"{bb_base_url}/charts/timeseries"
|
|
79
80
|
self.bb_market_breadth_url = f"{bb_base_url}/charts/market-breadth"
|
|
80
81
|
self.bb_cvd_symbol_url = f"{bb_base_url}/charts/cvd-symbol"
|
|
82
|
+
self.bb_futures_market_url = f"{bb_base_url}/charts/futures-market"
|
|
81
83
|
self.bb_cvd_aggregate_url = f"{bb_base_url}/charts/cvd-aggregate"
|
|
82
84
|
self.bb_gainers_losers_series_url = (
|
|
83
85
|
f"{bb_base_url}/charts/gainers-losers-series"
|
|
@@ -284,6 +286,24 @@ class BinbotApi:
|
|
|
284
286
|
response = self.request(url=f"{self.bb_bot_url}/symbol/{symbol}")
|
|
285
287
|
return self._bot_model(response["data"])
|
|
286
288
|
|
|
289
|
+
def get_bot(self, bot_id: str) -> BotModel:
|
|
290
|
+
response = self.request(url=f"{self.bb_bot_url}/{bot_id}")
|
|
291
|
+
return BotModel.model_validate(response["data"])
|
|
292
|
+
|
|
293
|
+
def get_futures_market(self, symbol: str) -> FuturesMarketSnapshot:
|
|
294
|
+
"""Read live contract, book, trades and candles for one futures symbol.
|
|
295
|
+
|
|
296
|
+
The endpoint returns a bare snapshot, not a StandardResponse envelope.
|
|
297
|
+
Each source carries its own fetch time or error. Assembling every
|
|
298
|
+
source can take tens of seconds, hence the longer read timeout.
|
|
299
|
+
"""
|
|
300
|
+
response = self.request(
|
|
301
|
+
url=self.bb_futures_market_url,
|
|
302
|
+
params={"symbol": symbol.upper()},
|
|
303
|
+
timeout=(5, 90),
|
|
304
|
+
)
|
|
305
|
+
return FuturesMarketSnapshot.model_validate(response)
|
|
306
|
+
|
|
287
307
|
async def get_market_breadth(self, size: int = 400) -> MarketBreadthSeries | None:
|
|
288
308
|
"""
|
|
289
309
|
Get market breadth data
|
|
@@ -546,6 +566,20 @@ class BinbotApi:
|
|
|
546
566
|
response = self.request(url=self.bb_bot_url, method="POST", json=data)
|
|
547
567
|
return BotResponse.model_validate(response)
|
|
548
568
|
|
|
569
|
+
def edit_bot(self, bot_id: str, data: dict) -> BotResponse:
|
|
570
|
+
"""Save bot fields with PUT /bot/{id}.
|
|
571
|
+
|
|
572
|
+
This only stores the bot. For an active bot, the new parameters reach
|
|
573
|
+
the exchange after activate_bot recalculates its protection, which is
|
|
574
|
+
the terminal's "Update deal" flow. Binbot rejects invalid edits with
|
|
575
|
+
HTTP 422, raised here as BinbotErrors. activate_bot can instead fail
|
|
576
|
+
with HTTP 200 and error=1, so callers must check BotResponse.error.
|
|
577
|
+
"""
|
|
578
|
+
response = self.request(
|
|
579
|
+
url=f"{self.bb_bot_url}/{bot_id}", method="PUT", json=data
|
|
580
|
+
)
|
|
581
|
+
return BotResponse.model_validate(response)
|
|
582
|
+
|
|
549
583
|
def activate_bot(self, bot_id: str) -> BotResponse:
|
|
550
584
|
response = self.request(
|
|
551
585
|
url=f"{self.bb_activate_bot_url}/{bot_id}", method="POST"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Live KuCoin futures market snapshot returned by binbot's charts endpoint."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MarketObservation(BaseModel):
|
|
9
|
+
"""One market source, with either its data or the reason it is missing."""
|
|
10
|
+
|
|
11
|
+
observed_at: float
|
|
12
|
+
data: Any = None
|
|
13
|
+
error: str | None = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FuturesMarketSnapshot(BaseModel):
|
|
17
|
+
"""Contract, book, trades and candles for one symbol, keyed by source name."""
|
|
18
|
+
|
|
19
|
+
symbol: str
|
|
20
|
+
captured_at: float
|
|
21
|
+
sources: dict[str, MarketObservation]
|
|
@@ -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, LinkPreviewOptions
|
|
12
|
+
from telegram import Bot, InlineKeyboardMarkup, LinkPreviewOptions, Message
|
|
13
13
|
from telegram.constants import ParseMode
|
|
14
14
|
from telegram.error import RetryAfter, TimedOut
|
|
15
15
|
from telegram.helpers import escape
|
|
@@ -21,15 +21,21 @@ class TelegramDelivery:
|
|
|
21
21
|
def __init__(
|
|
22
22
|
self,
|
|
23
23
|
token: str | None = None,
|
|
24
|
-
chat_id: str | None = None,
|
|
24
|
+
chat_id: str | int | None = None,
|
|
25
25
|
*,
|
|
26
|
+
bot: Bot | None = None,
|
|
26
27
|
min_send_interval_seconds: float = 0,
|
|
27
28
|
retry_after_pad_seconds: float = 2,
|
|
28
29
|
) -> None:
|
|
29
|
-
|
|
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))
|
|
30
34
|
self.token = os.getenv("TELEGRAM_BOT_KEY", "") if token is None else token
|
|
31
35
|
self.chat_id = os.getenv("TELEGRAM_USER_ID", "") if chat_id is None else chat_id
|
|
32
|
-
self.bot =
|
|
36
|
+
self.bot = bot
|
|
37
|
+
if self.bot is None and self.token:
|
|
38
|
+
self.bot = Bot(token=self.token)
|
|
33
39
|
self._send_lock = asyncio.Lock()
|
|
34
40
|
self._min_send_interval_seconds = min_send_interval_seconds
|
|
35
41
|
self._retry_after_pad_seconds = retry_after_pad_seconds
|
|
@@ -93,54 +99,76 @@ class TelegramDelivery:
|
|
|
93
99
|
"""Deliver within an optional deadline, including time spent waiting to send."""
|
|
94
100
|
if not self.token or not self.chat_id or self.bot is None:
|
|
95
101
|
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
102
|
try:
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
|
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")
|
|
114
|
+
return False
|
|
141
115
|
except TimeoutError:
|
|
142
116
|
logging.info("Telegram alert expired before delivery completed; skipping")
|
|
143
117
|
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
|
|
144
172
|
|
|
145
173
|
def send_once(self, message: str) -> bool:
|
|
146
174
|
"""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.
|
|
3
|
+
Version: 2.1.17
|
|
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,6 +106,19 @@ 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
|
+
|
|
109
122
|
|
|
110
123
|
## Publishing
|
|
111
124
|
|
|
@@ -28,6 +28,7 @@ pybinbot/models/cvd.py
|
|
|
28
28
|
pybinbot/models/deal.py
|
|
29
29
|
pybinbot/models/derivatives.py
|
|
30
30
|
pybinbot/models/fastest_movers.py
|
|
31
|
+
pybinbot/models/futures_market.py
|
|
31
32
|
pybinbot/models/grid_ladder.py
|
|
32
33
|
pybinbot/models/order.py
|
|
33
34
|
pybinbot/models/routes.py
|
|
@@ -70,6 +71,7 @@ tests/test_cvd_api.py
|
|
|
70
71
|
tests/test_deal_model.py
|
|
71
72
|
tests/test_derivatives_api.py
|
|
72
73
|
tests/test_fastest_movers.py
|
|
74
|
+
tests/test_futures_market_api.py
|
|
73
75
|
tests/test_futures_place_order.py
|
|
74
76
|
tests/test_grid_ladder.py
|
|
75
77
|
tests/test_handlers.py
|
|
@@ -528,6 +528,46 @@ class TestBotRouteResponses:
|
|
|
528
528
|
assert captured["method"] == "DELETE"
|
|
529
529
|
assert captured["json"] == {"ids": ["bot-1", "bot-2"]}
|
|
530
530
|
|
|
531
|
+
def test_get_bot_reads_one_bot_by_id(self) -> None:
|
|
532
|
+
api_class = load_binbot_api_class()
|
|
533
|
+
api = object.__new__(api_class)
|
|
534
|
+
api.bb_bot_url = "https://example.com/bot"
|
|
535
|
+
captured: dict = {}
|
|
536
|
+
|
|
537
|
+
def fake_request(**kwargs):
|
|
538
|
+
captured.update(kwargs)
|
|
539
|
+
return {"message": "Successfully found one bot.", "data": {"pair": "X"}}
|
|
540
|
+
|
|
541
|
+
api.request = fake_request
|
|
542
|
+
|
|
543
|
+
result = api.get_bot("bot-1")
|
|
544
|
+
|
|
545
|
+
assert isinstance(result, _BotModel)
|
|
546
|
+
assert result.pair == "X"
|
|
547
|
+
assert captured == {"url": "https://example.com/bot/bot-1"}
|
|
548
|
+
|
|
549
|
+
def test_edit_bot_puts_the_full_payload_to_the_bot_url(self) -> None:
|
|
550
|
+
api_class = load_binbot_api_class()
|
|
551
|
+
api = object.__new__(api_class)
|
|
552
|
+
api.bb_bot_url = "https://example.com/bot"
|
|
553
|
+
captured: dict = {}
|
|
554
|
+
|
|
555
|
+
def fake_request(**kwargs):
|
|
556
|
+
captured.update(kwargs)
|
|
557
|
+
return {"message": "Successfully edited bot.", "data": {"pair": "X"}}
|
|
558
|
+
|
|
559
|
+
api.request = fake_request
|
|
560
|
+
payload = {"pair": "X", "stop_loss": 2.5, "trailing_deviation": 1.5}
|
|
561
|
+
|
|
562
|
+
result = api.edit_bot("bot-1", payload)
|
|
563
|
+
|
|
564
|
+
assert isinstance(result, _BotResponse)
|
|
565
|
+
assert result.message == "Successfully edited bot."
|
|
566
|
+
assert result.error == 0
|
|
567
|
+
assert captured["url"] == "https://example.com/bot/bot-1"
|
|
568
|
+
assert captured["method"] == "PUT"
|
|
569
|
+
assert captured["json"] == payload
|
|
570
|
+
|
|
531
571
|
|
|
532
572
|
class TestCalculateGridLevels:
|
|
533
573
|
def test_posts_payload_to_grid_calculate_endpoint(self) -> None:
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from unittest.mock import Mock, patch
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from pydantic import ValidationError
|
|
5
|
+
|
|
6
|
+
from pybinbot import BinbotApi, FuturesMarketSnapshot, MarketObservation
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def snapshot_payload() -> dict:
|
|
10
|
+
return {
|
|
11
|
+
"symbol": "XBTUSDTM",
|
|
12
|
+
"captured_at": 1_796_000_000.5,
|
|
13
|
+
"sources": {
|
|
14
|
+
"contract": {
|
|
15
|
+
"observed_at": 1_796_000_000.1,
|
|
16
|
+
"data": {"symbol": "XBTUSDTM", "multiplier": 0.001},
|
|
17
|
+
},
|
|
18
|
+
"trades": {"observed_at": 1_796_000_000.2, "error": "Timeout"},
|
|
19
|
+
},
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.fixture
|
|
24
|
+
def api() -> BinbotApi:
|
|
25
|
+
with patch.object(BinbotApi, "_login_service_account"):
|
|
26
|
+
return BinbotApi("https://example.com", "service@example.com", "password")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_futures_market_reads_bare_snapshot_with_a_long_timeout(api, monkeypatch):
|
|
30
|
+
request = Mock(return_value=snapshot_payload())
|
|
31
|
+
monkeypatch.setattr(api, "request", request)
|
|
32
|
+
|
|
33
|
+
result = api.get_futures_market("xbtusdtm")
|
|
34
|
+
|
|
35
|
+
request.assert_called_once_with(
|
|
36
|
+
url="https://example.com/charts/futures-market",
|
|
37
|
+
params={"symbol": "XBTUSDTM"},
|
|
38
|
+
timeout=(5, 90),
|
|
39
|
+
)
|
|
40
|
+
assert isinstance(result, FuturesMarketSnapshot)
|
|
41
|
+
assert result.symbol == "XBTUSDTM"
|
|
42
|
+
assert isinstance(result.sources["contract"], MarketObservation)
|
|
43
|
+
assert result.sources["contract"].data["multiplier"] == 0.001
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_futures_market_keeps_a_failed_source_as_an_explicit_error(api, monkeypatch):
|
|
47
|
+
monkeypatch.setattr(api, "request", Mock(return_value=snapshot_payload()))
|
|
48
|
+
|
|
49
|
+
trades = api.get_futures_market("XBTUSDTM").sources["trades"]
|
|
50
|
+
|
|
51
|
+
assert trades.data is None
|
|
52
|
+
assert trades.error == "Timeout"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_futures_market_rejects_a_snapshot_without_sources(api, monkeypatch):
|
|
56
|
+
payload = snapshot_payload()
|
|
57
|
+
del payload["sources"]
|
|
58
|
+
monkeypatch.setattr(api, "request", Mock(return_value=payload))
|
|
59
|
+
|
|
60
|
+
with pytest.raises(ValidationError):
|
|
61
|
+
api.get_futures_market("XBTUSDTM")
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
from datetime import UTC, datetime, timedelta
|
|
3
|
-
from unittest.mock import AsyncMock, patch
|
|
3
|
+
from unittest.mock import AsyncMock, Mock, patch
|
|
4
4
|
|
|
5
5
|
import pytest
|
|
6
|
-
from telegram
|
|
6
|
+
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Message
|
|
7
|
+
from telegram.error import BadRequest, RetryAfter, TimedOut
|
|
7
8
|
|
|
8
9
|
from pybinbot.shared.telegram_delivery import TelegramDelivery
|
|
9
10
|
|
|
@@ -147,3 +148,111 @@ async def test_delivery_deadline_cancels_a_stalled_request():
|
|
|
147
148
|
is False
|
|
148
149
|
)
|
|
149
150
|
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 <= 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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|