Bot auto-update: src/main_ml.py
This commit is contained in:
parent
32ed8cac6d
commit
bd68b491f2
272
src/main_ml.py
272
src/main_ml.py
|
|
@ -1,63 +1,56 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""Trading Bot v0.4 - Dynamic Position Sizing (% of Portfolio)"""
|
||||||
Trading Bot V0.3 - Strategy Rewrite
|
import os, json, time, logging
|
||||||
Deployed: 2026-07-09 18:30 UTC
|
|
||||||
Changes: Fresh balance cache, local min signal, hard TP/SL
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from decimal import Decimal, ROUND_DOWN
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
from binance.client import Client
|
from binance.client import Client
|
||||||
from binance.exceptions import BinanceAPIException
|
from binance.exceptions import BinanceAPIException
|
||||||
|
|
||||||
|
# Setup Logging
|
||||||
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s')
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Setup
|
# Load API Keys
|
||||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s')
|
API_KEY = os.getenv('BINANCE_API_KEY_LIVE')
|
||||||
logger = logging.getLogger()
|
API_SECRET = os.getenv('BINANCE_API_SECRET_LIVE')
|
||||||
|
|
||||||
load_dotenv()
|
if not API_KEY or not API_SECRET:
|
||||||
try:
|
|
||||||
API_KEY = os.getenv('BINANCE_API_KEY_LIVE')
|
|
||||||
API_SECRET = os.getenv('BINANCE_API_SECRET_LIVE')
|
|
||||||
except:
|
|
||||||
logger.error("Missing API keys")
|
logger.error("Missing API keys")
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
# Constants
|
# ===== DYNAMIC POSITION SIZING CONSTANTS =====
|
||||||
SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'XRPUSDT', 'SOLUSDT']
|
SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'XRPUSDT', 'SOLUSDT']
|
||||||
MIN_USDT = 5.00
|
MIN_USDT = 5.00
|
||||||
MAX_TRADE_USDT = 20.00
|
MAX_POSITION_PCT = 0.05 # 5% of portfolio per trade (DYNAMIC!)
|
||||||
|
KELLY_FRACTION = 0.25 # Conservative Kelly
|
||||||
|
ESTIMATED_WIN_RATE = 0.60 # 60% from bot data
|
||||||
TAKE_PROFIT_PCT = 0.015 # +1.5%
|
TAKE_PROFIT_PCT = 0.015 # +1.5%
|
||||||
STOP_LOSS_PCT = -0.008 # -0.8%
|
STOP_LOSS_PCT = -0.008 # -0.8%
|
||||||
CYCLE_SEC = 60
|
CYCLE_SEC = 60
|
||||||
|
|
||||||
|
|
||||||
class TradingBotV03:
|
class TradingBotV04:
|
||||||
"""Trading Bot with Fresh Cache + Local Min Signals + Hard Risk Management"""
|
"""Trading Bot v0.4 with Dynamic Position Sizing"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.client = Client(API_KEY, API_SECRET)
|
self.client = Client(API_KEY, API_SECRET)
|
||||||
self.price_history = {sym: [] for sym in SYMBOLS}
|
self.price_history = {sym: [] for sym in SYMBOLS}
|
||||||
self.active_trades = {} # {symbol: {'entry_price': float, 'qty': float}}
|
self.active_trades = {}
|
||||||
|
self.portfolio_value = 0
|
||||||
|
self.max_trade_usdt = 0
|
||||||
|
|
||||||
# CRITICAL: Recover orphaned trades from Binance balance (bot got restarted!)
|
# Recover orphaned trades
|
||||||
try:
|
try:
|
||||||
account = self.client.get_account()
|
account = self.client.get_account()
|
||||||
for b in account['balances']:
|
for b in account['balances']:
|
||||||
asset = b['asset']
|
asset = b['asset']
|
||||||
free = float(b['free'])
|
free = float(b['free'])
|
||||||
|
|
||||||
# If we hold a symbol's coin, reconstruct it
|
|
||||||
for symbol in SYMBOLS:
|
for symbol in SYMBOLS:
|
||||||
if symbol.replace('USDT', '') == asset and free > 0.0001:
|
if symbol.replace('USDT', '') == asset and free > 0.0001:
|
||||||
# Get current price to estimate entry
|
|
||||||
try:
|
try:
|
||||||
current_price = float(self.get_current_price(symbol))
|
current_price = float(self.get_current_price(symbol))
|
||||||
self.active_trades[symbol] = {
|
self.active_trades[symbol] = {
|
||||||
'entry_price': current_price, # Reconstructed (not exact, but better than 0)
|
'entry_price': current_price,
|
||||||
'qty': free,
|
'qty': free,
|
||||||
'entry_time': datetime.now().isoformat()
|
'entry_time': datetime.now().isoformat()
|
||||||
}
|
}
|
||||||
|
|
@ -66,21 +59,43 @@ class TradingBotV03:
|
||||||
pass
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Trade recovery failed: {e}")
|
logger.warning(f"Trade recovery failed: {e}")
|
||||||
logger.info("Bot V0.3 initialized | Fresh Cache + Local Min + Hard TP/SL")
|
|
||||||
|
logger.info("Bot V0.4 initialized | Dynamic Position Sizing (% of Portfolio)")
|
||||||
|
|
||||||
def get_fresh_balance(self):
|
def get_fresh_balance(self):
|
||||||
"""KEY FIX: Always fetch FRESH balance from API (no stale cache!)"""
|
"""Always fetch FRESH balance from API"""
|
||||||
try:
|
try:
|
||||||
account = self.client.get_account()
|
account = self.client.get_account()
|
||||||
balances = {}
|
balances = {}
|
||||||
|
portfolio_value = 0
|
||||||
|
|
||||||
|
# Get prices
|
||||||
|
prices = {'USDT': 1.0}
|
||||||
|
for p in ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT']:
|
||||||
|
try:
|
||||||
|
t = self.client.get_ticker(symbol=p)
|
||||||
|
prices[p.replace('USDT', '')] = float(t['lastPrice'])
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Calculate balances & portfolio value
|
||||||
for b in account['balances']:
|
for b in account['balances']:
|
||||||
balances[b['asset']] = float(b['free'])
|
asset, free = b['asset'], float(b['free'])
|
||||||
|
balances[asset] = free
|
||||||
|
price = prices.get(asset, 1.0)
|
||||||
|
portfolio_value += free * price
|
||||||
|
|
||||||
usdt_available = balances.get('USDT', 0)
|
usdt_available = balances.get('USDT', 0)
|
||||||
logger.info(f"Fresh balance: USDT=${usdt_available:.2f}")
|
|
||||||
return balances, usdt_available
|
# Store for later use
|
||||||
|
self.portfolio_value = portfolio_value
|
||||||
|
self.max_trade_usdt = portfolio_value * MAX_POSITION_PCT
|
||||||
|
|
||||||
|
logger.info(f"Fresh balance: USDT=${usdt_available:.2f} | Portfolio=${portfolio_value:.2f} | Max Trade=${self.max_trade_usdt:.2f}")
|
||||||
|
return balances, usdt_available, portfolio_value
|
||||||
except BinanceAPIException as e:
|
except BinanceAPIException as e:
|
||||||
logger.error(f"Balance fetch failed: {e}")
|
logger.error(f"Balance fetch failed: {e}")
|
||||||
return {}, 0
|
return {}, 0, 0
|
||||||
|
|
||||||
def get_current_price(self, symbol):
|
def get_current_price(self, symbol):
|
||||||
"""Get current market price"""
|
"""Get current market price"""
|
||||||
|
|
@ -93,50 +108,37 @@ class TradingBotV03:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def calculate_valid_quantity(self, symbol, usdt_amount):
|
def calculate_valid_quantity(self, symbol, usdt_amount):
|
||||||
"""Berechne korrekte Qty mit Decimal precision für LOT_SIZE"""
|
"""Calculate correct Qty with Decimal precision"""
|
||||||
try:
|
try:
|
||||||
price = self.get_current_price(symbol)
|
price = self.get_current_price(symbol)
|
||||||
if not price:
|
if not price:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
# Get exchange info for lot size
|
||||||
info = self.client.get_symbol_info(symbol)
|
info = self.client.get_symbol_info(symbol)
|
||||||
if not info:
|
if not info:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
# Hole LOT_SIZE filter
|
# Find LOT_SIZE filter
|
||||||
lot_size_info = None
|
step_size = None
|
||||||
for filt in info.get('filters', []):
|
for f in info.get('filters', []):
|
||||||
if filt['filterType'] == 'LOT_SIZE':
|
if f['filterType'] == 'LOT_SIZE':
|
||||||
lot_size_info = filt
|
step_size = float(f['stepSize'])
|
||||||
break
|
break
|
||||||
|
|
||||||
if not lot_size_info:
|
if not step_size:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
step_size = Decimal(lot_size_info.get('stepSize', '0.00001'))
|
qty_float = usdt_amount / price
|
||||||
min_qty = Decimal(lot_size_info.get('minQty', '0'))
|
|
||||||
max_qty = Decimal(lot_size_info.get('maxQty', '10000'))
|
|
||||||
|
|
||||||
# Berechne Qty mit Decimal (kein floating-point Fehler!)
|
# Round to step size
|
||||||
qty_decimal = Decimal(str(usdt_amount)) / Decimal(str(price))
|
qty_float = int(qty_float / step_size) * step_size
|
||||||
|
|
||||||
# Runde auf step_size (immer abrunden, nie aufrunden)
|
# Check minimum notional
|
||||||
qty_rounded = (qty_decimal / step_size).quantize(Decimal('1'), rounding=ROUND_DOWN) * step_size
|
min_notional = 5.0
|
||||||
|
|
||||||
# Prüfe Min/Max Grenzen
|
|
||||||
if qty_rounded < min_qty:
|
|
||||||
logger.debug(f"Qty zu klein: {symbol} {qty_rounded} < {min_qty}")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if qty_rounded > max_qty:
|
|
||||||
logger.debug(f"Qty zu groß: {symbol} {qty_rounded} > {max_qty}")
|
|
||||||
qty_rounded = max_qty
|
|
||||||
|
|
||||||
# Konvertiere zu float mit gerader Präzision
|
|
||||||
qty_float = float(qty_rounded)
|
|
||||||
notional = qty_float * price
|
notional = qty_float * price
|
||||||
|
|
||||||
if notional < MIN_USDT:
|
if notional < min_notional:
|
||||||
logger.debug(f"Order too small: {symbol} ${notional:.2f}")
|
logger.debug(f"Order too small: {symbol} ${notional:.2f}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
@ -146,16 +148,15 @@ class TradingBotV03:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Qty calc failed: {e}")
|
logger.warning(f"Qty calc failed: {e}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
def is_local_minimum(self, symbol):
|
def is_local_minimum(self, symbol):
|
||||||
"""Signal Logic: Buy when price is at local minimum (not random %)"""
|
"""Signal Logic: Buy when price is at local minimum"""
|
||||||
if len(self.price_history[symbol]) < 5:
|
if len(self.price_history[symbol]) < 5:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
recent_prices = self.price_history[symbol][-5:]
|
recent_prices = self.price_history[symbol][-5:]
|
||||||
current_price = recent_prices[-1]
|
current_price = recent_prices[-1]
|
||||||
|
|
||||||
# Local min condition: current is lower than all recent prices
|
|
||||||
is_min = all(current_price < p for p in recent_prices[:-1])
|
is_min = all(current_price < p for p in recent_prices[:-1])
|
||||||
|
|
||||||
if is_min:
|
if is_min:
|
||||||
|
|
@ -188,58 +189,51 @@ class TradingBotV03:
|
||||||
logger.info(f"BUY: {qty} {symbol} @ ${entry_price:.2f} (${qty*entry_price:.2f})")
|
logger.info(f"BUY: {qty} {symbol} @ ${entry_price:.2f} (${qty*entry_price:.2f})")
|
||||||
logger.info(f" TP target: +${qty*entry_price*TAKE_PROFIT_PCT:.2f} ({TAKE_PROFIT_PCT*100:.1f}%)")
|
logger.info(f" TP target: +${qty*entry_price*TAKE_PROFIT_PCT:.2f} ({TAKE_PROFIT_PCT*100:.1f}%)")
|
||||||
logger.info(f" SL target: -${qty*entry_price*abs(STOP_LOSS_PCT):.2f} ({STOP_LOSS_PCT*100:.1f}%)")
|
logger.info(f" SL target: -${qty*entry_price*abs(STOP_LOSS_PCT):.2f} ({STOP_LOSS_PCT*100:.1f}%)")
|
||||||
|
logger.info(f" [DYNAMIC] Portfolio: ${self.portfolio_value:.2f} | Max Position: ${self.max_trade_usdt:.2f}")
|
||||||
|
|
||||||
return order
|
return order
|
||||||
|
|
||||||
except BinanceAPIException as e:
|
except BinanceAPIException as e:
|
||||||
logger.error(f"Buy order failed: {e}")
|
logger.error(f"Order failed: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def check_and_close_positions(self):
|
def check_and_close_positions(self):
|
||||||
"""HARD RISK MANAGEMENT: Close positions that hit TP or SL"""
|
"""Check TP/SL for all active trades"""
|
||||||
for symbol in list(self.active_trades.keys()):
|
for symbol, trade in list(self.active_trades.items()):
|
||||||
trade = self.active_trades[symbol]
|
try:
|
||||||
current_price = self.get_current_price(symbol)
|
current_price = self.get_current_price(symbol)
|
||||||
|
if not current_price:
|
||||||
if not current_price:
|
continue
|
||||||
continue
|
|
||||||
|
entry_price = trade['entry_price']
|
||||||
entry_price = trade['entry_price']
|
qty = trade['qty']
|
||||||
qty = trade['qty']
|
pnl_pct = ((current_price - entry_price) / entry_price) * 100
|
||||||
pnl_pct = (current_price - entry_price) / entry_price
|
|
||||||
pnl_usdt = qty * (current_price - entry_price)
|
# Check TP
|
||||||
|
if pnl_pct >= TAKE_PROFIT_PCT * 100:
|
||||||
# Check Take Profit (close winners immediately!)
|
logger.info(f"SELL (TP): {qty} {symbol} @ ${current_price:.2f} | +{pnl_pct:.2f}%")
|
||||||
if pnl_pct >= TAKE_PROFIT_PCT:
|
try:
|
||||||
logger.info(f"TAKE PROFIT: {symbol} +{pnl_pct*100:.2f}% (${pnl_usdt:.2f})")
|
self.client.order_market_sell(symbol=symbol, quantity=qty)
|
||||||
try:
|
del self.active_trades[symbol]
|
||||||
# Validiere Qty vor Verkauf (rund ab für LOT_SIZE)
|
except:
|
||||||
qty_sell = float(Decimal(str(qty)).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN))
|
pass
|
||||||
self.client.order_market_sell(symbol=symbol, quantity=qty_sell)
|
|
||||||
del self.active_trades[symbol]
|
# Check SL
|
||||||
except Exception as e:
|
elif pnl_pct <= STOP_LOSS_PCT * 100:
|
||||||
logger.error(f"Sell failed: {e}")
|
logger.info(f"SELL (SL): {qty} {symbol} @ ${current_price:.2f} | {pnl_pct:.2f}%")
|
||||||
continue
|
try:
|
||||||
|
self.client.order_market_sell(symbol=symbol, quantity=qty)
|
||||||
# Check Stop Loss (cut losers fast!)
|
del self.active_trades[symbol]
|
||||||
if pnl_pct <= STOP_LOSS_PCT:
|
except:
|
||||||
logger.warning(f"STOP LOSS: {symbol} {pnl_pct*100:.2f}% (${pnl_usdt:.2f})")
|
pass
|
||||||
try:
|
except:
|
||||||
# Validiere Qty vor Verkauf (rund ab für LOT_SIZE)
|
pass
|
||||||
qty_sell = float(Decimal(str(qty)).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN))
|
|
||||||
self.client.order_market_sell(symbol=symbol, quantity=qty_sell)
|
|
||||||
del self.active_trades[symbol]
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Sell failed: {e}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
def cycle(self):
|
def run_cycle(self):
|
||||||
"""Main trading cycle (runs every 60 seconds)"""
|
"""Main trading cycle"""
|
||||||
logger.info("=" * 70)
|
logger.info("=" * 70)
|
||||||
logger.info(f"CYCLE START @ {datetime.now().strftime('%H:%M:%S CET')}")
|
|
||||||
|
|
||||||
# STEP 1: Fresh balance (KEY FIX for cache bug!)
|
# STEP 1: Fresh balance & calculate dynamic position size
|
||||||
balances, usdt_free = self.get_fresh_balance()
|
balances, usdt_free, portfolio_val = self.get_fresh_balance()
|
||||||
|
|
||||||
if usdt_free < MIN_USDT:
|
if usdt_free < MIN_USDT:
|
||||||
logger.warning(f"Insufficient capital: ${usdt_free:.2f} < ${MIN_USDT}")
|
logger.warning(f"Insufficient capital: ${usdt_free:.2f} < ${MIN_USDT}")
|
||||||
|
|
@ -254,7 +248,6 @@ class TradingBotV03:
|
||||||
price = self.get_current_price(symbol)
|
price = self.get_current_price(symbol)
|
||||||
if price:
|
if price:
|
||||||
self.price_history[symbol].append(price)
|
self.price_history[symbol].append(price)
|
||||||
# Keep only last 20 prices
|
|
||||||
if len(self.price_history[symbol]) > 20:
|
if len(self.price_history[symbol]) > 20:
|
||||||
self.price_history[symbol].pop(0)
|
self.price_history[symbol].pop(0)
|
||||||
|
|
||||||
|
|
@ -267,53 +260,46 @@ class TradingBotV03:
|
||||||
|
|
||||||
# STEP 5: Place trade if signal exists and we have capital
|
# STEP 5: Place trade if signal exists and we have capital
|
||||||
if best_signal and usdt_free >= MIN_USDT:
|
if best_signal and usdt_free >= MIN_USDT:
|
||||||
# Use max 50% of available capital, but capped at MAX_TRADE_USDT
|
trade_amount = min(self.max_trade_usdt, usdt_free * 0.5)
|
||||||
trade_amount = min(MAX_TRADE_USDT, usdt_free * 0.5)
|
|
||||||
self.place_buy_order(best_signal, trade_amount)
|
self.place_buy_order(best_signal, trade_amount)
|
||||||
|
|
||||||
logger.info(f"CYCLE END | Active trades: {len(self.active_trades)} | Free USDT: ${usdt_free:.2f}")
|
logger.info(f"CYCLE END | Active trades: {len(self.active_trades)} | Free USDT: ${usdt_free:.2f} | Portfolio: ${portfolio_val:.2f}")
|
||||||
|
|
||||||
# Save active trades for dashboard (atomic write with temp file)
|
# Save active trades for dashboard
|
||||||
import json, os
|
import json, os
|
||||||
try:
|
try:
|
||||||
temp_file = '/home/marc/bot-deploy/active_trades.json.tmp'
|
temp_file = '/home/marc/bot-deploy/active_trades.json.tmp'
|
||||||
with open(temp_file, 'w') as f:
|
with open(temp_file, 'w') as f:
|
||||||
json.dump({'active_trades': self.active_trades, 'count': len(self.active_trades)}, f)
|
json.dump({
|
||||||
|
'active_trades': self.active_trades,
|
||||||
|
'count': len(self.active_trades),
|
||||||
|
'portfolio_value': round(portfolio_val, 2),
|
||||||
|
'max_trade_usdt': round(self.max_trade_usdt, 2),
|
||||||
|
'timestamp': datetime.now().isoformat()
|
||||||
|
}, f)
|
||||||
os.replace(temp_file, '/home/marc/bot-deploy/active_trades.json')
|
os.replace(temp_file, '/home/marc/bot-deploy/active_trades.json')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f'Failed to save active_trades.json: {e}')
|
logger.warning(f"Failed to save trades: {e}")
|
||||||
|
|
||||||
# Verify data freshness (Log entry_times for debug)
|
|
||||||
if self.active_trades:
|
|
||||||
oldest = min([t['entry_time'] for t in self.active_trades.values()])
|
|
||||||
logger.info(f"DATA FRESHNESS: Oldest trade entry @ {oldest[:19]} (fresh from API)")
|
|
||||||
logger.info("=" * 70)
|
logger.info("=" * 70)
|
||||||
|
|
||||||
def run(self):
|
|
||||||
"""Infinite trading loop"""
|
|
||||||
logger.info("=" * 70)
|
|
||||||
logger.info("TRADING BOT V0.3 STARTED")
|
|
||||||
logger.info(f"Symbols: {SYMBOLS}")
|
|
||||||
logger.info(f"Strategy: Local Min Signals | Risk: TP=+{TAKE_PROFIT_PCT*100:.1f}% / SL={STOP_LOSS_PCT*100:.1f}%")
|
|
||||||
logger.info(f"KEY FIX: Fresh balance fetched EVERY cycle (no stale cache!)")
|
|
||||||
logger.info("=" * 70)
|
|
||||||
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
self.cycle()
|
|
||||||
time.sleep(CYCLE_SEC)
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
logger.info("Bot stopped by user")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"CRITICAL ERROR: {e}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
bot = TradingBotV03()
|
import sys
|
||||||
bot.run()
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv('/home/marc/bot-deploy/.env')
|
||||||
|
|
||||||
|
bot = TradingBotV04()
|
||||||
|
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == '--once':
|
||||||
|
bot.run_cycle()
|
||||||
|
else:
|
||||||
|
logger.info("Starting Bot V0.4 cycle loop...")
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
bot.run_cycle()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Cycle error: {e}")
|
||||||
|
|
||||||
|
time.sleep(CYCLE_SEC)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue