File size: 23,008 Bytes
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ed22f
1db0bad
30ed22f
1db0bad
 
 
 
30ed22f
 
1db0bad
 
 
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
from dotenv import load_dotenv
load_dotenv()

import os
import json
import hashlib
import hmac
import time
import requests
import pandas as pd
import numpy as np
from flask import Flask, jsonify, send_file, request, send_from_directory
from flask_cors import CORS

from datetime import datetime, timedelta
from modules.telegram_alert import alert_on_buy_signals
from modules.stats import log_admin_stat

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

# Share the login session with subdomains (e.g. scan.blindmonkeys.org) so
# tools hosted there can recognize logged-in admins. Only widen the cookie
# domain when the site is reached via a blindmonkeys.org host; on other
# hosts (e.g. the raw run.app URL) keep the default host-only cookie.
@app.before_request
def _session_cookie_domain():
    host = (request.host or "").split(":")[0].lower()
    if host == "blindmonkeys.org" or host.endswith(".blindmonkeys.org"):
        app.config["SESSION_COOKIE_DOMAIN"] = ".blindmonkeys.org"
    else:
        app.config["SESSION_COOKIE_DOMAIN"] = None

# ---------- Configuration ----------
JOURNAL_FILE = 'trade_journal.csv'
BINGX_API_KEY = os.environ.get('BINGX_API_KEY')
BINGX_API_SECRET = os.environ.get('BINGX_API_SECRET')

# ---------- Coin List ----------
COINS = [
    "bitcoin", "ethereum", "solana", "cardano", "ripple",
    "polkadot", "chainlink", "litecoin", "bitcoin-cash", "stellar",
    "dogecoin", "matic-network", "uniswap", "aave", "cosmos",
    "algorand", "avalanche-2", "vechain", "filecoin", "theta-token",
    "ethereum-classic", "near", "monero", "tezos", "eos",
    "quant-network", "hedera-hashgraph", "elrond-egld", "internet-computer",
    "the-graph", "decentraland", "sandbox", "axie-infinity", "enjin-coin",
    "basic-attention-token", "zilliqa", "theta-fuel", "harmony",
    "icon", "ontology", "nano", "digibyte", "siacoin",
    "qtum", "waves", "ardor", "verge", "bytecoin",
    "shiba-inu", "floki", "bonk"
]

# ---------- Journal Functions ----------
def init_journal():
    if not os.path.isfile(JOURNAL_FILE):
        with open(JOURNAL_FILE, 'w') as f:
            f.write('symbol,entry_price,exit_price,quantity,entry_date,exit_date,pnl,status\n')

# ---------- Market Data Functions ----------
def get_market_data():
    """Fetch real crypto prices from CoinGecko API"""
    try:
        url = "https://api.coingecko.com/api/v3/simple/price"
        params = {
            "ids": "bitcoin,ethereum,solana,cardano,ripple",
            "vs_currencies": "usd"
        }
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        return {
            "BTC": data.get("bitcoin", {}).get("usd", 0),
            "ETH": data.get("ethereum", {}).get("usd", 0),
            "SOL": data.get("solana", {}).get("usd", 0),
            "ADA": data.get("cardano", {}).get("usd", 0),
            "XRP": data.get("ripple", {}).get("usd", 0),
            "timestamp": datetime.now().isoformat()
        }
    except Exception as e:
        return {
            "BTC": 65000.00,
            "ETH": 3500.00,
            "error": str(e),
            "timestamp": datetime.now().isoformat()
        }

# ---------- Direct BingX API (No external library) ----------
def bingx_request(endpoint, method="GET", params=None, signed=True):
    """Make a direct request to BingX API"""
    base_url = "https://open-api.bingx.com"
    url = f"{base_url}{endpoint}"
    
    headers = {
        "X-BX-APIKEY": BINGX_API_KEY,
        "Content-Type": "application/json"
    }
    
    if signed and BINGX_API_KEY and BINGX_API_SECRET:
        timestamp = str(int(time.time() * 1000))
        signature_string = f"{timestamp}{method}{endpoint}"
        signature = hmac.new(
            BINGX_API_SECRET.encode('utf-8'),
            signature_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        headers["X-BX-TIMESTAMP"] = timestamp
        headers["X-BX-SIGNATURE"] = signature
    
    try:
        response = requests.request(method, url, headers=headers, json=params, timeout=10)
        return response.json()
    except Exception as e:
        return {"error": str(e)}

def get_bingx_balance():
    """Get BingX spot account balance using direct API"""
    try:
        # Construct the correct endpoint
        endpoint = "/openApi/spot/v1/account/balance"
        url = f"https://open-api.bingx.com{endpoint}"
        
        # Generate required parameters
        timestamp = str(int(time.time() * 1000))
        params = {
            "timestamp": timestamp
        }
        
        # Create the signature string
        signature_string = timestamp + endpoint
        signature = hmac.new(
            BINGX_API_SECRET.encode('utf-8'),
            signature_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        params["signature"] = signature
        
        # Prepare headers
        headers = {
            "X-BX-APIKEY": BINGX_API_KEY,
        }
        
        # Make the request
        response = requests.get(url, headers=headers, params=params, timeout=10)
        
        # Parse the response
        result = response.json()
        
        # Check if the response is successful
        if result.get('code') == 0:
            return result.get('data', {})
        else:
            # Return the full response for debugging
            return {
                "error": "BingX API error",
                "code": result.get('code'),
                "msg": result.get('msg'),
                "full_response": result
            }
            
    except Exception as e:
        return {"error": str(e)}

def get_bingx_assets():
    """Get BingX spot assets using direct API"""
    try:
        endpoint = "/openApi/spot/v1/account/assets"
        url = f"https://open-api.bingx.com{endpoint}"
        
        timestamp = str(int(time.time() * 1000))
        params = {"timestamp": timestamp}
        signature_string = timestamp + endpoint
        signature = hmac.new(
            BINGX_API_SECRET.encode('utf-8'),
            signature_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        params["signature"] = signature
        
        headers = {"X-BX-APIKEY": BINGX_API_KEY}
        response = requests.get(url, headers=headers, params=params, timeout=10)
        result = response.json()
        
        if result.get('code') == 0:
            return result.get('data', {})
        else:
            return {"error": result.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}

def get_bingx_positions():
    """Get BingX swap positions using direct API"""
    try:
        endpoint = "/openApi/swap/v2/position/list"
        url = f"https://open-api.bingx.com{endpoint}"
        
        timestamp = str(int(time.time() * 1000))
        params = {"timestamp": timestamp}
        signature_string = timestamp + endpoint
        signature = hmac.new(
            BINGX_API_SECRET.encode('utf-8'),
            signature_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        params["signature"] = signature
        
        headers = {"X-BX-APIKEY": BINGX_API_KEY}
        response = requests.get(url, headers=headers, params=params, timeout=10)
        result = response.json()
        
        if result.get('code') == 0:
            return result.get('data', {})
        else:
            return {"error": result.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}

def get_bingx_swap_balance():
    """Get BingX swap account balance using direct API"""
    try:
        endpoint = "/openApi/swap/v2/account/balance"
        url = f"https://open-api.bingx.com{endpoint}"
        
        timestamp = str(int(time.time() * 1000))
        params = {"timestamp": timestamp}
        signature_string = timestamp + endpoint
        signature = hmac.new(
            BINGX_API_SECRET.encode('utf-8'),
            signature_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        params["signature"] = signature
        
        headers = {"X-BX-APIKEY": BINGX_API_KEY}
        response = requests.get(url, headers=headers, params=params, timeout=10)
        result = response.json()
        
        if result.get('code') == 0:
            return result.get('data', {})
        else:
            return {"error": result.get('msg', 'Unknown error')}
    except Exception as e:
        return {"error": str(e)}

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

def calculate_portfolio_allocation(balance_data, prices):
    """Calculate portfolio allocation percentages"""
    total_value = 0
    allocations = {}
    
    if balance_data and not balance_data.get('error'):
        # Check if balance_data is a dict with coin keys
        for coin, value in balance_data.items():
            if isinstance(value, dict):
                available = float(value.get('available', 0))
                if available > 0:
                    # Try to get price from the prices dict
                    price = prices.get(coin, 1)
                    usdt_value = available * price
                    allocations[coin] = {
                        "available": available,
                        "price": price,
                        "usdt_value": usdt_value
                    }
                    total_value += usdt_value
    
    if total_value > 0:
        for coin in allocations:
            allocations[coin]["percentage"] = round((allocations[coin]["usdt_value"] / total_value) * 100, 2)
    
    return {
        "total_value": total_value,
        "allocations": allocations
    }

def calculate_hedging_percentage(spot_balance, swap_positions):
    """Calculate hedging percentage based on spot and swap positions"""
    total_spot_value = 0
    total_swap_value = 0
    
    if spot_balance and not spot_balance.get('error'):
        for coin, value in spot_balance.items():
            if isinstance(value, dict):
                total_spot_value += float(value.get('available', 0))
    
    if swap_positions and not swap_positions.get('error'):
        if 'data' in swap_positions:
            for position in swap_positions.get('data', []):
                total_swap_value += float(position.get('positionValue', 0))
    
    if total_spot_value == 0:
        return {"hedge_percentage": 0, "message": "No spot balance to hedge"}
    
    hedge_percentage = (total_swap_value / total_spot_value) * 100
    return {
        "total_spot_value": total_spot_value,
        "total_swap_value": total_swap_value,
        "hedge_percentage": round(hedge_percentage, 2)
    }

# ---------- Scan Functions ----------
def fetch_coin_data(coin_id, days=30):
    """Fetch historical price data for a coin"""
    try:
        url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart"
        params = {
            "vs_currency": "usd",
            "days": days,
            "interval": "daily"
        }
        response = requests.get(url, params=params, timeout=15)
        response.raise_for_status()
        data = response.json()
        if 'prices' in data and len(data['prices']) > 0:
            prices = [p[1] for p in data['prices']]
            return prices
        return None
    except Exception as e:
        print(f"Error fetching {coin_id}: {e}")
        return None

def calculate_zscore(prices):
    """Calculate Z-score for a price series"""
    if not prices or len(prices) < 10:
        return 0
    recent_prices = prices[-30:] if len(prices) >= 30 else prices
    mean = np.mean(recent_prices)
    std = np.std(recent_prices)
    if std == 0:
        return 0
    current_price = prices[-1]
    return (current_price - mean) / std

def calculate_volatility(prices):
    """Calculate volatility (standard deviation of daily returns)"""
    if not prices or len(prices) < 10:
        return 0
    returns = [prices[i] / prices[i-1] - 1 for i in range(1, len(prices))]
    return np.std(returns) * 100

def calculate_momentum(prices):
    """Calculate 7-day momentum"""
    if not prices or len(prices) < 7:
        return 0
    current = prices[-1]
    past = prices[-7]
    if past == 0:
        return 0
    return ((current / past) - 1) * 100

def run_scan(coin_ids, lookback_days=30, limit=10):
    """Run scan on a list of coins"""
    results = []
    total = len(coin_ids)
    progress = 0

    for coin_id in coin_ids:
        progress += 1
        print(f"Scanning {coin_id} ({progress}/{total})...")

        prices = fetch_coin_data(coin_id, lookback_days)
        if not prices or len(prices) < 7:
            continue

        current_price = prices[-1]
        zscore = calculate_zscore(prices)
        volatility = calculate_volatility(prices)
        momentum = calculate_momentum(prices)
        rsi = calculate_rsi(prices, period=14)

        # RSI penalty (same logic as modules/scanner.py)
        rsi_penalty = 0
        if rsi > 70:
            rsi_penalty = (rsi - 70) * 0.5
        elif rsi < 30:
            rsi_penalty = -2.0

        composite_score = -zscore * 1.5 + momentum * 1.0 - volatility * 0.5 - rsi_penalty

        buy_signal = (
            zscore < -1 and
            momentum > 5 and
            volatility < 8 and
            rsi < 70
        )

        results.append({
            "symbol": coin_id.upper(),
            "coin_id": coin_id,
            "price": round(current_price, 4),
            "zscore": round(zscore, 2),
            "volatility": round(volatility, 2),
            "momentum": round(momentum, 2),
            "rsi": rsi,
            "composite_score": round(composite_score, 2),
            "buy_signal": buy_signal
        })

    results.sort(key=lambda x: x["composite_score"], reverse=True)
    return results[:limit]



# ---------- Serve Frontend ----------
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve_frontend(path):
    """Serve the React frontend from the static folder"""
    if path and os.path.exists(os.path.join('static', path)):
        return send_from_directory('static', path)
    return send_from_directory('static', 'index.html')

# ---------- API Routes ----------
@app.route('/api/market-data')
def market_data_api():
    return jsonify(get_market_data())

@app.route('/api/journal')
def get_journal():
    if not os.path.isfile(JOURNAL_FILE):
        init_journal()
    return send_file(JOURNAL_FILE, as_attachment=True)

# ---------- BingX Routes ----------
@app.route('/api/bingx/balance')
def bingx_balance():
    """Get BingX spot account balance"""
    try:
        balance = get_bingx_balance()
        return jsonify(balance)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/assets')
def bingx_assets():
    """Get BingX spot assets"""
    try:
        assets = get_bingx_assets()
        return jsonify(assets)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/positions')
def bingx_positions():
    """Get BingX swap positions"""
    try:
        positions = get_bingx_positions()
        return jsonify(positions)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/swap-balance')
def bingx_swap_balance():
    """Get BingX swap account balance"""
    try:
        balance = get_bingx_swap_balance()
        return jsonify(balance)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/account')
def bingx_account():
    """Get full BingX account overview"""
    try:
        spot_balance = get_bingx_balance()
        swap_balance = get_bingx_swap_balance()
        positions = get_bingx_positions()
        
        return jsonify({
            "spot_balance": spot_balance,
            "swap_balance": swap_balance,
            "positions": positions
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/portfolio')
def bingx_portfolio():
    """Get portfolio allocation percentages"""
    try:
        spot_balance = get_bingx_balance()
        prices = get_market_data()
        portfolio = calculate_portfolio_allocation(spot_balance, prices)
        return jsonify(portfolio)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/hedge')
def bingx_hedge():
    """Get hedging percentage"""
    try:
        spot_balance = get_bingx_balance()
        positions = get_bingx_positions()
        hedge = calculate_hedging_percentage(spot_balance, positions)
        return jsonify(hedge)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/bingx/order', methods=['POST'])
def bingx_order():
    """Place an order on BingX"""
    try:
        data = request.get_json()
        symbol = data.get('symbol')
        side = data.get('side')
        quantity = data.get('quantity')
        order_type = data.get('order_type', 'MARKET')
        price = data.get('price')
        
        if not symbol or not side or not quantity:
            return jsonify({"error": "Missing required fields: symbol, side, quantity"}), 400
        
        result = place_bingx_order(symbol, side, quantity, order_type, price)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ---------- Scan Routes ----------
@app.route('/api/scan', methods=['GET', 'POST'])
def scan_api():
    """Main scan endpoint (20-day lookback, 14-period RSI)."""
    try:
        results = run_scan(COINS, lookback_days=20, limit=10)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

    scan_data = {
        "results": results,
        "total_scanned": len(results),
        "lookback_days": 20,
        "rsi_period": 14,
    }

    try:
        log_admin_stat("scan", len(results))
    except Exception as e:
        print(f"⚠️ admin_stats log failed: {e}")

    alert_on_buy_signals(scan_data)

    return jsonify({
        "status": "success",
        "scan_type": "scan",
        "timestamp": datetime.now().isoformat(),
        "total_scanned": len(results),
        "results": results,
    })

@app.route('/api/short-scan', methods=['GET', 'POST'])
def short_scan_api():
    """Alias for /api/scan — no duplicate Telegram alert."""
    try:
        results = run_scan(COINS, lookback_days=20, limit=10)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

    try:
        log_admin_stat("scan", len(results))
    except Exception as e:
        print(f"⚠️ admin_stats log failed: {e}")

    return jsonify({
        "status": "success",
        "scan_type": "scan",
        "timestamp": datetime.now().isoformat(),
        "total_scanned": len(results),
        "results": results,
    })

@app.route('/api/long-scan', methods=['GET', 'POST'])
def long_scan_api():
    """Long scan (90-day lookback)."""
    try:
        results = run_scan(COINS, lookback_days=90, limit=10)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

    try:
        log_admin_stat("scan", len(results), extra={"scan_type": "long"})
    except Exception as e:
        print(f"⚠️ admin_stats log failed: {e}")

    return jsonify({
        "status": "success",
        "scan_type": "long",
        "timestamp": datetime.now().isoformat(),
        "total_scanned": len(results),
        "results": results,
    })

@app.route('/api/scan/<scan_type>')
def scan_generic_api(scan_type):
    """Generic scan endpoint — short=20d, long=90d."""
    lookback_days = 90 if scan_type == "long" else 20
    try:
        results = run_scan(COINS, lookback_days=lookback_days, limit=10)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

    try:
        log_admin_stat("scan", len(results), extra={"scan_type": scan_type})
    except Exception as e:
        print(f"⚠️ admin_stats log failed: {e}")

    return jsonify({
        "status": "success",
        "scan_type": scan_type,
        "timestamp": datetime.now().isoformat(),
        "total_scanned": len(results),
        "results": results,
    })

@app.route('/api/cron/hourly-scan', methods=['GET', 'POST'])
def cron_hourly_scan():
    """Hourly cron trigger — secret-protected."""
    secret = request.headers.get("X-Cron-Secret") or request.args.get("secret")
    expected = os.environ.get("CRON_SECRET", "")
    if not expected or secret != expected:
        return jsonify({"error": "unauthorized"}), 401

    try:
        results = run_scan(COINS, lookback_days=20, limit=10)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

    scan_data = {
        "results": results,
        "total_scanned": len(results),
        "lookback_days": 20,
        "rsi_period": 14,
    }

    try:
        log_admin_stat("scan", len(results), extra={"trigger": "cron"})
    except Exception as e:
        print(f"⚠️ admin_stats log failed: {e}")

    alert_on_buy_signals(scan_data)

    return jsonify({
        "ok": True,
        "buy_signals": sum(1 for r in results if r.get("buy_signal")),
        "scanned": len(results),
    })

@app.route('/api/bingx/debug')
def bingx_debug():
    """Debug BingX API response"""
    try:
        endpoint = "/openApi/spot/v1/account/balance"
        url = f"https://open-api.bingx.com{endpoint}"
        
        timestamp = str(int(time.time() * 1000))
        params = {"timestamp": timestamp}
        signature_string = timestamp + endpoint
        signature = hmac.new(
            BINGX_API_SECRET.encode('utf-8'),
            signature_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        params["signature"] = signature
        
        headers = {"X-BX-APIKEY": BINGX_API_KEY}
        response = requests.get(url, headers=headers, params=params, timeout=10)
        
        # Return the RAW response for debugging
        return jsonify({
            "status_code": response.status_code,
            "headers": dict(response.headers),
            "raw_response": response.text,
            "parsed_response": response.json() if response.text else None
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ---------- Run Server ----------
if __name__ == '__main__':
    init_journal()
    port = int(os.environ.get('PORT', 8080))
    app.run(host='0.0.0.0', port=port)