import MetaTrader5 as mt5
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mplfinance as mpf
from ta.momentum import RSIIndicator
from ta.volatility import BollingerBands
from ta.trend import MACD, CCIIndicator
import winsound
import time

# Definir o símbolo globalmente
symbol = "EURUSD"

# Função para emitir um som de alerta
def play_alert():
    for _ in range(3):
        winsound.Beep(1000, 500)  # Frequência de 1000Hz por 500ms
        time.sleep(0.5)

# Função para conectar ao MetaTrader 5 e obter dados
def fetch_data():
    if not mt5.initialize():
        print("Falha ao inicializar MetaTrader 5")
        mt5.shutdown()
        return None

    timeframe = mt5.TIMEFRAME_H1
    n_bars = 500

    rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, n_bars)
    mt5.shutdown()

    data = pd.DataFrame(rates)
    data['time'] = pd.to_datetime(data['time'], unit='s')
    data.set_index('time', inplace=True)

    if 'volume' not in data.columns:
        data['volume'] = 0

    data['RSI'] = RSIIndicator(data['close'], window=14).rsi()
    data['MA'] = data['close'].rolling(window=50).mean()
    bollinger = BollingerBands(data['close'], window=20, window_dev=2)
    data['BB_High'] = bollinger.bollinger_hband()
    data['BB_Low'] = bollinger.bollinger_lband()
    macd = MACD(data['close'], window_slow=26, window_fast=12, window_sign=9)
    data['MACD'] = macd.macd()
    data['MACD_Signal'] = macd.macd_signal()
    data['CCI'] = CCIIndicator(data['high'], data['low'], data['close'], window=14).cci()

    return data

# Função para gerar sinais de compra/venda
def generate_signals(data):
    buy_signals = []
    sell_signals = []
    for i in range(len(data)):
        if (data['RSI'][i] < 30 and data['close'][i] > data['MA'][i] and
            data['MACD'][i] > data['MACD_Signal'][i] and data['close'][i] < data['BB_Low'][i] and
            data['CCI'][i] < -100):
            buy_signals.append((data.index[i], data['close'][i]))
        elif (data['RSI'][i] > 70 and data['close'][i] < data['MA'][i] and
              data['MACD'][i] < data['MACD_Signal'][i] and data['close'][i] > data['BB_High'][i] and
              data['CCI'][i] > 100):
            sell_signals.append((data.index[i], data['close'][i]))
    return buy_signals, sell_signals

# Função para plotar os dados
def plot_data(data, buy_signals, sell_signals, symbol):
    # Plot das velas
    apds = [
        mpf.make_addplot(data['MA'], color='orange', linestyle='--'),  # Média Móvel
    ]
    
    # Adicionar sinais de compra e venda
    buy_dates, buy_prices = zip(*buy_signals) if buy_signals else ([], [])
    sell_dates, sell_prices = zip(*sell_signals) if sell_signals else ([], [])
    apds.append(mpf.make_addplot(data['close'], type='scatter', markersize=100, marker='^', color='green', series=data.index.isin(buy_dates)))
    apds.append(mpf.make_addplot(data['close'], type='scatter', markersize=100, marker='v', color='red', series=data.index.isin(sell_dates)))
    
    mpf.plot(data, type='candle', style='charles', volume=True, title=symbol, ylabel='Preço', ylabel_lower='Volume', show_nontrading=True, addplot=apds)

# Loop de atualização
def main_loop():
    previous_buy_signals = []
    previous_sell_signals = []

    while True:
        data = fetch_data()
        if data is None:
            break

        buy_signals, sell_signals = generate_signals(data)

        # Verificar se há novos sinais e emitir alerta
        if buy_signals and buy_signals != previous_buy_signals:
            play_alert()
        if sell_signals and sell_signals != previous_sell_signals:
            play_alert()

        # Plotar dados
        plot_data(data, previous_buy_signals + buy_signals, previous_sell_signals + sell_signals, symbol)

        # Atualizar sinais anteriores
        previous_buy_signals = buy_signals
        previous_sell_signals = sell_signals

        time.sleep(60)  # Esperar 60 segundos antes de atualizar

if __name__ == "__main__":
    main_loop()


nao esta mostrando no grafico sinais de compra e venda