pybinbot 2.1.7__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.7/pybinbot.egg-info → pybinbot-2.1.9}/PKG-INFO +37 -1
  2. {pybinbot-2.1.7 → pybinbot-2.1.9}/README.md +36 -0
  3. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/__init__.py +2 -2
  4. pybinbot-2.1.9/pybinbot/shared/beta.py +13 -0
  5. pybinbot-2.1.9/pybinbot/shared/breadth.py +21 -0
  6. pybinbot-2.1.9/pybinbot/shared/price_crossings.py +15 -0
  7. pybinbot-2.1.9/pybinbot/strategy/swing_protection.py +167 -0
  8. {pybinbot-2.1.7 → pybinbot-2.1.9/pybinbot.egg-info}/PKG-INFO +37 -1
  9. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot.egg-info/SOURCES.txt +5 -0
  10. {pybinbot-2.1.7 → pybinbot-2.1.9}/pyproject.toml +2 -1
  11. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_beta.py +1 -1
  12. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_price_crossings.py +1 -1
  13. pybinbot-2.1.9/tests/test_swing_protection.py +153 -0
  14. {pybinbot-2.1.7 → pybinbot-2.1.9}/LICENSE +0 -0
  15. {pybinbot-2.1.7 → pybinbot-2.1.9}/MANIFEST.in +0 -0
  16. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/binance/base.py +0 -0
  17. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/binance/exceptions.py +0 -0
  18. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/binbot/base.py +0 -0
  19. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/binbot/exceptions.py +0 -0
  20. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/coingecko.py +0 -0
  21. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/kucoin/base.py +0 -0
  22. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/kucoin/exceptions.py +0 -0
  23. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/kucoin/futures.py +0 -0
  24. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/kucoin/market.py +0 -0
  25. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/kucoin/orders.py +0 -0
  26. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/apis/kucoin/rest.py +0 -0
  27. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/__init__.py +0 -0
  28. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/autotrade_settings.py +0 -0
  29. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/bot.py +0 -0
  30. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/bot_base.py +0 -0
  31. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/cvd.py +0 -0
  32. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/deal.py +0 -0
  33. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/derivatives.py +0 -0
  34. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/fastest_movers.py +0 -0
  35. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/grid_ladder.py +0 -0
  36. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/order.py +0 -0
  37. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/routes.py +0 -0
  38. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/signals.py +0 -0
  39. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/models/symbol.py +0 -0
  40. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/py.typed +0 -0
  41. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/__init__.py +0 -0
  42. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/cache.py +0 -0
  43. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/candles.py +0 -0
  44. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/enums.py +0 -0
  45. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/handlers.py +0 -0
  46. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/heikin_ashi.py +0 -0
  47. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/indicators.py +0 -0
  48. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/logging_config.py +0 -0
  49. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/maths.py +0 -0
  50. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/telegram_delivery.py +0 -0
  51. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/timestamps.py +0 -0
  52. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/types.py +0 -0
  53. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/shared/utils.py +0 -0
  54. {pybinbot-2.1.7/pybinbot/shared → pybinbot-2.1.9/pybinbot/strategy}/beta.py +0 -0
  55. {pybinbot-2.1.7/pybinbot/shared → pybinbot-2.1.9/pybinbot/strategy}/breadth.py +0 -0
  56. {pybinbot-2.1.7/pybinbot/shared → pybinbot-2.1.9/pybinbot/strategy}/price_crossings.py +0 -0
  57. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/streaming/binance/async_socket_client.py +0 -0
  58. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/streaming/binance/socket_client.py +0 -0
  59. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/streaming/binance/socket_manager.py +0 -0
  60. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
  61. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot.egg-info/dependency_links.txt +0 -0
  62. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot.egg-info/requires.txt +0 -0
  63. {pybinbot-2.1.7 → pybinbot-2.1.9}/pybinbot.egg-info/top_level.txt +0 -0
  64. {pybinbot-2.1.7 → pybinbot-2.1.9}/setup.cfg +0 -0
  65. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_binbot_api.py +0 -0
  66. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_bot_futures_leverage.py +0 -0
  67. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_breadth.py +0 -0
  68. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_candles.py +0 -0
  69. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_closed_bot_status.py +0 -0
  70. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_coingecko.py +0 -0
  71. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_conditional_entry.py +0 -0
  72. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_conditional_futures_orders.py +0 -0
  73. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_cvd_api.py +0 -0
  74. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_deal_model.py +0 -0
  75. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_derivatives_api.py +0 -0
  76. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_fastest_movers.py +0 -0
  77. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_futures_place_order.py +0 -0
  78. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_grid_ladder.py +0 -0
  79. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_handlers.py +0 -0
  80. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_heikin_ashi.py +0 -0
  81. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_indicators.py +0 -0
  82. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_kucoin_api.py +0 -0
  83. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_logging_config.py +0 -0
  84. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_matching_engine.py +0 -0
  85. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_maths.py +0 -0
  86. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_symbol_model.py +0 -0
  87. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_telegram_delivery.py +0 -0
  88. {pybinbot-2.1.7 → pybinbot-2.1.9}/tests/test_timestamps.py +0 -0
  89. {pybinbot-2.1.7 → 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.7
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
@@ -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
+ ]
@@ -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.7
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.
@@ -49,6 +49,10 @@ pybinbot/shared/telegram_delivery.py
49
49
  pybinbot/shared/timestamps.py
50
50
  pybinbot/shared/types.py
51
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
52
56
  pybinbot/streaming/binance/async_socket_client.py
53
57
  pybinbot/streaming/binance/socket_client.py
54
58
  pybinbot/streaming/binance/socket_manager.py
@@ -76,6 +80,7 @@ tests/test_logging_config.py
76
80
  tests/test_matching_engine.py
77
81
  tests/test_maths.py
78
82
  tests/test_price_crossings.py
83
+ tests/test_swing_protection.py
79
84
  tests/test_symbol_model.py
80
85
  tests/test_telegram_delivery.py
81
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.7"
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]
@@ -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
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