many ki generated scripts and versions added
This commit is contained in:
@@ -0,0 +1,367 @@
|
||||
"""
|
||||
Position Control für TradingBot V1.4
|
||||
Verhindert mehrfache gleichzeitige Trades
|
||||
"""
|
||||
|
||||
import MetaTrader5 as mt
|
||||
import pandas as pd
|
||||
from datetime import datetime
|
||||
|
||||
def check_existing_positions(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete"):
|
||||
"""
|
||||
Überprüft ob bereits Positionen für das Symbol und die Strategie existieren
|
||||
|
||||
Returns:
|
||||
- has_position: bool - True wenn bereits Position existiert
|
||||
- position_info: dict - Info über bestehende Position(en)
|
||||
"""
|
||||
try:
|
||||
# Alle Positionen für das Symbol abrufen
|
||||
positions = mt.positions_get(symbol=symbol)
|
||||
|
||||
if positions is None:
|
||||
return False, {"count": 0, "details": []}
|
||||
|
||||
# Filter nach Strategie-Namen im Kommentar
|
||||
strategy_positions = []
|
||||
for pos in positions:
|
||||
if strategy_name in pos.comment:
|
||||
strategy_positions.append({
|
||||
"ticket": pos.ticket,
|
||||
"type": "BUY" if pos.type == 0 else "SELL",
|
||||
"volume": pos.volume,
|
||||
"price_open": pos.price_open,
|
||||
"profit": pos.profit,
|
||||
"comment": pos.comment,
|
||||
"time_open": pd.to_datetime(pos.time, unit='s')
|
||||
})
|
||||
|
||||
has_position = len(strategy_positions) > 0
|
||||
|
||||
position_info = {
|
||||
"count": len(strategy_positions),
|
||||
"details": strategy_positions
|
||||
}
|
||||
|
||||
return has_position, position_info
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error checking positions: {e}")
|
||||
return False, {"count": 0, "details": []}
|
||||
|
||||
def get_position_summary(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete"):
|
||||
"""
|
||||
Gibt eine übersichtliche Zusammenfassung der aktuellen Positionen
|
||||
"""
|
||||
has_position, position_info = check_existing_positions(symbol, strategy_name)
|
||||
|
||||
print(f"\n📊 POSITION SUMMARY für {symbol}")
|
||||
print("=" * 50)
|
||||
|
||||
if not has_position:
|
||||
print("✅ Keine aktiven Positionen - bereit für neuen Trade")
|
||||
return False
|
||||
|
||||
print(f"⚠️ {position_info['count']} aktive Position(en) gefunden:")
|
||||
|
||||
for i, pos in enumerate(position_info['details'], 1):
|
||||
profit_emoji = "🟢" if pos['profit'] >= 0 else "🔴"
|
||||
print(f"\n Position {i}:")
|
||||
print(f" Ticket: {pos['ticket']}")
|
||||
print(f" Typ: {pos['type']}")
|
||||
print(f" Volumen: {pos['volume']}")
|
||||
print(f" Eröffnungspreis: {pos['price_open']}")
|
||||
print(f" Profit: {profit_emoji} {pos['profit']:.2f}")
|
||||
print(f" Eröffnungszeit: {pos['time_open']}")
|
||||
print(f" Kommentar: {pos['comment']}")
|
||||
|
||||
print(f"\n🛑 TRADING BLOCKIERT - Maximal 1 Position erlaubt")
|
||||
return True
|
||||
|
||||
def close_existing_positions(symbol="XAUUSD", strategy_name="TradingBot_V1.4_Complete", force_close=False):
|
||||
"""
|
||||
Schließt bestehende Positionen (optional)
|
||||
|
||||
Args:
|
||||
force_close: bool - Wenn True, schließt alle Positionen sofort
|
||||
"""
|
||||
has_position, position_info = check_existing_positions(symbol, strategy_name)
|
||||
|
||||
if not has_position:
|
||||
print("✅ Keine Positionen zum Schließen")
|
||||
return True
|
||||
|
||||
if not force_close:
|
||||
print(f"⚠️ {position_info['count']} Position(en) gefunden. Verwende force_close=True zum Schließen.")
|
||||
return False
|
||||
|
||||
print(f"🔄 Schließe {position_info['count']} Position(en)...")
|
||||
|
||||
success_count = 0
|
||||
for pos in position_info['details']:
|
||||
try:
|
||||
# Position schließen
|
||||
close_request = {
|
||||
"action": mt.TRADE_ACTION_DEAL,
|
||||
"symbol": symbol,
|
||||
"volume": pos['volume'],
|
||||
"type": mt.ORDER_TYPE_SELL if pos['type'] == "BUY" else mt.ORDER_TYPE_BUY,
|
||||
"position": pos['ticket'],
|
||||
"price": mt.symbol_info_tick(symbol).bid if pos['type'] == "BUY" else mt.symbol_info_tick(symbol).ask,
|
||||
"deviation": 20,
|
||||
"magic": 234000,
|
||||
"comment": f"Close {strategy_name}",
|
||||
"type_time": mt.ORDER_TIME_GTC,
|
||||
"type_filling": mt.ORDER_FILLING_IOC,
|
||||
}
|
||||
|
||||
result = mt.order_send(close_request)
|
||||
|
||||
if result.retcode == mt.TRADE_RETCODE_DONE:
|
||||
print(f"✅ Position {pos['ticket']} erfolgreich geschlossen")
|
||||
success_count += 1
|
||||
else:
|
||||
print(f"❌ Fehler beim Schließen von Position {pos['ticket']}: {result.comment}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Exception beim Schließen von Position {pos['ticket']}: {e}")
|
||||
|
||||
print(f"📊 {success_count}/{len(position_info['details'])} Positionen erfolgreich geschlossen")
|
||||
return success_count == len(position_info['details'])
|
||||
|
||||
def enhanced_execute_trade_v2_with_position_control(
|
||||
symbol="XAUUSD",
|
||||
atr_mult=1.5,
|
||||
base_confidence=70,
|
||||
max_risk_per_trade=0.01,
|
||||
risk_filter=True,
|
||||
min_atr=0.0010,
|
||||
use_pullback_entry=True,
|
||||
max_positions=1, # NEU: Maximale Anzahl Positionen
|
||||
strategy_name="TradingBot_V1.4_Complete",
|
||||
debug=True
|
||||
):
|
||||
"""
|
||||
Enhanced Execute Trade mit Position-Kontrolle
|
||||
"""
|
||||
|
||||
# WICHTIG: Zuerst Position-Check
|
||||
print(f"\n🔍 POSITION CHECK für {symbol}")
|
||||
has_position, position_info = check_existing_positions(symbol, strategy_name)
|
||||
|
||||
if has_position and position_info['count'] >= max_positions:
|
||||
if debug:
|
||||
print(f"🛑 TRADE BLOCKIERT: {position_info['count']}/{max_positions} Positionen bereits aktiv")
|
||||
for pos in position_info['details']:
|
||||
profit_emoji = "🟢" if pos['profit'] >= 0 else "🔴"
|
||||
print(f" Position: {pos['type']} {pos['volume']} @ {pos['price_open']} | Profit: {profit_emoji} {pos['profit']:.2f}")
|
||||
return None
|
||||
|
||||
print(f"✅ Position-Check OK: {position_info['count']}/{max_positions} Positionen")
|
||||
|
||||
# Hier würde deine bestehende execute_trade_v2 Logik kommen
|
||||
# Ich importiere sie von deinem bestehenden Code
|
||||
|
||||
try:
|
||||
# Import der bestehenden Funktionen (angepasst an deine Struktur)
|
||||
from TradingBot_V1_4_Complete import extended_top_down_v2, check_risk_limits, market_order, check_pullback_entry
|
||||
|
||||
# Signal-Analyse
|
||||
signal_info = extended_top_down_v2(symbol)
|
||||
if signal_info is None:
|
||||
print("❌ Signal-Analyse fehlgeschlagen")
|
||||
return None
|
||||
|
||||
entry_signal = signal_info["entry_signal"]
|
||||
confidence = signal_info["confidence"]
|
||||
adaptive_threshold = signal_info["adaptive_threshold"]
|
||||
signal_quality = signal_info["signal_quality"]
|
||||
market_regime = signal_info["market_regime"]
|
||||
|
||||
# Get Price/ATR from M5
|
||||
m5_info = signal_info["trend_info"]["M5"]
|
||||
price = m5_info["price"]
|
||||
atr = m5_info["atr"]
|
||||
|
||||
# Enhanced Pre-checks
|
||||
reason = ""
|
||||
|
||||
if confidence < adaptive_threshold:
|
||||
reason = f"Confidence {confidence}% < adaptive threshold {adaptive_threshold}%"
|
||||
elif entry_signal == 0:
|
||||
reason = f"No entry signal (Trend: {signal_info['top_down_trend']}, Regime: {market_regime['regime']})"
|
||||
elif price is None or atr is None:
|
||||
reason = "Price/ATR not available"
|
||||
elif risk_filter and atr < min_atr:
|
||||
reason = f"ATR {atr:.5f} < min_atr {min_atr}"
|
||||
elif signal_quality == "none":
|
||||
reason = "Signal quality insufficient"
|
||||
else:
|
||||
# Entry Timing Check
|
||||
if use_pullback_entry:
|
||||
pullback_ok, pullback_reason = check_pullback_entry(symbol, signal_info)
|
||||
if not pullback_ok:
|
||||
reason = f"Entry timing: {pullback_reason}"
|
||||
|
||||
if not reason:
|
||||
# Risk Checks
|
||||
risk_ok = check_risk_limits(symbol, max_risk_per_trade=max_risk_per_trade)
|
||||
if not risk_ok:
|
||||
reason = "Risk limits exceeded"
|
||||
|
||||
# Execute Trade if all checks pass
|
||||
if not reason:
|
||||
# Enhanced SL/TP calculation based on regime
|
||||
regime_mult = 1.0
|
||||
if market_regime['regime'] == 'volatile':
|
||||
regime_mult = 1.3 # Wider stops in volatile markets
|
||||
elif market_regime['regime'] == 'ranging':
|
||||
regime_mult = 0.8 # Tighter stops in ranging markets
|
||||
|
||||
adjusted_atr_mult = atr_mult * regime_mult
|
||||
|
||||
if entry_signal == 1: # Long
|
||||
stop_loss = price - adjusted_atr_mult * atr
|
||||
take_profit = price + adjusted_atr_mult * atr * 2.5
|
||||
else: # Short
|
||||
stop_loss = price + adjusted_atr_mult * atr
|
||||
take_profit = price - adjusted_atr_mult * atr * 2.5
|
||||
|
||||
# Dynamic Position Sizing
|
||||
stop_distance = adjusted_atr_mult * atr
|
||||
account_info = mt.account_info()
|
||||
if account_info:
|
||||
balance = account_info.balance
|
||||
risk_amount = balance * max_risk_per_trade
|
||||
if symbol == "XAUUSD":
|
||||
volume = min(0.1, max(0.01, risk_amount / (stop_distance * 100)))
|
||||
else:
|
||||
volume = 0.01
|
||||
else:
|
||||
volume = 0.01
|
||||
|
||||
# FINAL POSITION CHECK vor Order
|
||||
final_check, _ = check_existing_positions(symbol, strategy_name)
|
||||
if final_check:
|
||||
print(f"🛑 LAST-MINUTE BLOCK: Position wurde zwischen Checks eröffnet!")
|
||||
return None
|
||||
|
||||
# Log Enhanced Trade Info
|
||||
print(f"\n🚀 ENHANCED TRADE EXECUTION (mit Position Control)")
|
||||
print(f"Symbol: {symbol}")
|
||||
print(f"Direction: {'LONG' if entry_signal == 1 else 'SHORT'}")
|
||||
print(f"Price: {price:.5f}")
|
||||
print(f"Volume: {volume:.2f}")
|
||||
print(f"Stop Loss: {stop_loss:.5f}")
|
||||
print(f"Take Profit: {take_profit:.5f}")
|
||||
print(f"Confidence: {confidence}% (Threshold: {adaptive_threshold}%)")
|
||||
print(f"Signal Quality: {signal_quality.upper()}")
|
||||
print(f"Market Regime: {market_regime['regime'].upper()}")
|
||||
print(f"Position Limit: {position_info['count']}/{max_positions}")
|
||||
|
||||
# Execute the actual trade
|
||||
try:
|
||||
order_result = market_order(
|
||||
symbol=symbol,
|
||||
volume=volume,
|
||||
order_type="buy" if entry_signal == 1 else "sell",
|
||||
stoploss=stop_loss,
|
||||
take_profit=take_profit,
|
||||
comment=strategy_name # Wichtig für Position-Tracking
|
||||
)
|
||||
|
||||
if order_result and order_result.retcode == mt.TRADE_RETCODE_DONE:
|
||||
print(f"✅ Trade erfolgreich eröffnet! Ticket: {order_result.order}")
|
||||
|
||||
# Verify position was created
|
||||
new_check, new_info = check_existing_positions(symbol, strategy_name)
|
||||
print(f"📊 Neue Position-Anzahl: {new_info['count']}")
|
||||
|
||||
return order_result
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Trade execution failed: {e}")
|
||||
return None
|
||||
|
||||
else:
|
||||
if debug:
|
||||
print(f"\n⏸️ TRADE SKIPPED: {reason}")
|
||||
print(f"Confidence: {confidence}% | Threshold: {adaptive_threshold}%")
|
||||
print(f"Signal Quality: {signal_quality} | Regime: {market_regime['regime']}")
|
||||
print(f"Positions: {position_info['count']}/{max_positions}")
|
||||
return None
|
||||
|
||||
except ImportError:
|
||||
print("❌ Konnte bestehende Funktionen nicht importieren. Verwende vereinfachte Version.")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"❌ Fehler in enhanced_execute_trade_v2_with_position_control: {e}")
|
||||
return None
|
||||
|
||||
def position_management_menu():
|
||||
"""
|
||||
Interaktives Menü für Position-Management
|
||||
"""
|
||||
symbol = "XAUUSD"
|
||||
strategy_name = "TradingBot_V1.4_Complete"
|
||||
|
||||
while True:
|
||||
print(f"\n🔧 POSITION MANAGEMENT MENU")
|
||||
print("=" * 40)
|
||||
print("1. Position Status anzeigen")
|
||||
print("2. Alle Positionen schließen")
|
||||
print("3. Position-Check für neuen Trade")
|
||||
print("4. Trading mit Position-Control testen")
|
||||
print("5. Exit")
|
||||
|
||||
choice = input("\nWähle Option (1-5): ").strip()
|
||||
|
||||
if choice == "1":
|
||||
get_position_summary(symbol, strategy_name)
|
||||
|
||||
elif choice == "2":
|
||||
confirm = input("❗ Alle Positionen schließen? (yes/no): ").strip().lower()
|
||||
if confirm in ['yes', 'y', 'ja', 'j']:
|
||||
close_existing_positions(symbol, strategy_name, force_close=True)
|
||||
else:
|
||||
print("❌ Abgebrochen")
|
||||
|
||||
elif choice == "3":
|
||||
has_pos, pos_info = check_existing_positions(symbol, strategy_name)
|
||||
if has_pos:
|
||||
print(f"🛑 {pos_info['count']} Position(en) aktiv - KEIN neuer Trade möglich")
|
||||
else:
|
||||
print("✅ Keine Positionen - neuer Trade möglich")
|
||||
|
||||
elif choice == "4":
|
||||
print("🧪 Testing Trading mit Position Control...")
|
||||
result = enhanced_execute_trade_v2_with_position_control(
|
||||
symbol=symbol,
|
||||
strategy_name=strategy_name,
|
||||
debug=True
|
||||
)
|
||||
if result:
|
||||
print(f"✅ Test-Trade ausgeführt: {result}")
|
||||
else:
|
||||
print("⏸️ Kein Test-Trade ausgeführt")
|
||||
|
||||
elif choice == "5":
|
||||
print("👋 Exit Position Management")
|
||||
break
|
||||
|
||||
else:
|
||||
print("❌ Ungültige Option")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Teste Position Control
|
||||
symbol = "XAUUSD"
|
||||
strategy_name = "TradingBot_V1.4_Complete"
|
||||
|
||||
print("🔍 TESTING POSITION CONTROL")
|
||||
print("=" * 40)
|
||||
|
||||
# Check current positions
|
||||
get_position_summary(symbol, strategy_name)
|
||||
|
||||
# Start interactive menu
|
||||
position_management_menu()
|
||||
Reference in New Issue
Block a user