pybinbot 2.1.7__tar.gz → 2.1.12__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.12}/PKG-INFO +52 -1
  2. {pybinbot-2.1.7 → pybinbot-2.1.12}/README.md +51 -0
  3. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/__init__.py +2 -2
  4. pybinbot-2.1.12/pybinbot/shared/beta.py +13 -0
  5. pybinbot-2.1.12/pybinbot/shared/breadth.py +21 -0
  6. pybinbot-2.1.12/pybinbot/shared/price_crossings.py +15 -0
  7. pybinbot-2.1.12/pybinbot/strategy/swing_protection.py +293 -0
  8. {pybinbot-2.1.7 → pybinbot-2.1.12/pybinbot.egg-info}/PKG-INFO +52 -1
  9. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot.egg-info/SOURCES.txt +5 -0
  10. {pybinbot-2.1.7 → pybinbot-2.1.12}/pyproject.toml +2 -1
  11. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_beta.py +1 -1
  12. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_price_crossings.py +1 -1
  13. pybinbot-2.1.12/tests/test_swing_protection.py +271 -0
  14. {pybinbot-2.1.7 → pybinbot-2.1.12}/LICENSE +0 -0
  15. {pybinbot-2.1.7 → pybinbot-2.1.12}/MANIFEST.in +0 -0
  16. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/binance/base.py +0 -0
  17. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/binance/exceptions.py +0 -0
  18. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/binbot/base.py +0 -0
  19. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/binbot/exceptions.py +0 -0
  20. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/coingecko.py +0 -0
  21. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/kucoin/base.py +0 -0
  22. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/kucoin/exceptions.py +0 -0
  23. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/kucoin/futures.py +0 -0
  24. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/kucoin/market.py +0 -0
  25. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/kucoin/orders.py +0 -0
  26. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/apis/kucoin/rest.py +0 -0
  27. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/__init__.py +0 -0
  28. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/autotrade_settings.py +0 -0
  29. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/bot.py +0 -0
  30. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/bot_base.py +0 -0
  31. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/cvd.py +0 -0
  32. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/deal.py +0 -0
  33. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/derivatives.py +0 -0
  34. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/fastest_movers.py +0 -0
  35. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/grid_ladder.py +0 -0
  36. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/order.py +0 -0
  37. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/routes.py +0 -0
  38. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/signals.py +0 -0
  39. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/models/symbol.py +0 -0
  40. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/py.typed +0 -0
  41. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/__init__.py +0 -0
  42. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/cache.py +0 -0
  43. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/candles.py +0 -0
  44. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/enums.py +0 -0
  45. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/handlers.py +0 -0
  46. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/heikin_ashi.py +0 -0
  47. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/indicators.py +0 -0
  48. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/logging_config.py +0 -0
  49. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/maths.py +0 -0
  50. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/telegram_delivery.py +0 -0
  51. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/timestamps.py +0 -0
  52. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/types.py +0 -0
  53. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/shared/utils.py +0 -0
  54. {pybinbot-2.1.7/pybinbot/shared → pybinbot-2.1.12/pybinbot/strategy}/beta.py +0 -0
  55. {pybinbot-2.1.7/pybinbot/shared → pybinbot-2.1.12/pybinbot/strategy}/breadth.py +0 -0
  56. {pybinbot-2.1.7/pybinbot/shared → pybinbot-2.1.12/pybinbot/strategy}/price_crossings.py +0 -0
  57. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/streaming/binance/async_socket_client.py +0 -0
  58. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/streaming/binance/socket_client.py +0 -0
  59. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/streaming/binance/socket_manager.py +0 -0
  60. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
  61. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot.egg-info/dependency_links.txt +0 -0
  62. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot.egg-info/requires.txt +0 -0
  63. {pybinbot-2.1.7 → pybinbot-2.1.12}/pybinbot.egg-info/top_level.txt +0 -0
  64. {pybinbot-2.1.7 → pybinbot-2.1.12}/setup.cfg +0 -0
  65. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_binbot_api.py +0 -0
  66. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_bot_futures_leverage.py +0 -0
  67. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_breadth.py +0 -0
  68. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_candles.py +0 -0
  69. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_closed_bot_status.py +0 -0
  70. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_coingecko.py +0 -0
  71. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_conditional_entry.py +0 -0
  72. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_conditional_futures_orders.py +0 -0
  73. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_cvd_api.py +0 -0
  74. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_deal_model.py +0 -0
  75. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_derivatives_api.py +0 -0
  76. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_fastest_movers.py +0 -0
  77. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_futures_place_order.py +0 -0
  78. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_grid_ladder.py +0 -0
  79. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_handlers.py +0 -0
  80. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_heikin_ashi.py +0 -0
  81. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_indicators.py +0 -0
  82. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_kucoin_api.py +0 -0
  83. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_logging_config.py +0 -0
  84. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_matching_engine.py +0 -0
  85. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_maths.py +0 -0
  86. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_symbol_model.py +0 -0
  87. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_telegram_delivery.py +0 -0
  88. {pybinbot-2.1.7 → pybinbot-2.1.12}/tests/test_timestamps.py +0 -0
  89. {pybinbot-2.1.7 → pybinbot-2.1.12}/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.12
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,54 @@ 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.
175
+
176
+ `refine_swing_protection` manages the whole timeframe decision. If 1m history
177
+ is gapped or unreliable, it returns the nearest trustworthy coarser swing.
178
+ Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
179
+ gaps make a source unreliable. Price gaps are non-overlapping candle ranges
180
+ separated by more than 0.1% and two price-precision ticks; more than 20% of
181
+ transitions, with at least two gaps, rejects the timeframe.
182
+
183
+ The 3% candle-width threshold prompts refinement. It can be relaxed for a
184
+ coarser fallback after finer data fails, while the buffered stop-distance cap,
185
+ three-hour swing age, confirmation and unbroken-swing requirements still apply.
186
+ If no coarser swing fits, the result has no placement. A missing timeframe in
187
+ the input mapping requests that interval; an empty list means the read finished
188
+ without usable data. Live callers can therefore keep exchange reads off the
189
+ protective exit path while this decision remains shared with entry strategies.
@@ -107,3 +107,54 @@ 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.
146
+
147
+ `refine_swing_protection` manages the whole timeframe decision. If 1m history
148
+ is gapped or unreliable, it returns the nearest trustworthy coarser swing.
149
+ Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
150
+ gaps make a source unreliable. Price gaps are non-overlapping candle ranges
151
+ separated by more than 0.1% and two price-precision ticks; more than 20% of
152
+ transitions, with at least two gaps, rejects the timeframe.
153
+
154
+ The 3% candle-width threshold prompts refinement. It can be relaxed for a
155
+ coarser fallback after finer data fails, while the buffered stop-distance cap,
156
+ three-hour swing age, confirmation and unbroken-swing requirements still apply.
157
+ If no coarser swing fits, the result has no placement. A missing timeframe in
158
+ the input mapping requests that interval; an empty list means the read finished
159
+ without usable data. Live callers can therefore keep exchange reads off the
160
+ protective exit path while this decision remains shared with entry strategies.
@@ -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,293 @@
1
+ """Choose recent structural protection without clipping a distant swing."""
2
+
3
+ from collections.abc import Mapping, 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
+ MAX_PROTECTION_PRICE_GAP_RATIO = 0.2
16
+ MIN_PROTECTION_PRICE_GAP_PCT = 0.1
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class SwingProtection:
21
+ interval_minutes: int
22
+ swing_open_time_ms: int
23
+ confirmation_time_ms: int
24
+ stop_price: float
25
+ distance_pct: float
26
+ candle_range_pct: float
27
+
28
+
29
+ def _completed_protection_window(
30
+ candles: Sequence[Sequence[float]],
31
+ *,
32
+ now_ms: int,
33
+ interval_minutes: int,
34
+ lookback_ms: int,
35
+ fractal_wing: int,
36
+ price_precision: int,
37
+ ) -> list[tuple[int, float, float, float, float]] | None:
38
+ interval_ms = interval_minutes * 60 * 1000
39
+ window_end = now_ms // interval_ms * interval_ms
40
+ window_start = now_ms - lookback_ms
41
+ rows: list[tuple[int, float, float, float, float]] = []
42
+ try:
43
+ for candle in candles:
44
+ timestamp = float(candle[0])
45
+ if not isfinite(timestamp):
46
+ return None
47
+ if timestamp < window_start or timestamp >= window_end:
48
+ continue
49
+ if timestamp != int(timestamp) or int(timestamp) % interval_ms:
50
+ return None
51
+ opening, high, low, close = map(float, candle[1:5])
52
+ volume = float(candle[5])
53
+ if (
54
+ not all(
55
+ isfinite(value) and value > 0
56
+ for value in (opening, high, low, close)
57
+ )
58
+ or not low <= min(opening, close) <= max(opening, close) <= high
59
+ or len(candle) < 7
60
+ or not isfinite(volume)
61
+ or volume <= 0
62
+ or not timestamp <= float(candle[6]) < timestamp + interval_ms
63
+ ):
64
+ return None
65
+ rows.append((int(timestamp), opening, high, low, close))
66
+ except IndexError, TypeError, ValueError, OverflowError:
67
+ return None
68
+ rows.sort()
69
+ if (
70
+ len(rows) < 2 * fractal_wing + 1
71
+ or rows[-1][0] != window_end - interval_ms
72
+ or any(
73
+ later[0] - earlier[0] != interval_ms
74
+ for earlier, later in zip(rows, rows[1:])
75
+ )
76
+ ):
77
+ return None
78
+ tick = 10.0**-price_precision
79
+ price_gaps = sum(
80
+ max(later[3] - earlier[2], earlier[3] - later[2], 0)
81
+ > max(2 * tick, earlier[4] * MIN_PROTECTION_PRICE_GAP_PCT / 100)
82
+ for earlier, later in zip(rows, rows[1:])
83
+ )
84
+ if price_gaps > max(1, MAX_PROTECTION_PRICE_GAP_RATIO * (len(rows) - 1)):
85
+ return None
86
+ return rows
87
+
88
+
89
+ def recent_swing_protection(
90
+ candles: Sequence[Sequence[float]],
91
+ *,
92
+ position: Position,
93
+ reference_price: float,
94
+ now_ms: int,
95
+ interval_minutes: int,
96
+ price_precision: int,
97
+ buffer_pct: float = 0.1,
98
+ max_distance_pct: float = MAX_PROTECTION_DISTANCE_PCT,
99
+ min_distance_pct: float = 0.0,
100
+ max_candle_range_pct: float | None = MAX_PROTECTION_CANDLE_RANGE_PCT,
101
+ lookback_ms: int = PROTECTION_LOOKBACK_MS,
102
+ not_before_ms: int = 0,
103
+ fractal_wing: int = 2,
104
+ ) -> SwingProtection | None:
105
+ """Evaluate only the latest confirmed swing in a bounded completed window.
106
+
107
+ Input rows use normalized millisecond OHLCV timestamps. Reject
108
+ incomplete, stale, gapped or invalid history. The swing and all bars used
109
+ to confirm it must be inside the lookback. Never search older swings when
110
+ the latest one is broken, too wide or on the wrong side of the reference.
111
+ Distances include the buffer and outward exchange-tick rounding.
112
+
113
+ A None candle-range limit permits a coarser fallback after finer history
114
+ fails validation; it never relaxes the buffered stop-distance limit.
115
+ Prefer refine_swing_protection for the full 15m -> 5m -> 1m decision.
116
+ Entry callers use the intended entry as reference; live trailing callers
117
+ use the current favorable price and separately enforce tightening only.
118
+ """
119
+ if (
120
+ position not in (Position.long, Position.short)
121
+ or interval_minutes not in PROTECTION_INTERVALS_MINUTES
122
+ or lookback_ms <= 0
123
+ or lookback_ms > PROTECTION_LOOKBACK_MS
124
+ or fractal_wing < 1
125
+ or price_precision < 0
126
+ or not all(
127
+ isfinite(value)
128
+ for value in (
129
+ reference_price,
130
+ buffer_pct,
131
+ max_distance_pct,
132
+ min_distance_pct,
133
+ )
134
+ )
135
+ or reference_price <= 0
136
+ or not 0 <= buffer_pct < 100
137
+ or not 0 <= min_distance_pct < max_distance_pct <= 3
138
+ or (max_candle_range_pct is not None and not 0 < max_candle_range_pct <= 3)
139
+ ):
140
+ return None
141
+ rows = _completed_protection_window(
142
+ candles,
143
+ now_ms=now_ms,
144
+ interval_minutes=interval_minutes,
145
+ lookback_ms=lookback_ms,
146
+ fractal_wing=fractal_wing,
147
+ price_precision=price_precision,
148
+ )
149
+ if rows is None:
150
+ return None
151
+ interval_ms = interval_minutes * 60 * 1000
152
+
153
+ short = position == Position.short
154
+ value_column = 2 if short else 3
155
+ swing_index = next(
156
+ (
157
+ index
158
+ for index in range(len(rows) - fractal_wing - 1, fractal_wing - 1, -1)
159
+ if rows[index][0] >= not_before_ms
160
+ and all(
161
+ (rows[index][value_column] > rows[neighbor][value_column])
162
+ if short
163
+ else (rows[index][value_column] < rows[neighbor][value_column])
164
+ for neighbor in range(index - fractal_wing, index + fractal_wing + 1)
165
+ if neighbor != index
166
+ )
167
+ ),
168
+ None,
169
+ )
170
+ if swing_index is None:
171
+ return None
172
+ timestamp, _opening, high, low, _close = rows[swing_index]
173
+ swing_price = high if short else low
174
+ if any(
175
+ row[value_column] >= swing_price if short else row[value_column] <= swing_price
176
+ for row in rows[swing_index + 1 :]
177
+ ):
178
+ return None
179
+ candle_range = (Decimal(str(high)) / Decimal(str(low)) - 1) * 100
180
+ if max_candle_range_pct is not None and candle_range > Decimal(
181
+ str(max_candle_range_pct)
182
+ ):
183
+ return None
184
+ direction = Decimal(1 if short else -1)
185
+ stop = (
186
+ Decimal(str(swing_price)) * (1 + direction * Decimal(str(buffer_pct)) / 100)
187
+ ).quantize(
188
+ Decimal(1).scaleb(-price_precision),
189
+ rounding=ROUND_CEILING if short else ROUND_FLOOR,
190
+ )
191
+ distance = direction * (stop / Decimal(str(reference_price)) - 1) * 100
192
+ if (
193
+ stop <= 0
194
+ or distance <= 0
195
+ or distance < Decimal(str(min_distance_pct))
196
+ or distance > Decimal(str(max_distance_pct))
197
+ ):
198
+ return None
199
+ return SwingProtection(
200
+ interval_minutes=interval_minutes,
201
+ swing_open_time_ms=timestamp,
202
+ confirmation_time_ms=rows[swing_index + fractal_wing][0] + interval_ms - 1,
203
+ stop_price=float(stop),
204
+ distance_pct=float(distance),
205
+ candle_range_pct=float(candle_range),
206
+ )
207
+
208
+
209
+ @dataclass(frozen=True)
210
+ class SwingProtectionSelection:
211
+ protection: SwingProtection | None = None
212
+ required_interval_minutes: int | None = None
213
+ used_coarser_fallback: bool = False
214
+
215
+
216
+ def refine_swing_protection(
217
+ candles_by_interval: Mapping[int, Sequence[Sequence[float]]],
218
+ *,
219
+ position: Position,
220
+ reference_price: float,
221
+ now_ms: int,
222
+ price_precision: int,
223
+ buffer_pct: float = 0.1,
224
+ max_distance_pct: float = MAX_PROTECTION_DISTANCE_PCT,
225
+ min_distance_pct: float = 0.0,
226
+ lookback_ms: int = PROTECTION_LOOKBACK_MS,
227
+ not_before_ms: int = 0,
228
+ ) -> SwingProtectionSelection:
229
+ """Descend through wide candles, but back up when finer history is unusable.
230
+
231
+ Missing dictionary entries request the next timeframe from the caller;
232
+ an empty list represents a completed read with unavailable data. A gap,
233
+ duplicate or stale bar ends refinement and selects the nearest healthy
234
+ coarser swing that fits the hard distance cap. A wide coarser candle may
235
+ be used in this case; an over-distance or broken swing never qualifies.
236
+ """
237
+ if (
238
+ position not in (Position.long, Position.short)
239
+ or price_precision < 0
240
+ or not 0 < lookback_ms <= PROTECTION_LOOKBACK_MS
241
+ or not all(
242
+ isfinite(value)
243
+ for value in (
244
+ reference_price,
245
+ buffer_pct,
246
+ max_distance_pct,
247
+ min_distance_pct,
248
+ )
249
+ )
250
+ or reference_price <= 0
251
+ or not 0 <= buffer_pct < 100
252
+ or not 0 <= min_distance_pct < max_distance_pct <= 3
253
+ ):
254
+ return SwingProtectionSelection()
255
+ fallback = None
256
+ for interval in PROTECTION_INTERVALS_MINUTES:
257
+ if interval not in candles_by_interval:
258
+ return SwingProtectionSelection(required_interval_minutes=interval)
259
+ candles = candles_by_interval[interval]
260
+ if (
261
+ _completed_protection_window(
262
+ candles,
263
+ now_ms=now_ms,
264
+ interval_minutes=interval,
265
+ lookback_ms=lookback_ms,
266
+ fractal_wing=2,
267
+ price_precision=price_precision,
268
+ )
269
+ is None
270
+ ):
271
+ return SwingProtectionSelection(
272
+ protection=fallback,
273
+ used_coarser_fallback=fallback is not None,
274
+ )
275
+ candidate = recent_swing_protection(
276
+ candles,
277
+ position=position,
278
+ reference_price=reference_price,
279
+ now_ms=now_ms,
280
+ interval_minutes=interval,
281
+ price_precision=price_precision,
282
+ buffer_pct=buffer_pct,
283
+ max_distance_pct=max_distance_pct,
284
+ min_distance_pct=min_distance_pct,
285
+ lookback_ms=lookback_ms,
286
+ not_before_ms=not_before_ms,
287
+ max_candle_range_pct=None,
288
+ )
289
+ if candidate is not None:
290
+ if candidate.candle_range_pct <= MAX_PROTECTION_CANDLE_RANGE_PCT:
291
+ return SwingProtectionSelection(protection=candidate)
292
+ fallback = candidate
293
+ return SwingProtectionSelection()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.7
3
+ Version: 2.1.12
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,54 @@ 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.
175
+
176
+ `refine_swing_protection` manages the whole timeframe decision. If 1m history
177
+ is gapped or unreliable, it returns the nearest trustworthy coarser swing.
178
+ Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
179
+ gaps make a source unreliable. Price gaps are non-overlapping candle ranges
180
+ separated by more than 0.1% and two price-precision ticks; more than 20% of
181
+ transitions, with at least two gaps, rejects the timeframe.
182
+
183
+ The 3% candle-width threshold prompts refinement. It can be relaxed for a
184
+ coarser fallback after finer data fails, while the buffered stop-distance cap,
185
+ three-hour swing age, confirmation and unbroken-swing requirements still apply.
186
+ If no coarser swing fits, the result has no placement. A missing timeframe in
187
+ the input mapping requests that interval; an empty list means the read finished
188
+ without usable data. Live callers can therefore keep exchange reads off the
189
+ protective exit path while this decision remains shared with entry strategies.
@@ -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.12"
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,271 @@
1
+ from copy import deepcopy
2
+
3
+ import pytest
4
+
5
+ from pybinbot import Position
6
+ from pybinbot.strategy.swing_protection import (
7
+ recent_swing_protection,
8
+ refine_swing_protection,
9
+ )
10
+
11
+
12
+ NOW_MS = 1_800_000_000_000
13
+
14
+
15
+ def candles(interval=15, *, high=102.0, count=12):
16
+ interval_ms = interval * 60_000
17
+ highs = [100.0] * (count - 5) + [100, 101, high, 101, 100]
18
+ rows = []
19
+ previous_close = highs[0] - 0.1
20
+ for index, value in enumerate(highs):
21
+ rows.append(
22
+ [
23
+ NOW_MS - (count - index) * interval_ms,
24
+ previous_close,
25
+ max(value, previous_close),
26
+ min(value - 0.2, previous_close),
27
+ value - 0.1,
28
+ 10,
29
+ NOW_MS - (count - index - 1) * interval_ms - 1,
30
+ ]
31
+ )
32
+ previous_close = value - 0.1
33
+ return rows
34
+
35
+
36
+ def resolve(rows, *, interval=15, position=Position.short, **kwargs):
37
+ return recent_swing_protection(
38
+ rows,
39
+ position=position,
40
+ reference_price=100,
41
+ now_ms=NOW_MS,
42
+ interval_minutes=interval,
43
+ price_precision=4,
44
+ **kwargs,
45
+ )
46
+
47
+
48
+ @pytest.mark.parametrize("interval", [15, 5, 1])
49
+ @pytest.mark.parametrize("position", [Position.long, Position.short])
50
+ def test_recent_confirmed_swing_protects_each_direction_at_each_timeframe(
51
+ interval, position
52
+ ):
53
+ rows = candles(interval)
54
+ if position == Position.long:
55
+ rows = [
56
+ [t, 200 - o, 200 - low, 200 - high, 200 - c, v, end]
57
+ for t, o, high, low, c, v, end in rows
58
+ ]
59
+
60
+ result = resolve(rows, interval=interval, position=position)
61
+
62
+ assert result is not None
63
+ assert result.interval_minutes == interval
64
+ assert result.swing_open_time_ms == NOW_MS - 3 * interval * 60_000
65
+ assert result.confirmation_time_ms == NOW_MS - 1
66
+ assert 2 < result.distance_pct < 2.5
67
+ assert (
68
+ result.stop_price > 100
69
+ if position == Position.short
70
+ else result.stop_price < 100
71
+ )
72
+
73
+
74
+ def test_six_percent_candle_requires_a_smaller_timeframe_even_with_a_nearby_peak():
75
+ rows = candles()
76
+ rows[-3][3] = 95
77
+
78
+ assert resolve(rows) is None
79
+ assert resolve(candles(5), interval=5) is not None
80
+
81
+
82
+ def test_wide_candle_fallback_cannot_hide_a_stop_more_than_two_and_a_half_percent_away():
83
+ assert resolve(candles(high=106.35), max_candle_range_pct=None) is None
84
+
85
+
86
+ def test_stop_distance_includes_buffer_and_outward_tick_rounding():
87
+ assert resolve(candles(), buffer_pct=0.5) is None
88
+ result = resolve(candles(high=101.99991))
89
+ assert result is not None
90
+ assert result.stop_price == 102.102
91
+ assert result.distance_pct == pytest.approx(2.102)
92
+
93
+
94
+ @pytest.mark.parametrize("high,qualifies", [(102.5, True), (102.5001, False)])
95
+ def test_stop_distance_cap_is_inclusive_without_clipping(high, qualifies):
96
+ assert (resolve(candles(high=high), buffer_pct=0) is not None) is qualifies
97
+
98
+
99
+ def test_unclosed_candle_cannot_confirm_a_swing():
100
+ rows = candles()
101
+ rows[-1][0] += 15 * 60_000
102
+ rows[-1][6] += 15 * 60_000
103
+ assert resolve(rows) is None
104
+
105
+
106
+ @pytest.mark.parametrize("problem", ["stale", "gap", "duplicate", "nan", "ohlc"])
107
+ def test_invalid_or_incomplete_history_cannot_place_protection(problem):
108
+ rows = candles()
109
+ if problem == "stale":
110
+ rows.pop()
111
+ elif problem == "gap":
112
+ rows.pop(-4)
113
+ elif problem == "duplicate":
114
+ rows.append(deepcopy(rows[-1]))
115
+ elif problem == "nan":
116
+ rows[-4][2] = float("nan")
117
+ else:
118
+ rows[-4][3] = rows[-4][2] + 1
119
+ assert resolve(rows) is None
120
+
121
+
122
+ def test_cannot_resurrect_a_swing_older_than_three_hours():
123
+ rows = candles(count=24)
124
+ for row in rows:
125
+ row[0] -= 3 * 60 * 60_000
126
+ row[6] -= 3 * 60 * 60_000
127
+ rows.extend(
128
+ [
129
+ [
130
+ NOW_MS - (12 - i) * 900_000,
131
+ 100,
132
+ 100.1,
133
+ 99.9,
134
+ 100,
135
+ 10,
136
+ NOW_MS - (11 - i) * 900_000 - 1,
137
+ ]
138
+ for i in range(12)
139
+ ]
140
+ )
141
+ assert resolve(rows) is None
142
+
143
+
144
+ def test_swing_window_can_be_restricted_to_one_hour_or_the_current_setup():
145
+ rows = candles()
146
+ assert resolve(rows, lookback_ms=60 * 60_000) is None # Only four 15m bars.
147
+ assert resolve(rows, not_before_ms=NOW_MS - 30 * 60_000) is None
148
+ assert resolve(rows, lookback_ms=4 * 60 * 60_000) is None
149
+
150
+
151
+ def test_latest_unconfirmed_break_invalidates_the_old_peak():
152
+ rows = candles(count=14)
153
+ rows[-1][2] = 103
154
+ assert resolve(rows) is None
155
+
156
+
157
+ def test_latest_wide_swing_does_not_fall_back_to_an_arbitrary_older_peak():
158
+ rows = candles(high=106.35)
159
+ rows[3][2] = 101
160
+ assert resolve(rows) is None
161
+
162
+
163
+ def wide_candles(interval):
164
+ rows = candles(interval)
165
+ rows[-3][3] = 95.0
166
+ return rows
167
+
168
+
169
+ def refine(history, *, position=Position.short):
170
+ if position == Position.long:
171
+ history = {
172
+ interval: [
173
+ [t, 200 - o, 200 - low, 200 - high, 200 - c, v, end]
174
+ for t, o, high, low, c, v, end in rows
175
+ ]
176
+ for interval, rows in history.items()
177
+ }
178
+ return refine_swing_protection(
179
+ history,
180
+ position=position,
181
+ reference_price=100,
182
+ now_ms=NOW_MS,
183
+ price_precision=4,
184
+ )
185
+
186
+
187
+ def test_wide_candles_request_the_next_finer_timeframe():
188
+ decision = refine({15: wide_candles(15), 5: wide_candles(5)})
189
+ assert decision.protection is None
190
+ assert decision.required_interval_minutes == 1
191
+
192
+
193
+ def test_continuous_one_minute_data_is_used_when_coarser_candles_are_wide():
194
+ decision = refine({15: wide_candles(15), 5: wide_candles(5), 1: candles(1)})
195
+ assert decision.protection is not None
196
+ assert decision.protection.interval_minutes == 1
197
+ assert not decision.used_coarser_fallback
198
+
199
+
200
+ @pytest.mark.parametrize(
201
+ "problem", ["missing", "empty", "stale", "duplicate", "no_trades", "price_gaps"]
202
+ )
203
+ @pytest.mark.parametrize("position", [Position.short, Position.long])
204
+ def test_untrustworthy_one_minute_history_falls_back_to_safe_five_minute_structure(
205
+ problem,
206
+ position,
207
+ ):
208
+ fine = candles(1)
209
+ if problem == "missing":
210
+ fine.pop(-4)
211
+ elif problem == "empty":
212
+ fine = []
213
+ elif problem == "stale":
214
+ fine.pop()
215
+ elif problem == "duplicate":
216
+ fine.append(deepcopy(fine[-1]))
217
+ elif problem == "no_trades":
218
+ fine[-4][5] = 0
219
+ else:
220
+ for index, row in enumerate(fine):
221
+ offset = 2 if index % 2 else 0
222
+ row[1:5] = [value + offset for value in row[1:5]]
223
+ decision = refine(
224
+ {15: wide_candles(15), 5: wide_candles(5), 1: fine}, position=position
225
+ )
226
+ assert decision.protection is not None
227
+ assert decision.protection.interval_minutes == 5
228
+ assert decision.protection.candle_range_pct > 3
229
+ assert decision.protection.distance_pct < 2.5
230
+ assert decision.used_coarser_fallback
231
+ assert decision.required_interval_minutes is None
232
+
233
+
234
+ def test_untrustworthy_five_minute_history_falls_back_to_fifteen_minutes():
235
+ fine = candles(5)
236
+ fine.pop(-4)
237
+ decision = refine({15: wide_candles(15), 5: fine})
238
+ assert decision.protection is not None
239
+ assert decision.protection.interval_minutes == 15
240
+ assert decision.used_coarser_fallback
241
+
242
+
243
+ def test_coarser_fallback_cannot_bypass_the_buffered_stop_distance_cap():
244
+ fine = candles(1)
245
+ fine.pop(-4)
246
+ decision = refine(
247
+ {15: candles(15, high=106.35), 5: candles(5, high=106.35), 1: fine}
248
+ )
249
+ assert decision.protection is None
250
+ assert decision.required_interval_minutes is None
251
+
252
+
253
+ def test_broken_coarser_swing_cannot_be_used_as_a_gap_fallback():
254
+ coarse = wide_candles(5)
255
+ coarse[-1][2] = 103
256
+ fine = candles(1)
257
+ fine.pop(-4)
258
+ # No valid 15m stop; the latest 5m peak was breached by an unconfirmed bar.
259
+ decision = refine({15: candles(15, high=106.35), 5: coarse, 1: fine})
260
+ assert decision.protection is None
261
+
262
+
263
+ def test_missing_coarse_history_cannot_be_replaced_by_a_trustworthy_finer_frame():
264
+ decision = refine({15: [], 5: candles(5), 1: candles(1)})
265
+ assert decision.protection is None
266
+
267
+
268
+ def test_one_small_price_gap_does_not_make_an_otherwise_continuous_history_unusable():
269
+ rows = candles(1)
270
+ rows[1][1:5] = [value + 0.31 for value in rows[1][1:5]]
271
+ assert resolve(rows, interval=1) is not None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes