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70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import hashlib
import hmac
import time
import requests
from datetime import datetime
from config import BINGX_API_KEY, BINGX_API_SECRET, BINGX_BASE_URL


def bingx_request(endpoint, method="GET", params=None):
    """Make a direct request to BingX API with correct signature"""
    all_params = params.copy() if params else {}
    all_params["timestamp"] = str(int(time.time() * 1000))

    sorted_params = sorted(all_params.items())
    query_string = "&".join([f"{k}={v}" for k, v in sorted_params])

    signature = hmac.new(
        BINGX_API_SECRET.encode('utf-8'),
        query_string.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

    signed_body = f"{query_string}&signature={signature}"

    print(f"[{method}] {endpoint}")
    print(f"Signing string: {query_string}")

    headers = {
        "X-BX-APIKEY": BINGX_API_KEY,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    try:
        if method == "GET":
            full_url = f"{BINGX_BASE_URL}{endpoint}?{signed_body}"
            response = requests.get(full_url, headers=headers, timeout=10)
        else:
            full_url = f"{BINGX_BASE_URL}{endpoint}"
            response = requests.post(full_url, headers=headers, data=signed_body, timeout=10)

        print(f"Response: {response.text[:300]}")
        return response.json()
    except Exception as e:
        print(f"Exception: {e}")
        return {"error": str(e)}


def get_bingx_balance():
    try:
        response = bingx_request("/openApi/spot/v1/account/balance")
        if response and response.get('code') == 0:
            return response.get('data', {})
        return {"error": response.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}


def get_bingx_assets():
    try:
        response = bingx_request("/openApi/spot/v1/account/assets")
        if response and response.get('code') == 0:
            return response.get('data', {})
        return {"error": response.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}


def get_bingx_positions():
    try:
        response = bingx_request("/openApi/swap/v2/user/positions")
        if response and response.get('code') == 0:
            return response.get('data', {})
        return {"error": response.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}


def get_bingx_swap_balance():
    try:
        response = bingx_request("/openApi/swap/v3/user/balance")
        if response and response.get('code') == 0:
            return response.get('data', {})
        return {"error": response.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}


def place_bingx_order(symbol, side, quantity, order_type="MARKET", price=None):
    try:
        params = {"symbol": symbol, "side": side, "type": order_type, "quantity": quantity}
        if price and order_type == "LIMIT":
            params["price"] = price
        return bingx_request("/openApi/swap/v2/trade/order", method="POST", params=params)
    except Exception as e:
        return {"error": str(e)}


def get_spot_symbol(coin_id):
    from modules.market_data import _map_to_binance
    from modules.coin_registry import get_coin_symbols
    symbols_map = get_coin_symbols()
    coin_symbol = symbols_map.get(coin_id)
    binance_symbol = _map_to_binance(coin_id, coin_symbol)
    if not binance_symbol:
        return None
    if binance_symbol.endswith("USDT"):
        base = binance_symbol[:-4]
        return f"{base}-USDT"
    return None


def get_spot_price(symbol):
    try:
        url = "https://api.bingx.com/openApi/spot/v1/ticker/price"
        response = requests.get(url, params={"symbol": symbol}, timeout=5)
        if response.status_code == 200:
            data = response.json()
            if data.get('code') == 0:
                return float(data['data']['price'])
        return None
    except Exception as e:
        print(f"Error getting price for {symbol}: {e}")
        return None


_bingx_symbols_cache = {"symbols": set(), "last_updated": None}


def get_bingx_available_symbols(force_refresh=False):
    global _bingx_symbols_cache
    if not force_refresh and _bingx_symbols_cache["symbols"] and _bingx_symbols_cache["last_updated"]:
        age = (datetime.now() - _bingx_symbols_cache["last_updated"]).total_seconds()
        if age < 3600:
            return _bingx_symbols_cache["symbols"]
    try:
        url = "https://open-api.bingx.com/openApi/spot/v1/common/symbols"
        response = requests.get(url, timeout=10)
        if response.status_code != 200:
            return _bingx_symbols_cache["symbols"]
        data = response.json()
        if data.get('code') != 0:
            return _bingx_symbols_cache["symbols"]
        symbols = set()
        for s in data.get('data', {}).get('symbols', []):
            if s.get('status') == 1:
                symbols.add(s['symbol'])
        _bingx_symbols_cache["symbols"] = symbols
        _bingx_symbols_cache["last_updated"] = datetime.now()
        print(f"Loaded {len(symbols)} BingX spot symbols")
        return symbols
    except Exception as e:
        print(f"Failed to fetch BingX symbols: {e}")
        return _bingx_symbols_cache["symbols"]


def _bingx_symbol_variants(symbol):
    """Return possible BingX formats for a Binance-style symbol."""
    if not symbol:
        return []
    variants = [symbol]
    if symbol.endswith("USDT"):
        base = symbol[:-4]
        variants.append(base + "-USDT")
        variants.append(base + "_USDT")
    return variants

def is_on_bingx(coin_id):
    symbol = get_spot_symbol(coin_id)
    if not symbol:
        return False
    available = get_bingx_available_symbols()
    for v in _bingx_symbol_variants(symbol):
        if v in available:
            return True
    return False


def place_spot_market_buy(symbol, quote_order_qty):
    params = {
        "symbol": symbol,
        "side": "BUY",
        "type": "MARKET",
        "quoteOrderQty": round(quote_order_qty, 2)
    }
    return bingx_request("/openApi/spot/v1/trade/order", method="POST", params=params)


def place_spot_market_sell(symbol, quantity):
    params = {
        "symbol": symbol,
        "side": "SELL",
        "type": "MARKET",
        "quantity": round(quantity, 8)
    }
    return bingx_request("/openApi/spot/v1/trade/order", method="POST", params=params)


def place_oco_order(symbol, quantity, take_profit_price, stop_loss_price):
    stop_limit_price = stop_loss_price * 0.99
    params = {
        "symbol": symbol,
        "side": "SELL",
        "quantity": round(quantity, 8),
        "price": round(take_profit_price, 8),
        "stopPrice": round(stop_loss_price, 8),
        "stopLimitPrice": round(stop_limit_price, 8),
        "type": "LIMIT_MAKER"
    }
    return bingx_request("/openApi/spot/v1/trade/oco", method="POST", params=params)


def place_tp_sl_separate(symbol, quantity, take_profit_price=None, stop_loss_price=None):
    results = {"take_profit": None, "stop_loss": None}

    if take_profit_price:
        tp_params = {
            "symbol": symbol,
            "side": "SELL",
            "type": "LIMIT",
            "quantity": round(quantity, 8),
            "price": round(take_profit_price, 8),
            "timeInForce": "GTC"
        }
        results["take_profit"] = bingx_request("/openApi/spot/v1/trade/order", method="POST", params=tp_params)

    if stop_loss_price:
        sl_params = {
            "symbol": symbol,
            "side": "SELL",
            "type": "STOP_LOSS_LIMIT",
            "quantity": round(quantity, 8),
            "price": round(stop_loss_price * 0.99, 8),
            "stopPrice": round(stop_loss_price, 8),
            "timeInForce": "GTC"
        }
        results["stop_loss"] = bingx_request("/openApi/spot/v1/trade/order", method="POST", params=sl_params)

    return results


def execute_batch_buy(coin_ids, take_profit_pct=0, stop_loss_pct=0, allocation_pct=100, use_oco=True, save_as_batch=True, use_atr_sizing=False):
    """
    Execute batch buy orders for multiple coins.
    
    Args:
        use_atr_sizing: If True, use ATR-based position sizing instead of equal weight
    """
    from modules.position_tracker import create_batch
    from modules.market_data import get_atr_for_coins

    results = {
        "success": [],
        "failed": [],
        "total_usdt_used": 0,
        "allocation_pct": allocation_pct,
        "sizing_mode": "atr" if use_atr_sizing else "equal"
    }

    MAX_COINS = 10
    if len(coin_ids) > MAX_COINS:
        return {"error": f"Maximum {MAX_COINS} coins allowed. You selected {len(coin_ids)}."}

    if not coin_ids:
        return {"error": "No coins selected"}

    # Get available USDT balance
    balance = get_bingx_balance()
    usdt_available = 0

    if balance and isinstance(balance, dict) and not balance.get('error'):
        for b in balance.get('balances', []):
            if b.get('asset') == 'USDT':
                usdt_available = float(b.get('free', 0))
                break

    if usdt_available <= 0:
        return {"error": "No USDT available", "usdt_available": 0}

    usdt_to_deploy = usdt_available * (allocation_pct / 100)

    # ---------- Compute position weights ----------
    if use_atr_sizing:
        print(f"Fetching ATR for {len(coin_ids)} coins...")
        atr_data = get_atr_for_coins(coin_ids, period=14)

        weights = {}
        total_weight = 0
        atr_used = {}

        for coin_id in coin_ids:
            atr_info = atr_data.get(coin_id.upper())
            if atr_info and atr_info.get('atr_percent', 0) > 0:
                atr_pct = atr_info['atr_percent']
                weight = 1.0 / atr_pct
                weights[coin_id] = weight
                total_weight += weight
                atr_used[coin_id] = atr_info
            else:
                weights[coin_id] = 1.0
                total_weight += 1.0
                atr_used[coin_id] = None

        usdt_per_coin = {}
        for coin_id in coin_ids:
            normalized = weights[coin_id] / total_weight if total_weight > 0 else 1.0 / len(coin_ids)
            usdt_per_coin[coin_id] = usdt_to_deploy * normalized

        results["atr_sizing_details"] = [
            {
                "coin_id": cid,
                "atr_pct": atr_used[cid]['atr_percent'] if atr_used[cid] else None,
                "usdt_allocated": round(usdt_per_coin[cid], 2),
                "weight_pct": round((usdt_per_coin[cid] / usdt_to_deploy) * 100, 2)
            }
            for cid in coin_ids
        ]
    else:
        equal_amount = usdt_to_deploy / len(coin_ids)
        usdt_per_coin = {cid: equal_amount for cid in coin_ids}

    results["usdt_available"] = round(usdt_available, 2)
    results["usdt_to_deploy"] = round(usdt_to_deploy, 2)

    # ---------- Place orders ----------
    for coin_id in coin_ids:
        try:
            symbol = get_spot_symbol(coin_id)
            if not symbol:
                results["failed"].append({"coin_id": coin_id, "error": "No BingX spot symbol found"})
                continue

            amount = usdt_per_coin[coin_id]
            order_result = place_spot_market_buy(symbol, amount)

            if order_result.get('code') == 0:
                order_data = order_result.get('data', {})
                executed_qty = float(order_data.get('executedQty', 0))
                cummulative_quote = float(order_data.get('cummulativeQuoteQty', 0))
                avg_price = cummulative_quote / executed_qty if executed_qty > 0 else 0

                result_entry = {
                    "coin_id": coin_id,
                    "symbol": symbol,
                    "usdt_spent": round(cummulative_quote, 2),
                    "quantity": executed_qty,
                    "avg_price": round(avg_price, 8),
                    "order_id": order_data.get('orderId'),
                    "status": "success"
                }

                if use_atr_sizing and atr_used.get(coin_id):
                    atr_val = atr_used[coin_id]['atr']
                    result_entry["atr"] = atr_val
                    result_entry["atr_stop_loss_price"] = round(avg_price - (2 * atr_val), 8)

                results["success"].append(result_entry)
                results["total_usdt_used"] += cummulative_quote
            else:
                results["failed"].append({
                    "coin_id": coin_id,
                    "symbol": symbol,
                    "error": order_result.get('msg', 'Unknown error'),
                    "code": order_result.get('code')
                })
        except Exception as e:
            results["failed"].append({"coin_id": coin_id, "error": str(e)})

    results["total_usdt_used"] = round(results["total_usdt_used"], 2)

    # Save as a portfolio batch
    if save_as_batch and results["success"] and (take_profit_pct > 0 or stop_loss_pct > 0):
        try:
            batch = create_batch(
                batch_name=f"Scan {datetime.now().strftime('%Y-%m-%d %H:%M')}",
                coins=results["success"],
                take_profit_pct=take_profit_pct,
                stop_loss_pct=stop_loss_pct
            )
            results["batch_id"] = batch["id"]
            results["batch_name"] = batch["name"]
        except Exception as e:
            print(f"Failed to save batch: {e}")

    return results


def close_batch_positions(batch_id):
    """Sell all coins in a batch at market price"""
    from modules.position_tracker import get_batch, close_batch

    batch = get_batch(batch_id)
    if not batch:
        return {"error": "Batch not found"}

    results = {"success": [], "failed": [], "total_usdt_received": 0}

    for coin in batch["coins"]:
        symbol = coin["symbol"]
        quantity = coin["quantity"]

        result = place_spot_market_sell(symbol, quantity)

        if result.get('code') == 0:
            order_data = result.get('data', {})
            cummulative_quote = float(order_data.get('cummulativeQuoteQty', 0))
            results["success"].append({
                "symbol": symbol,
                "quantity": quantity,
                "usdt_received": round(cummulative_quote, 2),
                "order_id": order_data.get('orderId')
            })
            results["total_usdt_received"] += cummulative_quote
        else:
            results["failed"].append({
                "symbol": symbol,
                "error": result.get('msg', 'Unknown error'),
                "code": result.get('code')
            })

    results["total_usdt_received"] = round(results["total_usdt_received"], 2)

    close_batch(
        batch_id=batch_id,
        reason=batch.get("pending_trigger") or "manual",
        final_value=results["total_usdt_received"],
        results=results
    )

    return results


def cancel_batch_orders(batch_id):
    """Cancel any open TP/SL orders for a batch (placeholder)"""
    return {"status": "ok", "message": "No individual orders to cancel"}