-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_app.py
More file actions
2305 lines (1870 loc) · 86.5 KB
/
Copy pathweb_app.py
File metadata and controls
2305 lines (1870 loc) · 86.5 KB
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_socketio import SocketIO, emit
import requests
import time
from functools import lru_cache
import os
import threading
import json
import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime, timedelta
import base64
import hmac
import hashlib
# Cryptography için import
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
CRYPTOGRAPHY_AVAILABLE = True
# Terminal encoding sorunlarını önlemek için
import sys
if sys.stdout.encoding != 'utf-8':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
# Config imports
from config import BINANCE_BASE_URL
print("✅ Cryptography kütüphanesi yüklendi")
# ⚡ GZIP Compression (optional - graceful fallback)
try:
from flask_compress import Compress # type: ignore
COMPRESS_AVAILABLE = True
except ImportError:
COMPRESS_AVAILABLE = False
print("⚠️ Flask-Compress not installed. Install with: pip install Flask-Compress==1.14")
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
# ⚡ GZIP Compression - Response boyutu %60-70 azalır
if COMPRESS_AVAILABLE:
compress = Compress()
compress.init_app(app)
app.config['COMPRESS_MIMETYPES'] = ['text/html', 'text/css', 'text/javascript', 'application/json']
app.config['COMPRESS_LEVEL'] = 6 # 1-9 arası (6 = hız/boyut dengesi)
app.config['COMPRESS_MIN_SIZE'] = 500 # 500 byte'dan küçük dosyaları sıkıştırma
print("[OK] GZIP Compression enabled!")
else:
print("[INFO] Running without compression (install Flask-Compress for better performance)")
# Disable bot-related endpoints centrally (return 410 Gone)
from flask import request
BOT_BLOCKED_PREFIXES = (
'/api/signal_bot',
)
BOT_BLOCKED_ROUTES = {
'/bot',
'/api/init',
'/api/set_demo_mode',
'/api/status',
'/api/add_candle',
'/api/get_last_signal',
'/api/apply_signal_to_bot',
'/api/config',
'/api/bot/config',
'/api/bot/start',
'/api/bot/stop',
'/api/balance',
'/api/balance/debug',
'/api/close_position',
}
@app.before_request
def _disable_bot_routes():
path = request.path or ''
if path in BOT_BLOCKED_ROUTES or any(path.startswith(p) for p in BOT_BLOCKED_PREFIXES):
return jsonify({'error': 'Bot features removed'}), 410
# Global semboller önbelleği
_symbols_cache = {
'data': [],
'timestamp': 0
}
CACHE_DURATION = 300 # 5 dakika
# Sembol minimum notional cache
_min_notional_cache = {
'data': {}, # {symbol: min_notional}
'timestamp': 0
}
MIN_NOTIONAL_CACHE_DURATION = 3600 # 1 saat (daha az değişir)
# Cache için timestamp tracking
_symbols_cache_time = None
_symbols_cache_lock = threading.Lock()
# Rate Limiting ve API Kontrolü
API_RATE_LIMITS = {
'requests_per_minute': 1200, # Binance API limiti
'requests_per_second': 10, # Güvenli limit
'weight_per_minute': 6000, # Weight limiti
'kline_weight': 1, # Kline çağrısı weight'i
'ticker_weight': 1, # Ticker çağrısı weight'i
'order_weight': 1 # Emir çağrısı weight'i
}
# API çağrı takibi
api_call_history = []
api_weight_history = []
api_lock = threading.Lock()
def check_rate_limit(weight=1):
"""Rate limit kontrolü - Binance API limitlerini aşmamak için"""
with api_lock:
current_time = time.time()
# Son 1 dakikadaki çağrıları temizle
api_call_history[:] = [call_time for call_time in api_call_history if current_time - call_time < 60]
api_weight_history[:] = [w for w in api_weight_history if current_time - w['time'] < 60]
# Limitleri kontrol et
if len(api_call_history) >= API_RATE_LIMITS['requests_per_minute']:
sleep_time = 60 - (current_time - api_call_history[0])
if sleep_time > 0:
print(f"[RATE LIMIT] {sleep_time:.2f} saniye bekleniyor...")
time.sleep(sleep_time)
# Weight limitini kontrol et
total_weight = sum(w['weight'] for w in api_weight_history)
if total_weight + weight > API_RATE_LIMITS['weight_per_minute']:
sleep_time = 60 - (current_time - api_weight_history[0]['time'])
if sleep_time > 0:
print(f"[WEIGHT LIMIT] {sleep_time:.2f} saniye bekleniyor...")
time.sleep(sleep_time)
# Çağrıyı kaydet
api_call_history.append(current_time)
api_weight_history.append({'time': current_time, 'weight': weight})
# 1 saniye içinde çok fazla çağrı kontrolü
recent_calls = [call_time for call_time in api_call_history if current_time - call_time < 1]
if len(recent_calls) > API_RATE_LIMITS['requests_per_second']:
time.sleep(1 - (current_time - recent_calls[0]))
def sign_request_hmac(params, api_secret):
"""HMAC-SHA256 ile request imzalama (eski yöntem)"""
try:
from urllib.parse import urlencode
# Query string oluştur
query_string = urlencode(params)
# HMAC-SHA256 ile imzala
signature = hmac.new(
api_secret.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
return signature
except Exception as e:
print(f"❌ HMAC signing error: {e}")
return None
def sign_request_rsa(params, private_key_pem):
"""RSA Private Key ile request imzalama (yeni yöntem)"""
try:
from urllib.parse import urlencode
import base64
# Query string oluştur
query_string = urlencode(params)
# PEM key'in geçerli olup olmadığını kontrol et
if not private_key_pem or len(private_key_pem.strip()) == 0:
print("❌ PEM key boş!")
return None
if '-----BEGIN' not in private_key_pem or '-----END' not in private_key_pem:
print("❌ Geçersiz PEM formatı! BEGIN ve END tag'leri bulunamadı.")
return None
# PEM formatındaki private key'i yükle
try:
# Önce standart PKCS#8 formatını dene (-----BEGIN PRIVATE KEY-----)
private_key = serialization.load_pem_private_key(
private_key_pem.encode('utf-8'),
password=None,
backend=default_backend()
)
print("✅ PEM key yüklendi (PKCS#8 veya PKCS#1 format)")
except Exception as key_error:
print(f"❌ PEM key yüklenemedi: {key_error}")
print("📌 PEM dosyanızın formatını kontrol edin.")
print(f"📌 PEM başlangıcı: {private_key_pem[:50]}...")
return None
# RSA ile imzala (PKCS1v15 padding kullanarak)
# type: ignore - IDE type checker cryptography kütüphanesini tam tanımıyor
signature_bytes = private_key.sign( # type: ignore
query_string.encode('utf-8'), # type: ignore
padding.PKCS1v15(), # type: ignore
hashes.SHA256() # type: ignore
)
# Base64 encode et
signature = base64.b64encode(signature_bytes).decode('utf-8')
print(f"✅ RSA imzalama başarılı (signature length: {len(signature)})")
return signature
except Exception as e:
print(f"❌ RSA signing error: {e}")
import traceback
traceback.print_exc()
return None
def sign_request(params, api_secret):
"""Akıllı imzalama - RSA veya HMAC otomatik seçim"""
# Eğer secret key PEM formatında ise RSA kullan
if '-----BEGIN' in api_secret:
return sign_request_rsa(params, api_secret)
else:
return sign_request_hmac(params, api_secret)
def get_account_balance():
"""Hesap bakiyesini al - HMAC-SHA256 authentication"""
try:
import time
from urllib.parse import urlencode
from config import BINANCE_API_KEY, BINANCE_API_SECRET, BINANCE_BASE_URL
# API Key ve Secret kontrolü
if not BINANCE_API_KEY:
return {'success': False, 'error': 'API Key bulunamadı! Config dosyasını kontrol edin.'}
if not BINANCE_API_SECRET:
return {'success': False, 'error': 'API Secret bulunamadı! Config dosyasını kontrol edin.'}
print(f"[INFO] API Key: {BINANCE_API_KEY[:10]}...")
print(f"[INFO] Secret Key Format: {'PEM (RSA)' if '-----BEGIN' in BINANCE_API_SECRET else 'HMAC'}")
url = f"{BINANCE_BASE_URL}/api/v3/account"
# Binance sunucu saatini al
server_time_response = requests.get(f"{BINANCE_BASE_URL}/api/v3/time", timeout=5)
if server_time_response.status_code == 200:
server_time = server_time_response.json()['serverTime']
timestamp = server_time
else:
# Fallback: yerel saat
timestamp = int(time.time() * 1000)
params = {
'timestamp': timestamp,
'recvWindow': 10000 # 10 saniye tolerans
}
# İmzalama (RSA veya HMAC otomatik seçim)
print(f"[INFO] İmzalama başlatılıyor...")
signature = sign_request(params, BINANCE_API_SECRET)
if not signature:
return {'success': False, 'error': 'İmzalama başarısız! PEM key formatını ve cryptography kütüphanesini kontrol edin. Terminal loglarına bakın.'}
params['signature'] = signature
headers = {
'X-MBX-APIKEY': BINANCE_API_KEY,
'Content-Type': 'application/x-www-form-urlencoded'
}
print(f"[INFO] Binance API'ye istek gönderiliyor...")
response = requests.get(url, params=params, headers=headers, timeout=10)
if response.status_code == 200:
account_data = response.json()
balances = {}
for balance in account_data.get('balances', []):
free_amount = float(balance['free'])
locked_amount = float(balance['locked'])
# Sadece bakiyesi olan varlıkları ekle
if free_amount > 0 or locked_amount > 0:
balances[balance['asset']] = {
'free': free_amount,
'locked': locked_amount
}
print(f"[SUCCESS] Bakiye başarıyla alındı: {len(balances)} varlık bulundu")
return {'success': True, 'balances': balances}
else:
error_msg = f"HTTP {response.status_code}"
try:
error_data = response.json()
if 'msg' in error_data:
error_msg = f"{error_msg} - {error_data['msg']}"
except:
pass
print(f"[ERROR] API Hatası: {error_msg}")
return {'success': False, 'error': f"API Error: {error_msg}"}
except Exception as e:
print(f"[ERROR] get_account_balance exception: {e}")
import traceback
traceback.print_exc()
return {'success': False, 'error': str(e)}
def get_current_price(symbol):
"""Güncel fiyatı al"""
try:
from config import BINANCE_BASE_URL
url = f"{BINANCE_BASE_URL}/api/v3/ticker/price"
params = {'symbol': symbol}
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
return {'success': True, 'price': float(data['price'])}
else:
return {'success': False, 'error': f"API Error: {response.status_code}"}
except Exception as e:
return {'success': False, 'error': str(e)}
def get_symbol_min_notional(symbol):
"""
Binance API'den sembol için minimum notional değerini al
MIN_NOTIONAL: Alış/satış için gereken minimum işlem değeri (fiyat * miktar)
Her coin için farklıdır:
- BTCUSDT: ~10 USDT
- DOGEUSDT: ~5 USDT
- BNBUSDT: ~20 USDT
Returns:
float: Minimum notional değer (USDT cinsinden)
"""
global _min_notional_cache
try:
# Cache kontrolü
current_time = time.time()
if (_min_notional_cache['timestamp'] > 0 and
current_time - _min_notional_cache['timestamp'] < MIN_NOTIONAL_CACHE_DURATION and
symbol in _min_notional_cache['data']):
print(f"[CACHE HIT] {symbol} min notional: {_min_notional_cache['data'][symbol]} USDT")
return _min_notional_cache['data'][symbol]
# API'den al
from config import BINANCE_BASE_URL
url = f"{BINANCE_BASE_URL}/api/v3/exchangeInfo"
params = {'symbol': symbol}
print(f"[API] {symbol} için exchange info çekiliyor...")
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
if 'symbols' in data and len(data['symbols']) > 0:
symbol_info = data['symbols'][0]
# MIN_NOTIONAL filtresini bul
for filter_item in symbol_info.get('filters', []):
if filter_item.get('filterType') == 'MIN_NOTIONAL':
min_notional = float(filter_item.get('minNotional', 10.0))
# Cache'e kaydet
_min_notional_cache['data'][symbol] = min_notional
_min_notional_cache['timestamp'] = current_time
print(f"[API SUCCESS] {symbol} min notional: {min_notional} USDT")
return min_notional
# MIN_NOTIONAL bulunamazsa NOTIONAL filtresi kontrol et
for filter_item in symbol_info.get('filters', []):
if filter_item.get('filterType') == 'NOTIONAL':
min_notional = float(filter_item.get('minNotional', 10.0))
# Cache'e kaydet
_min_notional_cache['data'][symbol] = min_notional
_min_notional_cache['timestamp'] = current_time
print(f"[API SUCCESS] {symbol} notional: {min_notional} USDT")
return min_notional
print(f"[WARNING] {symbol} için MIN_NOTIONAL/NOTIONAL filtresi bulunamadı, varsayılan: 10.0 USDT")
return 10.0
print(f"[ERROR] Exchange info API hatası: {response.status_code}")
return 10.0 # Fallback
except Exception as e:
print(f"[ERROR] Min notional alma hatası: {e}")
return 10.0 # Fallback
def get_symbol_lot_size(symbol):
"""
Binance API'den sembol için LOT_SIZE bilgisini al
LOT_SIZE: Quantity için adım büyüklüğü (stepSize)
Quantity bu stepSize'ın katları olmalı
Örnek:
- AVAX stepSize: 0.1 → quantity: 0.1, 0.2, 0.3, ... (0.14286 KABUL EDİLMEZ!)
- BTC stepSize: 0.00001 → quantity: 0.00001, 0.00002, ...
Returns:
dict: {'stepSize': float, 'minQty': float, 'maxQty': float}
"""
try:
from config import BINANCE_BASE_URL
url = f"{BINANCE_BASE_URL}/api/v3/exchangeInfo"
params = {'symbol': symbol}
print(f"[API] {symbol} için LOT_SIZE bilgisi çekiliyor...")
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
if 'symbols' in data and len(data['symbols']) > 0:
symbol_info = data['symbols'][0]
# LOT_SIZE filtresini bul
for filter_item in symbol_info.get('filters', []):
if filter_item.get('filterType') == 'LOT_SIZE':
lot_size_info = {
'stepSize': float(filter_item.get('stepSize', 0.1)),
'minQty': float(filter_item.get('minQty', 0.1)),
'maxQty': float(filter_item.get('maxQty', 9000000.0))
}
print(f"[API SUCCESS] {symbol} LOT_SIZE → stepSize: {lot_size_info['stepSize']}, minQty: {lot_size_info['minQty']}")
return lot_size_info
print(f"[WARNING] {symbol} için LOT_SIZE filtresi bulunamadı, varsayılan kullanılıyor")
return {'stepSize': 0.1, 'minQty': 0.1, 'maxQty': 9000000.0}
print(f"[ERROR] Exchange info API hatası: {response.status_code}")
return {'stepSize': 0.1, 'minQty': 0.1, 'maxQty': 9000000.0}
except Exception as e:
print(f"[ERROR] LOT_SIZE alma hatası: {e}")
return {'stepSize': 0.1, 'minQty': 0.1, 'maxQty': 9000000.0}
def round_to_step_size(quantity, step_size):
"""
Quantity'yi stepSize'a göre yuvarla
Args:
quantity: Yuvarlanacak miktar
step_size: Adım büyüklüğü (örn: 0.1, 0.01, 0.00001)
Returns:
float: Yuvarlanmış miktar
Örnek:
round_to_step_size(0.14286, 0.1) → 0.1
round_to_step_size(0.24286, 0.1) → 0.2
round_to_step_size(0.123456, 0.01) → 0.12
"""
# stepSize'ın ondalık sayısını bul
step_str = f"{step_size:.10f}".rstrip('0')
if '.' in step_str:
decimals = len(step_str.split('.')[1])
else:
decimals = 0
# Quantity'yi stepSize'ın katına yuvarla (aşağı yuvarla)
rounded = (quantity // step_size) * step_size
# Decimals'e göre format
rounded = round(rounded, decimals)
return rounded
def get_all_symbols_min_notional():
"""
Tüm sembollerin minimum notional değerlerini toplu al
Watchlist'teki coinler için optimize edilmiş
Returns:
dict: {symbol: min_notional}
"""
global _min_notional_cache
try:
# Cache kontrolü
current_time = time.time()
if (_min_notional_cache['timestamp'] > 0 and
current_time - _min_notional_cache['timestamp'] < MIN_NOTIONAL_CACHE_DURATION and
len(_min_notional_cache['data']) > 0):
print(f"[CACHE HIT] Min notional cache kullanılıyor ({len(_min_notional_cache['data'])} sembol)")
return _min_notional_cache['data']
# API'den tüm sembolleri al
from config import BINANCE_BASE_URL
url = f"{BINANCE_BASE_URL}/api/v3/exchangeInfo"
print(f"[API] Tüm semboller için exchange info çekiliyor...")
response = requests.get(url, timeout=15)
if response.status_code == 200:
data = response.json()
min_notionals = {}
for symbol_info in data.get('symbols', []):
symbol = symbol_info.get('symbol')
# MIN_NOTIONAL filtresini bul
for filter_item in symbol_info.get('filters', []):
if filter_item.get('filterType') in ['MIN_NOTIONAL', 'NOTIONAL']:
min_notional = float(filter_item.get('minNotional', 10.0))
min_notionals[symbol] = min_notional
break
# Cache'e kaydet
_min_notional_cache['data'] = min_notionals
_min_notional_cache['timestamp'] = current_time
print(f"[API SUCCESS] {len(min_notionals)} sembol için min notional yüklendi")
return min_notionals
print(f"[ERROR] Exchange info API hatası: {response.status_code}")
return {}
except Exception as e:
print(f"[ERROR] Toplu min notional alma hatası: {e}")
return {}
def send_real_order(signal, symbol, amount_usdt, max_retries=3):
"""
Gerçek Binance API ile emir gönder - KUSURSUZ VERSİYON
Args:
signal: 'BUY' veya 'SELL' (STRING)
symbol: Trading pair (örn: BTCUSDT)
amount_usdt: USDT cinsinden miktar
max_retries: Maksimum deneme sayısı
Returns:
dict: Emir sonucu
"""
try:
import time
from urllib.parse import urlencode
# Config'den API keyler
from config import BINANCE_API_KEY, BINANCE_API_SECRET, BINANCE_BASE_URL, MIN_ORDER_AMOUNT_USDT, MAX_ORDER_AMOUNT_USDT, VALID_SYMBOLS
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Validasyon 1: API Key kontrolü
if not BINANCE_API_KEY or not BINANCE_API_SECRET:
return {'success': False, 'error': 'API anahtarları eksik! Config dosyasını kontrol edin.'}
# Validasyon 2: Signal kontrolü (YENİ: STRING)
if signal not in ['BUY', 'SELL']:
return {'success': False, 'error': f'Geçersiz sinyal: {signal}. Sadece "BUY" veya "SELL" olabilir.'}
# Validasyon 3: Amount kontrolü - CANLI MOD İÇİN (Dinamik Minimum)
# Her coin için Binance'den minimum notional değerini al
min_notional = get_symbol_min_notional(symbol)
if amount_usdt < min_notional:
return {'success': False, 'error': f'Emir miktarı çok düşük! {symbol} için Binance minimum: {min_notional} USDT'}
if amount_usdt > MAX_ORDER_AMOUNT_USDT:
return {'success': False, 'error': f'Emir miktarı çok yüksek! Maksimum: {MAX_ORDER_AMOUNT_USDT} USDT'}
# Validasyon 4: SELL için bakiye kontrolü (CANLI MOD)
if signal == 'SELL':
# Gerçek bakiyede coin olup olmadığını kontrol et
balance_result = get_account_balance()
if balance_result['success']:
# Symbol'den base asset çıkar (AVAXUSDT -> AVAX)
base_asset = symbol.replace('USDT', '').replace('BUSD', '').replace('BTC', '').replace('ETH', '')
balances = balance_result.get('balances', {})
if base_asset in balances:
available = balances[base_asset]['free']
if available > 0:
# ✅ Bakiyede coin var, SELL yapılabilir
print(f"[INFO] Gerçek bakiyede {available} {base_asset} bulundu, SELL yapılacak")
else:
return {'success': False, 'error': f'{base_asset} bakiyesi yetersiz! Mevcut: {available}'}
else:
return {'success': False, 'error': f'{base_asset} bakiyenizde yok!'}
else:
# Bakiye kontrol edilemedi
return {'success': False, 'error': 'Bakiye kontrol edilemedi!'}
# Güncel fiyatı al (retry ile)
price_result = None
for attempt in range(max_retries):
price_result = get_current_price(symbol)
if price_result['success']:
break
print(f"[RETRY] Fiyat alma denemesi {attempt + 1}/{max_retries}")
time.sleep(1)
if not price_result or not price_result['success']:
return {'success': False, 'error': f"Fiyat alınamadı: {price_result.get('error') if price_result else 'Timeout'}"}
current_price = price_result['price']
# Emir parametreleri (signal zaten 'BUY' veya 'SELL' string)
side = signal
print(f"[{current_time}] [ORDER] {symbol} için {side} emri hazırlanıyor: {amount_usdt} USDT @ {current_price:.2f}")
# Miktar hesaplama ve bakiye kontrolü (retry ile)
balance_result = None
for attempt in range(max_retries):
balance_result = get_account_balance()
if balance_result['success']:
break
print(f"[RETRY] Bakiye alma denemesi {attempt + 1}/{max_retries}")
time.sleep(1)
if not balance_result or not balance_result['success']:
return {'success': False, 'error': f"Bakiye alınamadı: {balance_result.get('error') if balance_result else 'Timeout'}"}
if signal == 'BUY':
# USDT bakiyesini kontrol et
usdt_balance = balance_result['balances'].get('USDT', {}).get('free', 0)
print(f"[{current_time}] [BALANCE] Mevcut USDT: {usdt_balance:.2f}, Gerekli: {amount_usdt:.2f}")
if usdt_balance < amount_usdt:
balance_msg = f"\n{'='*80}\n"
balance_msg += f"❌ YETERSİZ BAKİYE - BUY EMRİ GÖNDERİLEMEDİ!\n"
balance_msg += f"{'='*80}\n"
balance_msg += f"📅 Tarih : {datetime.now().strftime('%d/%m/%Y')}\n"
balance_msg += f"🕐 Saat : {datetime.now().strftime('%H:%M:%S')}\n"
balance_msg += f"📊 Sinyal : BUY (ALIM)\n"
balance_msg += f"🪙 Coin : {symbol}\n"
balance_msg += f"\n📌 BAKİYE DURUMU:\n"
balance_msg += f" ├─ Mevcut USDT : {usdt_balance:.2f} USDT\n"
balance_msg += f" ├─ Gerekli : {amount_usdt:.2f} USDT\n"
balance_msg += f" ├─ Eksik : {(amount_usdt - usdt_balance):.2f} USDT\n"
balance_msg += f" └─ Mevcut Oran : {(usdt_balance / amount_usdt * 100):.1f}%\n"
balance_msg += f"\n💡 Ne Yapmalı : USDT yükleyin veya işlem miktarını {usdt_balance:.2f} USDT'ye düşürün!\n"
balance_msg += f"{'='*80}\n"
print(balance_msg)
if signal_logger:
signal_logger.error(f"❌ YETERSİZ BAKİYE - BUY | {symbol}")
signal_logger.error(f"Mevcut: {usdt_balance:.2f} USDT | Gerekli: {amount_usdt:.2f} USDT | Eksik: {(amount_usdt - usdt_balance):.2f}")
if error_logger:
error_logger.error(f"YETERSİZ USDT BAKİYESİ: {usdt_balance:.2f} < {amount_usdt:.2f}")
return {
'success': False,
'error': f"Yetersiz USDT bakiyesi! Mevcut: {usdt_balance:.2f} USDT, Gerekli: {amount_usdt:.2f} USDT"
}
# Alınacak miktar = USDT miktarı / fiyat
quantity = amount_usdt / current_price
# ⚠️ BİNANCE LOT_SIZE FİLTRESİNE GÖRE YUVARLA
lot_size_info = get_symbol_lot_size(symbol)
step_size = lot_size_info['stepSize']
min_qty = lot_size_info['minQty']
# Quantity'yi stepSize'a göre yuvarla (aşağı yuvarla)
quantity_original = quantity
quantity = round_to_step_size(quantity, step_size)
print(f"[{current_time}] [LOT_SIZE] Yuvarlanmış: {quantity_original:.8f} → {quantity:.8f} (stepSize: {step_size})")
# Minimum quantity kontrolü
if quantity < min_qty:
return {'success': False, 'error': f'Quantity çok düşük! Minimum: {min_qty} (Hesaplanan: {quantity})'}
print(f"[{current_time}] [ORDER] Alınacak miktar: {quantity} {symbol.replace('USDT', '')}")
else: # SELL
# Base asset bakiyesini kontrol et (örn: AVAX, BTC)
base_asset = symbol.replace('USDT', '').replace('BUSD', '').replace('BTC', '').replace('ETH', '')
base_balance = balance_result['balances'].get(base_asset, {}).get('free', 0)
# Gerçek bakiyeyi kullan
if base_balance <= 0:
return {'success': False, 'error': f'{base_asset} bakiyenizde yok! Mevcut: {base_balance:.6f}'}
# Gerçek bakiyenin tamamını sat
quantity = base_balance
print(f"[{current_time}] [REAL BALANCE] Gerçek bakiyeden satılacak: {quantity:.6f} {base_asset}")
# ⚠️ BİNANCE LOT_SIZE FİLTRESİNE GÖRE YUVARLA
lot_size_info = get_symbol_lot_size(symbol)
step_size = lot_size_info['stepSize']
min_qty = lot_size_info['minQty']
# Quantity'yi stepSize'a göre yuvarla (aşağı yuvarla)
quantity_original = quantity
quantity = round_to_step_size(quantity, step_size)
print(f"[{current_time}] [LOT_SIZE] Yuvarlanmış: {quantity_original:.8f} → {quantity:.8f} (stepSize: {step_size})")
# Minimum quantity kontrolü
if quantity < min_qty:
return {'success': False, 'error': f'{base_asset} miktarı çok düşük! Minimum: {min_qty} (Mevcut: {quantity})'}
print(f"[{current_time}] [BALANCE] Mevcut {base_asset}: {base_balance:.6f}, Satılacak: {quantity:.6f}")
if base_balance < quantity:
balance_msg = f"\n{'='*80}\n"
balance_msg += f"❌ YETERSİZ BAKİYE - SELL EMRİ GÖNDERİLEMEDİ!\n"
balance_msg += f"{'='*80}\n"
balance_msg += f"📅 Tarih : {datetime.now().strftime('%d/%m/%Y')}\n"
balance_msg += f"🕐 Saat : {datetime.now().strftime('%H:%M:%S')}\n"
balance_msg += f"📊 Sinyal : SELL (SATIM)\n"
balance_msg += f"🪙 Coin : {symbol}\n"
balance_msg += f"\n📌 BAKİYE DURUMU:\n"
balance_msg += f" ├─ Mevcut {base_asset:4s} : {base_balance:.6f}\n"
balance_msg += f" ├─ Gerekli : {quantity:.6f}\n"
balance_msg += f" ├─ Eksik : {(quantity - base_balance):.6f}\n"
balance_msg += f" └─ Mevcut Oran : {(base_balance / quantity * 100):.1f}%\n"
balance_msg += f"\n💡 Ne Yapmalı : {base_asset} bakiyenizi kontrol edin veya pozisyon miktarını düşürün!\n"
balance_msg += f"{'='*80}\n"
print(balance_msg)
if signal_logger:
signal_logger.error(f"❌ YETERSİZ BAKİYE - SELL | {symbol}")
signal_logger.error(f"Mevcut: {base_balance:.6f} {base_asset} | Gerekli: {quantity:.6f} | Eksik: {(quantity - base_balance):.6f}")
if error_logger:
error_logger.error(f"YETERSİZ {base_asset} BAKİYESİ: {base_balance:.6f} < {quantity:.6f}")
return {
'success': False,
'error': f"Yetersiz {base_asset} bakiyesi! Mevcut: {base_balance:.6f}, Gerekli: {quantity:.6f}"
}
# Binance Spot API endpoint
url = f"{BINANCE_BASE_URL}/api/v3/order"
# Retry loop for order placement
last_error = None
response = None
for attempt in range(max_retries):
try:
# Binance sunucu saatini al
server_time_response = requests.get(f"{BINANCE_BASE_URL}/api/v3/time", timeout=5)
if server_time_response.status_code == 200:
server_time = server_time_response.json()['serverTime']
timestamp = server_time
else:
# Fallback: yerel saat
timestamp = int(time.time() * 1000)
# Query parametreleri
if side == "BUY":
# BUY için quoteOrderQty kullan (USDT cinsinden)
params = {
'symbol': symbol,
'side': side,
'type': 'MARKET',
'quoteOrderQty': f"{amount_usdt:.2f}", # USDT cinsinden miktar
'timestamp': timestamp,
'recvWindow': 10000 # 10 saniye tolerans
}
else:
# SELL için quantity kullan (base asset cinsinden)
# Binance precision kurallarına uygun yuvarlama (trailing zeros kaldır)
quantity_str = f"{quantity:.8f}".rstrip('0').rstrip('.')
params = {
'symbol': symbol,
'side': side,
'type': 'MARKET',
'quantity': quantity_str, # Base asset cinsinden miktar (AVAX, BTC, vs.)
'timestamp': timestamp,
'recvWindow': 10000 # 10 saniye tolerans
}
print(f"[{current_time}] [ORDER] SELL emri: {quantity_str} {base_asset} (Gerçek bakiyeden)")
# İmzalama (RSA veya HMAC otomatik seçim)
signature = sign_request(params, BINANCE_API_SECRET)
if not signature:
last_error = 'Request signing failed'
print(f"[RETRY] İmzalama hatası, deneme {attempt + 1}/{max_retries}")
time.sleep(1)
continue
params['signature'] = signature
# Headers
headers = {
'X-MBX-APIKEY': BINANCE_API_KEY,
'Content-Type': 'application/x-www-form-urlencoded'
}
print(f"[{current_time}] [ORDER] Binance API'ye emir gönderiliyor... (Deneme {attempt + 1}/{max_retries})")
# POST request
response = requests.post(url, data=params, headers=headers, timeout=15)
# Başarılı response
if response.status_code == 200:
break
else:
last_error = f"HTTP {response.status_code}: {response.text}"
print(f"[RETRY] API hatası, deneme {attempt + 1}/{max_retries}: {last_error}")
time.sleep(2 ** attempt) # Exponential backoff
except requests.exceptions.Timeout:
last_error = "Request timeout"
print(f"[RETRY] Timeout, deneme {attempt + 1}/{max_retries}")
time.sleep(2 ** attempt)
except Exception as e:
last_error = str(e)
print(f"[RETRY] Hata: {last_error}, deneme {attempt + 1}/{max_retries}")
time.sleep(2 ** attempt)
# Tüm denemeler başarısız oldu
if not response or response.status_code != 200:
error_msg = f"Emir gönderilemedi! Son hata: {last_error}"
print(f"[{current_time}] [ORDER FAILED] {error_msg}")
if signal_logger:
signal_logger.error(f"{symbol} {side} emri başarısız: {error_msg}")
return {'success': False, 'error': error_msg}
# Başarılı emir
order_data = response.json()
# Gerçek executed fiyat ve miktar bilgilerini al
fills = order_data.get('fills', [])
if fills:
# Weighted average price hesapla
total_qty = sum(float(fill['qty']) for fill in fills)
weighted_price = sum(float(fill['price']) * float(fill['qty']) for fill in fills) / total_qty
executed_qty = total_qty
executed_commission = sum(float(fill['commission']) for fill in fills)
commission_asset = fills[0].get('commissionAsset', 'BNB')
else:
# Fallback to current price if fills not available
weighted_price = current_price
executed_qty = quantity
executed_commission = 0
commission_asset = 'BNB'
# Log yazma - daha detaylı
if signal == 'BUY':
log_message = f"[{current_time}] ✅ [CANLI ALIM BAŞARILI] {symbol}\n"
log_message += f" └─ Miktar: {executed_qty:.6f} {symbol.replace('USDT', '')}\n"
log_message += f" └─ Fiyat: {weighted_price:.2f} USDT\n"
log_message += f" └─ Toplam: {amount_usdt:.2f} USDT\n"
log_message += f" └─ Komisyon: {executed_commission:.6f} {commission_asset}\n"
log_message += f" └─ Emir ID: {order_data.get('orderId')}"
else: # SELL
log_message = f"[{current_time}] ✅ [CANLI SATIM BAŞARILI] {symbol}\n"
log_message += f" └─ Miktar: {executed_qty:.6f} {symbol.replace('USDT', '')}\n"
log_message += f" └─ Fiyat: {weighted_price:.2f} USDT\n"
log_message += f" └─ Komisyon: {executed_commission:.6f} {commission_asset}\n"
log_message += f" └─ Emir ID: {order_data.get('orderId')}"
print(log_message)
if signal_logger:
signal_logger.info(log_message)
# Return dictionary
result = {
'success': True,
'orderId': order_data.get('orderId'),
'status': order_data.get('status'),
'price': weighted_price,
'quantity': executed_qty,
'amount_usdt': amount_usdt,
'commission': executed_commission,
'commission_asset': commission_asset,
'data': order_data
}
return result
except Exception as e:
error_msg = str(e)
print(f"[{current_time}] [CANLI HATA] {symbol} emri hatası: {error_msg}")
if signal_logger:
signal_logger.error(f"{symbol} emri hatası: {error_msg}")
return {
'success': False,
'error': error_msg
}
def calculate_ssl_hybrid_signals(klines):
"""
SSL Hybrid stratejisi ile sinyal hesaplama
Args:
klines: Binance kline verisi
Returns:
dict: Sinyal bilgileri
"""
try:
if len(klines) < 20: # En az 20 mum gerekli (test için)
return {
'signal': 0,
'signal_text': 'NONE',
'trend': 'Beklemede',
'baseline': 0,
'ssl1': 0,
'ssl2': 0,
'exit': 0
}
# Tüm mumları kullan (1000 mum)
recent_klines = klines
# OHLCV verilerini çıkar
highs = [float(k[2]) for k in recent_klines]
lows = [float(k[3]) for k in recent_klines]
closes = [float(k[4]) for k in recent_klines]
opens = [float(k[1]) for k in recent_klines]
# SSL Hybrid parametreleri
ssl1_len = 60
ssl2_len = 5
exit_len = 15
atr_len = 14
# HMA hesaplama fonksiyonu
def calc_hma(values, period):
if len(values) < period:
return [0] * len(values)
# WMA hesaplama
def calc_wma(data, length):
result = []
for i in range(len(data)):
if i < length - 1:
result.append(0)
else:
weights = list(range(1, length + 1))
weight_sum = sum(weights)
weighted_sum = sum(data[i - length + 1 + j] * weights[j] for j in range(length))
result.append(weighted_sum / weight_sum)
return result
half_period = period // 2
sqrt_period = int(period ** 0.5)
wma1 = calc_wma(values, half_period)
wma2 = calc_wma(values, period)
raw_hma = [2 * wma1[i] - wma2[i] if wma1[i] != 0 and wma2[i] != 0 else 0 for i in range(len(values))]
return calc_wma(raw_hma, sqrt_period)
# EMA hesaplama
def calc_ema(values, period):
if len(values) < period:
return [0] * len(values)
k = 2 / (period + 1)
result = [values[0]]
for i in range(1, len(values)):