Spaces:
Configuration error
You are an expert AI trading system developer specializing in forex automation.
Browse filesWrite a complete, production-ready Python code for an AI-powered gold trading bot (XAU/USD) that performs the following tasks:
1. **Live Price Feed:**
- Continuously fetch real-time Gold Spot (XAU/USD) data from TradingView or a similar source (e.g., using `tvdatafeed` or `tradingview_ta` Python libraries).
- Update every few seconds to maintain accuracy.
2. **Technical Analysis:**
- Automatically analyze market structure and chart patterns (support/resistance, trendlines, breakouts, pullbacks).
- Use multiple indicators such as:
- RSI, MACD, EMA 20/50/200, Bollinger Bands, and ATR.
- Identify and label current trend direction (Bullish, Bearish, or Sideways).
- Detect reversal signals or breakouts.
3. **Signal Generation:**
- Generate clear trade signals:
- โBUYโ when price shows bullish confirmation near support or after EMA cross.
- โSELLโ when price shows bearish confirmation near resistance or reversal candle.
- โWAITโ when no strong setup is detected.
- Include confidence score and reasoning for each signal.
4. **Auto Trading Function:**
- Integrate with a broker API (like MetaTrader 5, Binance, or FBS) to execute trades automatically when signals are confirmed.
- Use risk management rules:
- Max 2% risk per trade.
- Auto calculate lot size based on account balance and stop-loss distance.
- Include take-profit and trailing stop options.
5. **Output:**
- Print or send alerts with details:
- Current price
- Signal (BUY/SELL/WAIT)
- Confidence level
- Recommended stop loss and take profit
- Optionally send signals to Telegram or Discord.
6. **Requirements:**
- Use Python 3.x with object-oriented structure.
- Include installation instructions for required libraries.
- Include comments explaining each function and logic clearly.
The goal is to create a fully functional and explainable AI trading assistant for Gold Spot (XAU/USD) based on TradingView live data and automatic decision-making.
- .env.example +15 -0
- README.md +69 -10
- golden_maverick_bot.py +365 -0
- requirements.txt +13 -0
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# TradingView credentials
|
| 3 |
+
TRADINGVIEW_USERNAME=your_username
|
| 4 |
+
TRADINGVIEW_PASSWORD=your_password
|
| 5 |
+
|
| 6 |
+
# Telegram notifications
|
| 7 |
+
TELEGRAM_BOT_TOKEN=your_bot_token
|
| 8 |
+
TELEGRAM_CHAT_ID=your_chat_id
|
| 9 |
+
|
| 10 |
+
# Broker API credentials (MetaTrader 5, Binance, etc.)
|
| 11 |
+
BROKER_API_KEY=your_api_key
|
| 12 |
+
BROKER_API_SECRET=your_api_secret
|
| 13 |
+
BROKER_ACCOUNT_ID=your_account_id
|
| 14 |
+
|
| 15 |
+
</html>
|
|
@@ -1,10 +1,69 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Golden Maverick: AI Gold Trading Bot ๐ฐ
|
| 3 |
+
|
| 4 |
+
An intelligent trading assistant for XAU/USD (Gold Spot) that combines AI predictions with technical analysis for automated trading.
|
| 5 |
+
|
| 6 |
+
## Features
|
| 7 |
+
|
| 8 |
+
- Real-time XAU/USD price tracking from TradingView
|
| 9 |
+
- Advanced technical analysis (EMA, RSI, MACD, Bollinger Bands, ATR)
|
| 10 |
+
- AI-powered market direction prediction
|
| 11 |
+
- Automated trade execution with proper risk management
|
| 12 |
+
- Telegram/Discord notifications
|
| 13 |
+
- 1:2 risk-reward strategy
|
| 14 |
+
|
| 15 |
+
## Installation
|
| 16 |
+
|
| 17 |
+
1. Clone the repository:
|
| 18 |
+
bash
|
| 19 |
+
git clone https://github.com/yourusername/golden-maverick.git
|
| 20 |
+
cd golden-maverick
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
2. Install dependencies:
|
| 24 |
+
bash
|
| 25 |
+
pip install -r requirements.txt
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
3. Create a `.env` file with your credentials:
|
| 29 |
+
|
| 30 |
+
TRADINGVIEW_USERNAME=your_username
|
| 31 |
+
TRADINGVIEW_PASSWORD=your_password
|
| 32 |
+
TELEGRAM_BOT_TOKEN=your_telegram_token
|
| 33 |
+
TELEGRAM_CHAT_ID=your_chat_id
|
| 34 |
+
BROKER_API_KEY=your_broker_key
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
4. Run the bot:
|
| 38 |
+
bash
|
| 39 |
+
python golden_maverick_bot.py
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
## Configuration
|
| 43 |
+
|
| 44 |
+
Edit the bot parameters in `GoldenMaverick` class:
|
| 45 |
+
- `risk_per_trade`: Percentage of account to risk per trade (default 2%)
|
| 46 |
+
- `take_profit_ratio`: Risk-reward ratio (default 1:2)
|
| 47 |
+
- `trailing_stop_enabled`: Whether to use trailing stops
|
| 48 |
+
- `timeframe`: Trading interval (5m, 15m, 1h, etc.)
|
| 49 |
+
|
| 50 |
+
## Trading Strategy
|
| 51 |
+
|
| 52 |
+
The bot combines:
|
| 53 |
+
1. AI prediction model (LSTM neural network)
|
| 54 |
+
2. Traditional technical indicators:
|
| 55 |
+
- EMA Crossovers (20/50/200)
|
| 56 |
+
- RSI overbought/oversold
|
| 57 |
+
- MACD crossovers
|
| 58 |
+
- Bollinger Band extremes
|
| 59 |
+
3. Risk management:
|
| 60 |
+
- 2% max risk per trade
|
| 61 |
+
- Automatic position sizing
|
| 62 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python
|
| 2 |
+
#!/usr/bin/env python3
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import json
|
| 6 |
+
import asyncio
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
from tradingview_ta import TA_Handler, Interval
|
| 12 |
+
from ta.trend import MACD, EMAIndicator
|
| 13 |
+
from ta.momentum import RSIIndicator
|
| 14 |
+
from ta.volatility import BollingerBands
|
| 15 |
+
from ta.volatility import AverageTrueRange
|
| 16 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 17 |
+
from tensorflow.keras.models import load_model
|
| 18 |
+
|
| 19 |
+
# Load environment variables
|
| 20 |
+
load_dotenv()
|
| 21 |
+
|
| 22 |
+
class GoldenMaverick:
|
| 23 |
+
"""
|
| 24 |
+
AI-powered Gold (XAU/USD) Trading Bot with automated technical analysis and trade execution
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self):
|
| 28 |
+
self.symbol = "XAUUSD"
|
| 29 |
+
self.exchange = "OANDA"
|
| 30 |
+
self.timeframe = Interval.INTERVAL_5_MINUTES
|
| 31 |
+
self.model_path = "models/gold_predictor.h5"
|
| 32 |
+
self.risk_per_trade = 0.02 # 2% risk per trade
|
| 33 |
+
self.take_profit_ratio = 2.0 # 1:2 risk-reward
|
| 34 |
+
self.trailing_stop_enabled = True
|
| 35 |
+
self.trailing_stop_distance = 0.0020 # 20 pips for XAU/USD
|
| 36 |
+
self.last_signal = None
|
| 37 |
+
self.account_balance = 10000 # Default, should be fetched from broker
|
| 38 |
+
self.load_ai_model()
|
| 39 |
+
|
| 40 |
+
def load_ai_model(self):
|
| 41 |
+
"""Load pre-trained AI model for market prediction"""
|
| 42 |
+
try:
|
| 43 |
+
self.model = load_model(self.model_path)
|
| 44 |
+
print("AI Model loaded successfully")
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Error loading AI model: {e}")
|
| 47 |
+
self.model = None
|
| 48 |
+
|
| 49 |
+
async def fetch_market_data(self):
|
| 50 |
+
"""Fetch real-time market data from TradingView"""
|
| 51 |
+
while True:
|
| 52 |
+
try:
|
| 53 |
+
handler = TA_Handler(
|
| 54 |
+
symbol=self.symbol,
|
| 55 |
+
exchange=self.exchange,
|
| 56 |
+
screener="forex",
|
| 57 |
+
interval=self.timeframe,
|
| 58 |
+
timeout=10
|
| 59 |
+
)
|
| 60 |
+
analysis = handler.get_analysis()
|
| 61 |
+
self.current_price = analysis.indicators['close']
|
| 62 |
+
self.ohlc_data = {
|
| 63 |
+
'open': analysis.indicators['open'],
|
| 64 |
+
'high': analysis.indicators['high'],
|
| 65 |
+
'low': analysis.indicators['low'],
|
| 66 |
+
'close': self.current_price,
|
| 67 |
+
'volume': analysis.indicators['volume']
|
| 68 |
+
}
|
| 69 |
+
print(f"\n[{datetime.now()}] XAU/USD Price: {self.current_price:.2f}")
|
| 70 |
+
await self.analyze_market()
|
| 71 |
+
await asyncio.sleep(30) # Update every 30 seconds
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error fetching data: {e}")
|
| 74 |
+
await asyncio.sleep(60)
|
| 75 |
+
|
| 76 |
+
async def analyze_market(self):
|
| 77 |
+
"""Perform comprehensive technical analysis"""
|
| 78 |
+
# Load data into DataFrame
|
| 79 |
+
df = pd.DataFrame([self.ohlc_data])
|
| 80 |
+
|
| 81 |
+
# Calculate indicators
|
| 82 |
+
df = self.calculate_technical_indicators(df)
|
| 83 |
+
|
| 84 |
+
# AI-based prediction
|
| 85 |
+
ai_signal = await self.generate_ai_signal(df)
|
| 86 |
+
|
| 87 |
+
# Traditional TA signals
|
| 88 |
+
ta_signals = self.generate_ta_signals(df)
|
| 89 |
+
|
| 90 |
+
# Combine signals
|
| 91 |
+
final_signal = self.combine_signals(ai_signal, ta_signals)
|
| 92 |
+
|
| 93 |
+
# Execute trading logic
|
| 94 |
+
if final_signal['signal'] != 'WAIT':
|
| 95 |
+
await self.execute_trade(final_signal)
|
| 96 |
+
|
| 97 |
+
def calculate_technical_indicators(self, df):
|
| 98 |
+
"""Calculate all technical indicators"""
|
| 99 |
+
# Moving Averages
|
| 100 |
+
df['ema_20'] = EMAIndicator(df['close'], window=20).ema_indicator()
|
| 101 |
+
df['ema_50'] = EMAIndicator(df['close'], window=50).ema_indicator()
|
| 102 |
+
df['ema_200'] = EMAIndicator(df['close'], window=200).ema_indicator()
|
| 103 |
+
|
| 104 |
+
# Momentum Indicators
|
| 105 |
+
df['rsi'] = RSIIndicator(df['close'], window=14).rsi()
|
| 106 |
+
macd = MACD(df['close'], window_slow=26, window_fast=12, window_sign=9)
|
| 107 |
+
df['macd'] = macd.macd()
|
| 108 |
+
df['macd_signal'] = macd.macd_signal()
|
| 109 |
+
df['macd_diff'] = macd.macd_diff()
|
| 110 |
+
|
| 111 |
+
# Volatility Indicators
|
| 112 |
+
bb = BollingerBands(df['close'], window=20, window_dev=2)
|
| 113 |
+
df['bb_upper'] = bb.bollinger_hband()
|
| 114 |
+
df['bb_middle'] = bb.bollinger_mavg()
|
| 115 |
+
df['bb_lower'] = bb.bollinger_lband()
|
| 116 |
+
df['atr'] = AverageTrueRange(
|
| 117 |
+
high=df['high'],
|
| 118 |
+
low=df['low'],
|
| 119 |
+
close=df['close'],
|
| 120 |
+
window=14
|
| 121 |
+
).average_true_range()
|
| 122 |
+
|
| 123 |
+
return df
|
| 124 |
+
|
| 125 |
+
async def generate_ai_signal(self, df):
|
| 126 |
+
"""Generate signal using AI model"""
|
| 127 |
+
if not self.model:
|
| 128 |
+
return {'signal': 'WAIT', 'confidence': 0, 'reason': 'AI Model not available'}
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
# Prepare data for AI model
|
| 132 |
+
features = df[['close', 'ema_20', 'ema_50', 'rsi', 'macd', 'atr']].values
|
| 133 |
+
scaler = MinMaxScaler()
|
| 134 |
+
features_scaled = scaler.fit_transform(features)
|
| 135 |
+
features_scaled = np.reshape(features_scaled, (1, features_scaled.shape[0], features_scaled.shape[1]))
|
| 136 |
+
|
| 137 |
+
# Make prediction
|
| 138 |
+
prediction = self.model.predict(features_scaled)
|
| 139 |
+
confidence = np.max(prediction)
|
| 140 |
+
signal = np.argmax(prediction)
|
| 141 |
+
|
| 142 |
+
return {
|
| 143 |
+
'signal': 'BUY' if signal == 0 else 'SELL' if signal == 1 else 'WAIT',
|
| 144 |
+
'confidence': float(confidence),
|
| 145 |
+
'reason': 'AI Market Prediction'
|
| 146 |
+
}
|
| 147 |
+
except Exception as e:
|
| 148 |
+
print(f"AI Prediction Error: {e}")
|
| 149 |
+
return {'signal': 'WAIT', 'confidence': 0, 'reason': 'Prediction Error'}
|
| 150 |
+
|
| 151 |
+
def generate_ta_signals(self, df):
|
| 152 |
+
"""Generate signals based on traditional technical analysis"""
|
| 153 |
+
signals = []
|
| 154 |
+
confidence = 0
|
| 155 |
+
reasons = []
|
| 156 |
+
|
| 157 |
+
# EMA Crossover Strategy
|
| 158 |
+
if df['ema_20'].iloc[-1] > df['ema_50'].iloc[-1] and df['ema_50'].iloc[-1] > df['ema_200'].iloc[-1]:
|
| 159 |
+
signals.append('BUY')
|
| 160 |
+
confidence += 0.3
|
| 161 |
+
reasons.append("Golden Cross (EMA 20 > 50 > 200)")
|
| 162 |
+
elif df['ema_20'].iloc[-1] < df['ema_50'].iloc[-1] and df['ema_50'].iloc[-1] < df['ema_200'].iloc[-1]:
|
| 163 |
+
signals.append('SELL')
|
| 164 |
+
confidence += 0.3
|
| 165 |
+
reasons.append("Death Cross (EMA 20 < 50 < 200)")
|
| 166 |
+
|
| 167 |
+
# RSI Analysis
|
| 168 |
+
if df['rsi'].iloc[-1] < 30:
|
| 169 |
+
signals.append('BUY')
|
| 170 |
+
confidence += 0.2
|
| 171 |
+
reasons.append("Oversold (RSI < 30)")
|
| 172 |
+
elif df['rsi'].iloc[-1] > 70:
|
| 173 |
+
signals.append('SELL')
|
| 174 |
+
confidence += 0.2
|
| 175 |
+
reasons.append("Overbought (RSI > 70)")
|
| 176 |
+
|
| 177 |
+
# MACD Analysis
|
| 178 |
+
if df['macd'].iloc[-1] > df['macd_signal'].iloc[-1] and df['macd'].iloc[-2] <= df['macd_signal'].iloc[-2]:
|
| 179 |
+
signals.append('BUY')
|
| 180 |
+
confidence += 0.2
|
| 181 |
+
reasons.append("MACD Bullish Crossover")
|
| 182 |
+
elif df['macd'].iloc[-1] < df['macd_signal'].iloc[-1] and df['macd'].iloc[-2] >= df['macd_signal'].iloc[-2]:
|
| 183 |
+
signals.append('SELL')
|
| 184 |
+
confidence += 0.2
|
| 185 |
+
reasons.append("MACD Bearish Crossover")
|
| 186 |
+
|
| 187 |
+
# Bollinger Bands Analysis
|
| 188 |
+
if df['close'].iloc[-1] < df['bb_lower'].iloc[-1]:
|
| 189 |
+
signals.append('BUY')
|
| 190 |
+
confidence += 0.1
|
| 191 |
+
reasons.append("Price at Lower Bollinger Band")
|
| 192 |
+
elif df['close'].iloc[-1] > df['bb_upper'].iloc[-1]:
|
| 193 |
+
signals.append('SELL')
|
| 194 |
+
confidence += 0.1
|
| 195 |
+
reasons.append("Price at Upper Bollinger Band")
|
| 196 |
+
|
| 197 |
+
# Determine final signal
|
| 198 |
+
if not signals:
|
| 199 |
+
return {'signal': 'WAIT', 'confidence': 0, 'reason': 'No strong signals detected'}
|
| 200 |
+
|
| 201 |
+
# Count votes and determine primary signal
|
| 202 |
+
buy_count = signals.count('BUY')
|
| 203 |
+
sell_count = signals.count('SELL')
|
| 204 |
+
|
| 205 |
+
final_signal = 'BUY' if buy_count > sell_count else 'SELL' if sell_count > buy_count else 'WAIT'
|
| 206 |
+
|
| 207 |
+
return {
|
| 208 |
+
'signal': final_signal,
|
| 209 |
+
'confidence': min(confidence, 0.9), # Cap at 90% for TA alone
|
| 210 |
+
'reason': " | ".join(reasons)
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
def combine_signals(self, ai_signal, ta_signal):
|
| 214 |
+
"""Combine AI and traditional TA signals with weighted confidence"""
|
| 215 |
+
if ai_signal['signal'] == 'WAIT' and ta_signal['signal'] == 'WAIT':
|
| 216 |
+
return {'signal': 'WAIT', 'confidence': 0, 'reason': 'No consensus'}
|
| 217 |
+
|
| 218 |
+
# Weighted combination (60% AI, 40% TA)
|
| 219 |
+
ai_weight = 0.6
|
| 220 |
+
ta_weight = 0.4
|
| 221 |
+
|
| 222 |
+
if ai_signal['signal'] == ta_signal['signal']:
|
| 223 |
+
combined_confidence = (ai_signal['confidence'] * ai_weight +
|
| 224 |
+
ta_signal['confidence'] * ta_weight)
|
| 225 |
+
return {
|
| 226 |
+
'signal': ai_signal['signal'],
|
| 227 |
+
'confidence': combined_confidence,
|
| 228 |
+
'reason': f"AI+TA Consensus: {ai_signal['reason']} & {ta_signal['reason']}"
|
| 229 |
+
}
|
| 230 |
+
else:
|
| 231 |
+
# When signals conflict, prefer AI with higher confidence
|
| 232 |
+
if ai_signal['confidence'] >= 0.7:
|
| 233 |
+
return ai_signal
|
| 234 |
+
elif ta_signal['confidence'] >= 0.7:
|
| 235 |
+
return ta_signal
|
| 236 |
+
else:
|
| 237 |
+
return {'signal': 'WAIT', 'confidence': 0, 'reason': 'Conflicting signals'}
|
| 238 |
+
|
| 239 |
+
async def execute_trade(self, signal):
|
| 240 |
+
"""Execute trade based on generated signal"""
|
| 241 |
+
# Check if this is a new signal
|
| 242 |
+
if self.last_signal == signal['signal']:
|
| 243 |
+
print(f"Maintaining existing {signal['signal']} position")
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
print(f"\n๐ Executing {signal['signal']} Signal ๐")
|
| 247 |
+
print(f"Confidence: {signal['confidence']*100:.1f}%")
|
| 248 |
+
print(f"Reason: {signal['reason']}")
|
| 249 |
+
print(f"Current Price: {self.current_price:.2f}")
|
| 250 |
+
|
| 251 |
+
# Calculate position size and risk parameters
|
| 252 |
+
stop_loss = self.calculate_stop_loss(signal['signal'])
|
| 253 |
+
take_profit = self.calculate_take_profit(signal['signal'], stop_loss)
|
| 254 |
+
position_size = self.calculate_position_size(stop_loss)
|
| 255 |
+
|
| 256 |
+
# Execute trade through broker API (pseudo-code)
|
| 257 |
+
trade_success = await self.send_to_broker(
|
| 258 |
+
symbol=self.symbol,
|
| 259 |
+
action=signal['signal'],
|
| 260 |
+
size=position_size,
|
| 261 |
+
stop_loss=stop_loss,
|
| 262 |
+
take_profit=take_profit
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
if trade_success:
|
| 266 |
+
self.last_signal = signal['signal']
|
| 267 |
+
await self.send_notification(
|
| 268 |
+
action=signal['signal'],
|
| 269 |
+
price=self.current_price,
|
| 270 |
+
stop_loss=stop_loss,
|
| 271 |
+
take_profit=take_profit,
|
| 272 |
+
confidence=signal['confidence'],
|
| 273 |
+
reason=signal['reason']
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
def calculate_stop_loss(self, signal_type):
|
| 277 |
+
"""Calculate stop loss based on ATR"""
|
| 278 |
+
if signal_type == 'BUY':
|
| 279 |
+
return self.current_price - (self.ohlc_data['atr'] * 1.5)
|
| 280 |
+
elif signal_type == 'SELL':
|
| 281 |
+
return self.current_price + (self.ohlc_data['atr'] * 1.5)
|
| 282 |
+
return None
|
| 283 |
+
|
| 284 |
+
def calculate_take_profit(self, signal_type, stop_loss):
|
| 285 |
+
"""Calculate take profit based on risk-reward ratio"""
|
| 286 |
+
if signal_type == 'BUY':
|
| 287 |
+
return self.current_price + abs(self.current_price - stop_loss) * self.take_profit_ratio
|
| 288 |
+
elif signal_type == 'SELL':
|
| 289 |
+
return self.current_price - abs(stop_loss - self.current_price) * self.take_profit_ratio
|
| 290 |
+
return None
|
| 291 |
+
|
| 292 |
+
def calculate_position_size(self, stop_loss):
|
| 293 |
+
"""Calculate position size based on account balance and risk"""
|
| 294 |
+
risk_amount = self.account_balance * self.risk_per_trade
|
| 295 |
+
risk_per_unit = abs(self.current_price - stop_loss)
|
| 296 |
+
|
| 297 |
+
if risk_per_unit == 0:
|
| 298 |
+
return 0
|
| 299 |
+
|
| 300 |
+
# For XAU/USD, 1 lot = 100 oz, price per pip is $0.10 for mini lots
|
| 301 |
+
position_size = (risk_amount / risk_per_unit) / 100
|
| 302 |
+
return round(position_size, 2) # Round to 2 decimal places
|
| 303 |
+
|
| 304 |
+
async def send_to_broker(self, **trade_params):
|
| 305 |
+
"""Placeholder for broker API integration"""
|
| 306 |
+
print(f"\n๐ Would execute trade with params:")
|
| 307 |
+
for k, v in trade_params.items():
|
| 308 |
+
print(f"{k}: {v}")
|
| 309 |
+
|
| 310 |
+
# In production, implement actual broker API calls here
|
| 311 |
+
# Example for MT5:
|
| 312 |
+
# mt5.initialize()
|
| 313 |
+
# request = {
|
| 314 |
+
# "action": mt5.TRADE_ACTION_DEAL,
|
| 315 |
+
# "symbol": trade_params['symbol'],
|
| 316 |
+
# "volume": trade_params['size'],
|
| 317 |
+
# "type": mt5.ORDER_TYPE_BUY if trade_params['action'] == 'BUY' else mt5.ORDER_TYPE_SELL,
|
| 318 |
+
# "price": trade_params['price'],
|
| 319 |
+
# "sl": trade_params['stop_loss'],
|
| 320 |
+
# "tp": trade_params['take_profit'],
|
| 321 |
+
# "deviation": 10,
|
| 322 |
+
# "magic": 123456,
|
| 323 |
+
# "comment": "Golden Maverick Trade",
|
| 324 |
+
# "type_time": mt5.ORDER_TIME_GTC,
|
| 325 |
+
# "type_filling": mt5.ORDER_FILLING_IOC,
|
| 326 |
+
# }
|
| 327 |
+
# result = mt5.order_send(request)
|
| 328 |
+
|
| 329 |
+
# Simulate success for demo
|
| 330 |
+
return True
|
| 331 |
+
|
| 332 |
+
async def send_notification(self, **kwargs):
|
| 333 |
+
"""Send trade notification via Telegram or other channels"""
|
| 334 |
+
message = (
|
| 335 |
+
f"๐ข New Trade Alert ๐ข\n\n"
|
| 336 |
+
f"Symbol: {self.symbol}\n"
|
| 337 |
+
f"Action: {kwargs['action']}\n"
|
| 338 |
+
f"Price: {kwargs['price']:.2f}\n"
|
| 339 |
+
f"Stop Loss: {kwargs['stop_loss']:.2f}\n"
|
| 340 |
+
f"Take Profit: {kwargs['take_profit']:.2f}\n"
|
| 341 |
+
f"Confidence: {kwargs['confidence']*100:.1f}%\n"
|
| 342 |
+
f"Reason: {kwargs['reason']}\n\n"
|
| 343 |
+
f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
print(f"\n๐ฉ Notification:\n{message}")
|
| 347 |
+
|
| 348 |
+
# Actual Telegram implementation would look like:
|
| 349 |
+
# if os.getenv('TELEGRAM_BOT_TOKEN'):
|
| 350 |
+
# bot = telegram.Bot(token=os.getenv('TELEGRAM_BOT_TOKEN'))
|
| 351 |
+
# await bot.send_message(
|
| 352 |
+
# chat_id=os.getenv('TELEGRAM_CHAT_ID'),
|
| 353 |
+
# text=message
|
| 354 |
+
# )
|
| 355 |
+
|
| 356 |
+
async def main():
|
| 357 |
+
bot = GoldenMaverick()
|
| 358 |
+
print("๐ฅ Golden Maverick AI Gold Trading Bot Activated ๐ฅ")
|
| 359 |
+
print(f"Tracking: {bot.symbol} | Timeframe: {bot.timeframe}")
|
| 360 |
+
await bot.fetch_market_data()
|
| 361 |
+
|
| 362 |
+
if __name__ == "__main__":
|
| 363 |
+
asyncio.run(main())
|
| 364 |
+
|
| 365 |
+
</html>
|
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
tradingview-ta==3.9.0
|
| 3 |
+
pandas==2.0.3
|
| 4 |
+
numpy==1.24.3
|
| 5 |
+
python-telegram-bot==20.4
|
| 6 |
+
matplotlib==3.7.2
|
| 7 |
+
tensorflow==2.12.0
|
| 8 |
+
scikit-learn==1.3.0
|
| 9 |
+
ta==0.10.2
|
| 10 |
+
websockets==11.0.3
|
| 11 |
+
python-dotenv==1.0.0
|
| 12 |
+
|
| 13 |
+
</html>
|