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"}