pybinbot 2.1.9__tar.gz → 2.1.13__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 (91) hide show
  1. {pybinbot-2.1.9/pybinbot.egg-info → pybinbot-2.1.13}/PKG-INFO +19 -1
  2. {pybinbot-2.1.9 → pybinbot-2.1.13}/README.md +18 -0
  3. pybinbot-2.1.13/pybinbot/strategy/swing_protection.py +305 -0
  4. {pybinbot-2.1.9 → pybinbot-2.1.13/pybinbot.egg-info}/PKG-INFO +19 -1
  5. {pybinbot-2.1.9 → pybinbot-2.1.13}/pyproject.toml +1 -1
  6. pybinbot-2.1.13/tests/test_swing_protection.py +336 -0
  7. pybinbot-2.1.9/pybinbot/strategy/swing_protection.py +0 -167
  8. pybinbot-2.1.9/tests/test_swing_protection.py +0 -153
  9. {pybinbot-2.1.9 → pybinbot-2.1.13}/LICENSE +0 -0
  10. {pybinbot-2.1.9 → pybinbot-2.1.13}/MANIFEST.in +0 -0
  11. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/__init__.py +0 -0
  12. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/binance/base.py +0 -0
  13. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/binance/exceptions.py +0 -0
  14. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/binbot/base.py +0 -0
  15. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/binbot/exceptions.py +0 -0
  16. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/coingecko.py +0 -0
  17. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/kucoin/base.py +0 -0
  18. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/kucoin/exceptions.py +0 -0
  19. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/kucoin/futures.py +0 -0
  20. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/kucoin/market.py +0 -0
  21. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/kucoin/orders.py +0 -0
  22. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/apis/kucoin/rest.py +0 -0
  23. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/__init__.py +0 -0
  24. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/autotrade_settings.py +0 -0
  25. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/bot.py +0 -0
  26. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/bot_base.py +0 -0
  27. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/cvd.py +0 -0
  28. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/deal.py +0 -0
  29. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/derivatives.py +0 -0
  30. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/fastest_movers.py +0 -0
  31. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/grid_ladder.py +0 -0
  32. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/order.py +0 -0
  33. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/routes.py +0 -0
  34. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/signals.py +0 -0
  35. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/models/symbol.py +0 -0
  36. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/py.typed +0 -0
  37. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/__init__.py +0 -0
  38. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/beta.py +0 -0
  39. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/breadth.py +0 -0
  40. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/cache.py +0 -0
  41. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/candles.py +0 -0
  42. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/enums.py +0 -0
  43. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/handlers.py +0 -0
  44. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/heikin_ashi.py +0 -0
  45. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/indicators.py +0 -0
  46. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/logging_config.py +0 -0
  47. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/maths.py +0 -0
  48. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/price_crossings.py +0 -0
  49. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/telegram_delivery.py +0 -0
  50. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/timestamps.py +0 -0
  51. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/types.py +0 -0
  52. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/shared/utils.py +0 -0
  53. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/strategy/beta.py +0 -0
  54. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/strategy/breadth.py +0 -0
  55. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/strategy/price_crossings.py +0 -0
  56. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/streaming/binance/async_socket_client.py +0 -0
  57. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/streaming/binance/socket_client.py +0 -0
  58. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/streaming/binance/socket_manager.py +0 -0
  59. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot/streaming/kucoin/kucoin_async_client.py +0 -0
  60. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot.egg-info/SOURCES.txt +0 -0
  61. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot.egg-info/dependency_links.txt +0 -0
  62. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot.egg-info/requires.txt +0 -0
  63. {pybinbot-2.1.9 → pybinbot-2.1.13}/pybinbot.egg-info/top_level.txt +0 -0
  64. {pybinbot-2.1.9 → pybinbot-2.1.13}/setup.cfg +0 -0
  65. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_beta.py +0 -0
  66. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_binbot_api.py +0 -0
  67. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_bot_futures_leverage.py +0 -0
  68. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_breadth.py +0 -0
  69. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_candles.py +0 -0
  70. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_closed_bot_status.py +0 -0
  71. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_coingecko.py +0 -0
  72. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_conditional_entry.py +0 -0
  73. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_conditional_futures_orders.py +0 -0
  74. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_cvd_api.py +0 -0
  75. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_deal_model.py +0 -0
  76. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_derivatives_api.py +0 -0
  77. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_fastest_movers.py +0 -0
  78. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_futures_place_order.py +0 -0
  79. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_grid_ladder.py +0 -0
  80. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_handlers.py +0 -0
  81. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_heikin_ashi.py +0 -0
  82. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_indicators.py +0 -0
  83. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_kucoin_api.py +0 -0
  84. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_logging_config.py +0 -0
  85. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_matching_engine.py +0 -0
  86. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_maths.py +0 -0
  87. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_price_crossings.py +0 -0
  88. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_symbol_model.py +0 -0
  89. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_telegram_delivery.py +0 -0
  90. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_timestamps.py +0 -0
  91. {pybinbot-2.1.9 → pybinbot-2.1.13}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.9
3
+ Version: 2.1.13
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -168,7 +168,25 @@ in `pybinbot.shared`. New reusable strategy calculations belong in
168
168
  confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
169
169
  that order when a candidate is unsuitable. The maximum search window is three
170
170
  hours, optionally narrowed to one hour or to the start of the current setup.
171
+ The reference price must remain on the protected side of the unbuffered swing.
172
+ A forming candle cannot confirm a swing, but a wick touching or crossing the
173
+ swing invalidates it even when the current price subsequently recovers.
171
174
  The selector rejects swing candles wider than 3% and stop distances over 2.5%
172
175
  after the buffer and outward tick rounding. It never clips a distant swing or
173
176
  searches older swings to force a result. Entry callers skip when all timeframes
174
177
  fail; live callers retain existing protection and only apply tighter stops.
178
+
179
+ `refine_swing_protection` manages the whole timeframe decision. If 1m history
180
+ is gapped or unreliable, it returns the nearest trustworthy coarser swing.
181
+ Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
182
+ gaps make a source unreliable. Price gaps are non-overlapping candle ranges
183
+ separated by more than 0.1% and two price-precision ticks; more than 20% of
184
+ transitions, with at least two gaps, rejects the timeframe.
185
+
186
+ The 3% candle-width threshold prompts refinement. It can be relaxed for a
187
+ coarser fallback after finer data fails, while the buffered stop-distance cap,
188
+ three-hour swing age, confirmation and unbroken-swing requirements still apply.
189
+ If no coarser swing fits, the result has no placement. A missing timeframe in
190
+ the input mapping requests that interval; an empty list means the read finished
191
+ without usable data. Live callers can therefore keep exchange reads off the
192
+ protective exit path while this decision remains shared with entry strategies.
@@ -139,7 +139,25 @@ in `pybinbot.shared`. New reusable strategy calculations belong in
139
139
  confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
140
140
  that order when a candidate is unsuitable. The maximum search window is three
141
141
  hours, optionally narrowed to one hour or to the start of the current setup.
142
+ The reference price must remain on the protected side of the unbuffered swing.
143
+ A forming candle cannot confirm a swing, but a wick touching or crossing the
144
+ swing invalidates it even when the current price subsequently recovers.
142
145
  The selector rejects swing candles wider than 3% and stop distances over 2.5%
143
146
  after the buffer and outward tick rounding. It never clips a distant swing or
144
147
  searches older swings to force a result. Entry callers skip when all timeframes
145
148
  fail; live callers retain existing protection and only apply tighter stops.
149
+
150
+ `refine_swing_protection` manages the whole timeframe decision. If 1m history
151
+ is gapped or unreliable, it returns the nearest trustworthy coarser swing.
152
+ Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
153
+ gaps make a source unreliable. Price gaps are non-overlapping candle ranges
154
+ separated by more than 0.1% and two price-precision ticks; more than 20% of
155
+ transitions, with at least two gaps, rejects the timeframe.
156
+
157
+ The 3% candle-width threshold prompts refinement. It can be relaxed for a
158
+ coarser fallback after finer data fails, while the buffered stop-distance cap,
159
+ three-hour swing age, confirmation and unbroken-swing requirements still apply.
160
+ If no coarser swing fits, the result has no placement. A missing timeframe in
161
+ the input mapping requests that interval; an empty list means the read finished
162
+ without usable data. Live callers can therefore keep exchange reads off the
163
+ protective exit path while this decision remains shared with entry strategies.
@@ -0,0 +1,305 @@
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 reference_price >= swing_price if short else reference_price <= swing_price:
175
+ return None
176
+ # A forming candle cannot confirm a swing, but its wick can break one.
177
+ # Check the raw input as well as the reference so a recovered price or a
178
+ # wide buffer cannot conceal that the confirmed structure was reclaimed.
179
+ try:
180
+ for candle in candles:
181
+ candle_time = float(candle[0])
182
+ if not timestamp < candle_time <= now_ms:
183
+ continue
184
+ extreme = float(candle[value_column])
185
+ if not isfinite(extreme) or extreme <= 0:
186
+ return None
187
+ if extreme >= swing_price if short else extreme <= swing_price:
188
+ return None
189
+ except IndexError, TypeError, ValueError, OverflowError:
190
+ return None
191
+ candle_range = (Decimal(str(high)) / Decimal(str(low)) - 1) * 100
192
+ if max_candle_range_pct is not None and candle_range > Decimal(
193
+ str(max_candle_range_pct)
194
+ ):
195
+ return None
196
+ direction = Decimal(1 if short else -1)
197
+ stop = (
198
+ Decimal(str(swing_price)) * (1 + direction * Decimal(str(buffer_pct)) / 100)
199
+ ).quantize(
200
+ Decimal(1).scaleb(-price_precision),
201
+ rounding=ROUND_CEILING if short else ROUND_FLOOR,
202
+ )
203
+ distance = direction * (stop / Decimal(str(reference_price)) - 1) * 100
204
+ if (
205
+ stop <= 0
206
+ or distance <= 0
207
+ or distance < Decimal(str(min_distance_pct))
208
+ or distance > Decimal(str(max_distance_pct))
209
+ ):
210
+ return None
211
+ return SwingProtection(
212
+ interval_minutes=interval_minutes,
213
+ swing_open_time_ms=timestamp,
214
+ confirmation_time_ms=rows[swing_index + fractal_wing][0] + interval_ms - 1,
215
+ stop_price=float(stop),
216
+ distance_pct=float(distance),
217
+ candle_range_pct=float(candle_range),
218
+ )
219
+
220
+
221
+ @dataclass(frozen=True)
222
+ class SwingProtectionSelection:
223
+ protection: SwingProtection | None = None
224
+ required_interval_minutes: int | None = None
225
+ used_coarser_fallback: bool = False
226
+
227
+
228
+ def refine_swing_protection(
229
+ candles_by_interval: Mapping[int, Sequence[Sequence[float]]],
230
+ *,
231
+ position: Position,
232
+ reference_price: float,
233
+ now_ms: int,
234
+ price_precision: int,
235
+ buffer_pct: float = 0.1,
236
+ max_distance_pct: float = MAX_PROTECTION_DISTANCE_PCT,
237
+ min_distance_pct: float = 0.0,
238
+ lookback_ms: int = PROTECTION_LOOKBACK_MS,
239
+ not_before_ms: int = 0,
240
+ ) -> SwingProtectionSelection:
241
+ """Descend through wide candles, but back up when finer history is unusable.
242
+
243
+ Missing dictionary entries request the next timeframe from the caller;
244
+ an empty list represents a completed read with unavailable data. A gap,
245
+ duplicate or stale bar ends refinement and selects the nearest healthy
246
+ coarser swing that fits the hard distance cap. A wide coarser candle may
247
+ be used in this case; an over-distance or broken swing never qualifies.
248
+ """
249
+ if (
250
+ position not in (Position.long, Position.short)
251
+ or price_precision < 0
252
+ or not 0 < lookback_ms <= PROTECTION_LOOKBACK_MS
253
+ or not all(
254
+ isfinite(value)
255
+ for value in (
256
+ reference_price,
257
+ buffer_pct,
258
+ max_distance_pct,
259
+ min_distance_pct,
260
+ )
261
+ )
262
+ or reference_price <= 0
263
+ or not 0 <= buffer_pct < 100
264
+ or not 0 <= min_distance_pct < max_distance_pct <= 3
265
+ ):
266
+ return SwingProtectionSelection()
267
+ fallback = None
268
+ for interval in PROTECTION_INTERVALS_MINUTES:
269
+ if interval not in candles_by_interval:
270
+ return SwingProtectionSelection(required_interval_minutes=interval)
271
+ candles = candles_by_interval[interval]
272
+ if (
273
+ _completed_protection_window(
274
+ candles,
275
+ now_ms=now_ms,
276
+ interval_minutes=interval,
277
+ lookback_ms=lookback_ms,
278
+ fractal_wing=2,
279
+ price_precision=price_precision,
280
+ )
281
+ is None
282
+ ):
283
+ return SwingProtectionSelection(
284
+ protection=fallback,
285
+ used_coarser_fallback=fallback is not None,
286
+ )
287
+ candidate = recent_swing_protection(
288
+ candles,
289
+ position=position,
290
+ reference_price=reference_price,
291
+ now_ms=now_ms,
292
+ interval_minutes=interval,
293
+ price_precision=price_precision,
294
+ buffer_pct=buffer_pct,
295
+ max_distance_pct=max_distance_pct,
296
+ min_distance_pct=min_distance_pct,
297
+ lookback_ms=lookback_ms,
298
+ not_before_ms=not_before_ms,
299
+ max_candle_range_pct=None,
300
+ )
301
+ if candidate is not None:
302
+ if candidate.candle_range_pct <= MAX_PROTECTION_CANDLE_RANGE_PCT:
303
+ return SwingProtectionSelection(protection=candidate)
304
+ fallback = candidate
305
+ return SwingProtectionSelection()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybinbot
3
- Version: 2.1.9
3
+ Version: 2.1.13
4
4
  Summary: Utility functions for the binbot project.
5
5
  Author-email: Carlos Wu <carkodw@gmail.com>
6
6
  Requires-Python: >=3.15
@@ -168,7 +168,25 @@ in `pybinbot.shared`. New reusable strategy calculations belong in
168
168
  confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
169
169
  that order when a candidate is unsuitable. The maximum search window is three
170
170
  hours, optionally narrowed to one hour or to the start of the current setup.
171
+ The reference price must remain on the protected side of the unbuffered swing.
172
+ A forming candle cannot confirm a swing, but a wick touching or crossing the
173
+ swing invalidates it even when the current price subsequently recovers.
171
174
  The selector rejects swing candles wider than 3% and stop distances over 2.5%
172
175
  after the buffer and outward tick rounding. It never clips a distant swing or
173
176
  searches older swings to force a result. Entry callers skip when all timeframes
174
177
  fail; live callers retain existing protection and only apply tighter stops.
178
+
179
+ `refine_swing_protection` manages the whole timeframe decision. If 1m history
180
+ is gapped or unreliable, it returns the nearest trustworthy coarser swing.
181
+ Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
182
+ gaps make a source unreliable. Price gaps are non-overlapping candle ranges
183
+ separated by more than 0.1% and two price-precision ticks; more than 20% of
184
+ transitions, with at least two gaps, rejects the timeframe.
185
+
186
+ The 3% candle-width threshold prompts refinement. It can be relaxed for a
187
+ coarser fallback after finer data fails, while the buffered stop-distance cap,
188
+ three-hour swing age, confirmation and unbroken-swing requirements still apply.
189
+ If no coarser swing fits, the result has no placement. A missing timeframe in
190
+ the input mapping requests that interval; an empty list means the read finished
191
+ without usable data. Live callers can therefore keep exchange reads off the
192
+ protective exit path while this decision remains shared with entry strategies.
@@ -23,7 +23,7 @@ build-backend = "setuptools.build_meta"
23
23
 
24
24
  [project]
25
25
  name = "pybinbot"
26
- version = "2.1.9"
26
+ version = "2.1.13"
27
27
  description = "Utility functions for the binbot project."
28
28
  authors = [
29
29
  { name="Carlos Wu", email="carkodw@gmail.com" }