Naufal Arhab commited on
Commit
abeb2e6
·
1 Parent(s): 86abcb2

fix(execution): add directional SL/TP validation, robust price/leverage parsing, and small TP2 merge fallback

Browse files
backend/engine/execution/bybit_executor.py CHANGED
@@ -257,6 +257,22 @@ class BybitExecutor:
257
  rounded_tp1 = self._round_tick(take_profit_1, tick_size)
258
  rounded_tp2 = self._round_tick(take_profit_2, tick_size) if (take_profit_2 and take_profit_2 > 0) else None
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  # 6. Build and submit primary entry order
261
  order_payload: dict[str, Any] = {
262
  "category": "linear",
@@ -270,6 +286,11 @@ class BybitExecutor:
270
  "slTriggerBy": "MarkPrice",
271
  }
272
 
 
 
 
 
 
273
  if order_type.upper() == "LIMIT" and entry_price:
274
  order_payload["price"] = str(self._round_tick(entry_price, tick_size))
275
 
@@ -281,6 +302,14 @@ class BybitExecutor:
281
  tp1_pct = max(10.0, min(float(tp1_percent), 100.0))
282
  tp1_orders_info = []
283
 
 
 
 
 
 
 
 
 
284
  if tp1_pct >= 99.0 or not rounded_tp2:
285
  # 100% full position to TP1
286
  tp1_qty = total_qty
@@ -312,7 +341,11 @@ class BybitExecutor:
312
  tp1_qty = self._round_step(raw_tp1_qty, qty_step)
313
  tp2_qty = self._round_step(total_qty - tp1_qty, qty_step)
314
 
315
- # Ensure both meet minimum qty
 
 
 
 
316
  if tp1_qty >= min_qty:
317
  tp1_payload = {
318
  "category": "linear",
@@ -329,7 +362,7 @@ class BybitExecutor:
329
  tp1_resp = await self._request("POST", "/v5/order/create", json_body=tp1_payload)
330
  tp1_orders_info.append({
331
  "tp_level": "TP1",
332
- "percent": tp1_pct,
333
  "order_id": tp1_resp.get("result", {}).get("orderId"),
334
  "price": rounded_tp1,
335
  "qty": tp1_qty,
 
257
  rounded_tp1 = self._round_tick(take_profit_1, tick_size)
258
  rounded_tp2 = self._round_tick(take_profit_2, tick_size) if (take_profit_2 and take_profit_2 > 0) else None
259
 
260
+ # Directional validation to protect user funds from inverted orders
261
+ if side_norm == "Buy":
262
+ if rounded_sl >= calc_price:
263
+ raise ValueError(f"Stop Loss (${rounded_sl}) harus lebih rendah dari harga Entry (${calc_price}) untuk posisi Long.")
264
+ if rounded_tp1 <= calc_price:
265
+ raise ValueError(f"Take Profit 1 (${rounded_tp1}) harus lebih tinggi dari harga Entry (${calc_price}) untuk posisi Long.")
266
+ if rounded_tp2 and rounded_tp2 <= rounded_tp1:
267
+ raise ValueError(f"Take Profit 2 (${rounded_tp2}) harus lebih tinggi dari TP1 (${rounded_tp1}) untuk posisi Long.")
268
+ else:
269
+ if rounded_sl <= calc_price:
270
+ raise ValueError(f"Stop Loss (${rounded_sl}) harus lebih tinggi dari harga Entry (${calc_price}) untuk posisi Short.")
271
+ if rounded_tp1 >= calc_price:
272
+ raise ValueError(f"Take Profit 1 (${rounded_tp1}) harus lebih rendah dari harga Entry (${calc_price}) untuk posisi Short.")
273
+ if rounded_tp2 and rounded_tp2 >= rounded_tp1:
274
+ raise ValueError(f"Take Profit 2 (${rounded_tp2}) harus lebih rendah dari TP1 (${rounded_tp1}) untuk posisi Short.")
275
+
276
  # 6. Build and submit primary entry order
277
  order_payload: dict[str, Any] = {
278
  "category": "linear",
 
286
  "slTriggerBy": "MarkPrice",
287
  }
288
 
289
+ # For Limit orders, also attach takeProfit to the order to ensure it is active upon fill
290
+ if order_type.upper() == "LIMIT":
291
+ order_payload["takeProfit"] = str(rounded_tp1)
292
+ order_payload["tpTriggerBy"] = "MarkPrice"
293
+
294
  if order_type.upper() == "LIMIT" and entry_price:
295
  order_payload["price"] = str(self._round_tick(entry_price, tick_size))
296
 
 
302
  tp1_pct = max(10.0, min(float(tp1_percent), 100.0))
303
  tp1_orders_info = []
304
 
305
+ # If Market order, pause briefly to let Bybit matching engine register the filled position
306
+ if order_type.upper() == "MARKET":
307
+ try:
308
+ import asyncio
309
+ await asyncio.sleep(0.3)
310
+ except Exception:
311
+ pass
312
+
313
  if tp1_pct >= 99.0 or not rounded_tp2:
314
  # 100% full position to TP1
315
  tp1_qty = total_qty
 
341
  tp1_qty = self._round_step(raw_tp1_qty, qty_step)
342
  tp2_qty = self._round_step(total_qty - tp1_qty, qty_step)
343
 
344
+ # If either slice is below minimum contract size, merge 100% into TP1
345
+ if tp1_qty < min_qty or tp2_qty < min_qty:
346
+ tp1_qty = total_qty
347
+ tp2_qty = 0.0
348
+
349
  if tp1_qty >= min_qty:
350
  tp1_payload = {
351
  "category": "linear",
 
362
  tp1_resp = await self._request("POST", "/v5/order/create", json_body=tp1_payload)
363
  tp1_orders_info.append({
364
  "tp_level": "TP1",
365
+ "percent": tp1_pct if tp2_qty > 0 else 100.0,
366
  "order_id": tp1_resp.get("result", {}).get("orderId"),
367
  "price": rounded_tp1,
368
  "qty": tp1_qty,
frontend/src/components/execution/ExecutionModal.tsx CHANGED
@@ -29,19 +29,32 @@ interface ExecutionModalProps {
29
 
30
  function parsePrice(str?: string): number | null {
31
  if (!str) return null;
32
- const match = str.match(/([0-9,.]+)/);
33
- if (!match) return null;
34
- const cleaned = match[1].replace(/,/g, '');
35
- const val = parseFloat(cleaned);
36
- return isNaN(val) ? null : val;
 
 
 
 
 
 
 
 
 
 
37
  }
38
 
39
  function parseLeverage(str?: string): number {
40
  if (!str) return 3;
41
- const match = str.match(/([0-9]+)\s*x/i) || str.match(/([0-9]+)/);
42
- if (!match) return 3;
43
- const val = parseInt(match[1], 10);
44
- return isNaN(val) ? 3 : Math.min(Math.max(val, 1), 50);
 
 
 
45
  }
46
 
47
  export function ExecutionModal({
@@ -183,6 +196,35 @@ export function ExecutionModal({
183
  return;
184
  }
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  setIsSubmitting(true);
187
  try {
188
  const res = await executionApi.executeOrder({
 
29
 
30
  function parsePrice(str?: string): number | null {
31
  if (!str) return null;
32
+ // 1. Look for explicit dollar amount: $0.1850 or $12,345.67
33
+ const dollarMatch = str.match(/\$\s*([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/);
34
+ if (dollarMatch && dollarMatch[1]) {
35
+ const val = parseFloat(dollarMatch[1].replace(/,/g, ''));
36
+ if (!isNaN(val) && val > 0) return val;
37
+ }
38
+ // 2. Strip known timeframe or indicator label prefixes like TP1:, TP2:, 1H, 4H, 15M, 5M, 24H, 1D
39
+ const cleanedStr = str.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi, '');
40
+ // 3. Match decimal or float number
41
+ const numMatch = cleanedStr.match(/([0-9]+(?:\.[0-9]+)?)/);
42
+ if (numMatch && numMatch[1]) {
43
+ const val = parseFloat(numMatch[1]);
44
+ if (!isNaN(val) && val > 0) return val;
45
+ }
46
+ return null;
47
  }
48
 
49
  function parseLeverage(str?: string): number {
50
  if (!str) return 3;
51
+ // Match number directly attached to 'x' or 'X' (e.g. "3x", "2-3x")
52
+ const match = str.match(/([0-9]+)\s*x/i);
53
+ if (match && match[1]) {
54
+ const val = parseInt(match[1], 10);
55
+ if (!isNaN(val) && val > 0) return Math.min(Math.max(val, 1), 50);
56
+ }
57
+ return 3;
58
  }
59
 
60
  export function ExecutionModal({
 
196
  return;
197
  }
198
 
199
+ // Directional validation to prevent inverted SL/TP orders
200
+ if (defaultSide === 'Buy') {
201
+ if (stopLoss >= refPrice) {
202
+ toast(`Stop Loss ($${stopLoss}) harus lebih rendah dari Entry ($${refPrice}) untuk posisi Long.`, 'error');
203
+ return;
204
+ }
205
+ if (takeProfit1 <= refPrice) {
206
+ toast(`Target TP1 ($${takeProfit1}) harus lebih tinggi dari Entry ($${refPrice}) untuk posisi Long.`, 'error');
207
+ return;
208
+ }
209
+ if (takeProfit2 && tp1Percent < 100 && takeProfit2 <= takeProfit1) {
210
+ toast(`Target TP2 ($${takeProfit2}) harus lebih tinggi dari TP1 ($${takeProfit1}).`, 'error');
211
+ return;
212
+ }
213
+ } else {
214
+ if (stopLoss <= refPrice) {
215
+ toast(`Stop Loss ($${stopLoss}) harus lebih tinggi dari Entry ($${refPrice}) untuk posisi Short.`, 'error');
216
+ return;
217
+ }
218
+ if (takeProfit1 >= refPrice) {
219
+ toast(`Target TP1 ($${takeProfit1}) harus lebih rendah dari Entry ($${refPrice}) untuk posisi Short.`, 'error');
220
+ return;
221
+ }
222
+ if (takeProfit2 && tp1Percent < 100 && takeProfit2 >= takeProfit1) {
223
+ toast(`Target TP2 ($${takeProfit2}) harus lebih rendah dari TP1 ($${takeProfit1}).`, 'error');
224
+ return;
225
+ }
226
+ }
227
+
228
  setIsSubmitting(true);
229
  try {
230
  const res = await executionApi.executeOrder({
tests/test_execution.py CHANGED
@@ -16,6 +16,11 @@ from engine.execution.bybit_executor import BybitExecutor
16
  client = TestClient(app)
17
 
18
 
 
 
 
 
 
19
  def test_bybit_signature_generation():
20
  """Verify HMAC-SHA256 signature algorithm against expected hash."""
21
  executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
@@ -99,6 +104,79 @@ async def test_bybit_execute_split_tp_logic():
99
  await executor.close()
100
 
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  def test_execution_settings_endpoint():
103
  """Verify /api/execution/bybit/settings endpoint returns valid JSON."""
104
  resp = client.get("/api/execution/bybit/settings")
 
16
  client = TestClient(app)
17
 
18
 
19
+ @pytest.fixture
20
+ def anyio_backend():
21
+ return 'asyncio'
22
+
23
+
24
  def test_bybit_signature_generation():
25
  """Verify HMAC-SHA256 signature algorithm against expected hash."""
26
  executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
 
104
  await executor.close()
105
 
106
 
107
+ @pytest.mark.anyio
108
+ async def test_bybit_directional_validation_and_tp2_merge():
109
+ """Verify that inverted SL/TP are caught and small TP2 merge works."""
110
+ executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
111
+
112
+ with patch.object(executor, "get_instrument_info", new_callable=AsyncMock) as mock_info, \
113
+ patch.object(executor, "set_leverage", new_callable=AsyncMock) as mock_lev, \
114
+ patch.object(executor, "_request", new_callable=AsyncMock) as mock_req:
115
+
116
+ mock_info.return_value = {
117
+ "symbol": "BTCUSDT",
118
+ "base_coin": "BTC",
119
+ "quote_coin": "USDT",
120
+ "qty_step": 0.001,
121
+ "min_order_qty": 0.001,
122
+ "max_order_qty": 100.0,
123
+ "tick_size": 0.1,
124
+ "min_price": 0.1,
125
+ "max_price": 1000000.0,
126
+ }
127
+ mock_lev.return_value = True
128
+ mock_req.return_value = {"retCode": 0, "result": {"orderId": "mock_btc_123"}}
129
+
130
+ # 1. Inverted Long SL (SL > entry) must raise ValueError
131
+ with pytest.raises(ValueError, match="harus lebih rendah dari harga Entry"):
132
+ await executor.execute_trade_setup(
133
+ symbol="BTCUSDT",
134
+ side="Buy",
135
+ order_type="Market",
136
+ margin_usd=100.0,
137
+ leverage=2,
138
+ stop_loss=65000.0, # Invalid: above entry 60000.0
139
+ take_profit_1=70000.0,
140
+ mark_price=60000.0,
141
+ )
142
+
143
+ # 2. Inverted Short SL (SL < entry) must raise ValueError
144
+ with pytest.raises(ValueError, match="harus lebih tinggi dari harga Entry"):
145
+ await executor.execute_trade_setup(
146
+ symbol="BTCUSDT",
147
+ side="Sell",
148
+ order_type="Market",
149
+ margin_usd=100.0,
150
+ leverage=2,
151
+ stop_loss=55000.0, # Invalid: below entry 60000.0
152
+ take_profit_1=50000.0,
153
+ mark_price=60000.0,
154
+ )
155
+
156
+ # 3. TP2 merge when remaining qty is below min_order_qty
157
+ # Margin 30, Lev 2 = 60 USD / 60000 = 0.001 BTC (exactly min_order_qty)
158
+ # 50% split would be 0.0005 BTC (< 0.001 min_qty), so 100% must be merged to TP1!
159
+ res_merge = await executor.execute_trade_setup(
160
+ symbol="BTCUSDT",
161
+ side="Buy",
162
+ order_type="Market",
163
+ margin_usd=30.0,
164
+ leverage=2,
165
+ stop_loss=58000.0,
166
+ take_profit_1=65000.0,
167
+ take_profit_2=70000.0,
168
+ tp1_percent=50.0,
169
+ mark_price=60000.0,
170
+ )
171
+ assert res_merge["success"] is True
172
+ assert len(res_merge["tp_orders"]) == 1
173
+ assert res_merge["tp_orders"][0]["tp_level"] == "TP1"
174
+ assert res_merge["tp_orders"][0]["qty"] == 0.001
175
+ assert res_merge["tp_orders"][0]["percent"] == 100.0
176
+
177
+ await executor.close()
178
+
179
+
180
  def test_execution_settings_endpoint():
181
  """Verify /api/execution/bybit/settings endpoint returns valid JSON."""
182
  resp = client.get("/api/execution/bybit/settings")