erro:
eger keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use ser.iloc[pos]
ax1.scatter(signals.index[i], signals['open_price'][i], marker='v', color='red', label='Venda')
D:\Tudo Sobre Python Software\SMART MONEY\Ultima Versao\O Melhor ate agora\Com Liquidez\Smart_Money_Liquidez_07_HWID_UPDATE_02_HUNG.py:272: FutureWarning: Series.getitem treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use ser.iloc[pos]
ax1.text(signals.index[i], signals['open_price'][i], f'Open: {signals["open_price"][i]:.5f}\nTP: {signals["tp"][i]:.5f}\nSL: {signals["sl"][i]: .5f}', fontsize=10, ha='center', va='top', color='red')
D:\Tudo Sobre Python Software\SMART MONEY\Ultima Versao\O Melhor ate agora\Com Liquidez\Smart_Money_Liquidez_07_HWID_UPDATE_02_HUNG.py:280: FutureWarning: Series.getitem treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use ser.iloc[pos]
ax1.text(signals.index[i], data['high'][i], signals['liquidity_message'][i], color='blue', ha='left')
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 1968, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 862, in callit
func(*args)
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\backends_backend_tk.py", line 142, in _on_timer
super()._on_timer()
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\backend_bases.py", line 1193, in _on_timer
ret = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1427, in _step
still_going = super()._step(*args)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1121, in _step
self._draw_next_frame(framedata, self._blit)
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1140, in _draw_next_frame
self._draw_frame(framedata)
File "C:\Users\Wendel\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py", line 1766, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Tudo Sobre Python Software\SMART MONEY\Ultima Versao\O Melhor ate agora\Com Liquidez\Smart_Money_Liquidez_07_HWID_UPDATE_02_HUNG.py", line 289, in plot_chart_with_signals
if new_signals_detected:
^^^^^^^^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'new_signals_detected' where it is not associated with a value
Assistant
meu codigo abaixo:
import MetaTrader5 as mt5
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import time
import threading
import matplotlib.dates as mdates
import requests
import hashlib
import wmi
from matplotlib.animation import FuncAnimation
import winsound
def get_hwid():
c = wmi.WMI()
serial_number = None
for disk in c.Win32_DiskDrive():
serial_number = disk.SerialNumber.strip()
break
if serial_number is None:
raise ValueError("Não foi possível Gerar o HWID.")
uuid_hash = hashlib.md5(serial_number.encode('utf-8')).hexdigest()
formatted_uuid = f"{uuid_hash[:8]}-{uuid_hash[8:12]}-{uuid_hash[12:16]}-{uuid_hash[16:20]}-{uuid_hash[20:]}"
return formatted_uuid
Função para verificar HWID localmente
def check_hwid_local(hwid):
hwids_autorizados = [
"", # Adicione os HWIDs autorizados aqui
]
return hwid in hwids_autorizados
Função para verificar HWID online
def check_hwid_online(hwids_url, hwid):
try:
response = requests.get(hwids_url)
if response.status_code == 200:
hwids = response.text.strip().split('\n')
if hwid in hwids:
return True
else:
return False
else:
print(f"Erro ao acessar Link: {response.status_code}")
return False
except requests.exceptions.RequestException as e:
print(f"Erro de requisição: {e}")
return False
hwid = get_hwid()
if not check_hwid_local(hwid):
if not check_hwid_online(hwids_url, hwid):
print(f"HWID do cliente: {hwid}")
input("HWID não autorizado. Envie o Numero HWID para o vendedor…")
quit()
Conectando ao MetaTrader 5
if not mt5.initialize():
print("initialize() failed, error code =", mt5.last_error())
quit()
Função para selecionar o par de moedas
def select_symbol():
symbols = ["EURUSD", "GBPUSD", "USDJPY", "USDCHF", "AUDUSD", "USDCAD", "NZDUSD"]
print("Escolha o par de moedas:")
for i, symbol in enumerate(symbols, 1):
print(f"{i} {symbol}")
choice = int(input("Digite o número correspondente ao par de moedas: "))
return symbols[choice - 1]
Função para selecionar o timeframe
def select_timeframe():
timeframes = {
1: ("15 Minutos", mt5.TIMEFRAME_M15),
2: ("30 Minutos", mt5.TIMEFRAME_M30),
3: ("1 Hora", mt5.TIMEFRAME_H1),
4: ("4 Horas", mt5.TIMEFRAME_H4),
5: ("1 Dia", mt5.TIMEFRAME_D1),
6: ("1 Semana", mt5.TIMEFRAME_W1),
7: ("1 Mês", mt5.TIMEFRAME_MN1)
}
print("Escolha o timeframe:")
for key, (name, _) in timeframes.items():
print(f"{key} {name}")
choice = int(input("Digite o número correspondente ao timeframe: "))
return timeframes[choice][1]
Selecionar o ativo e timeframe
symbol = select_symbol()
timeframe = select_timeframe()
mt5.symbol_select(symbol, True)
def calculate_rsi(series, period=14):
delta = series.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
return 100 - (100 / (1 + rs))
Função para calcular a volatilidade
def calculate_volatility(data, window=20):
data['volatility'] = data['close'].rolling(window=window).std()
return data
Lógica para detectar sinais de compra ou venda
def detect_signals(data):
order_blocks = find_order_blocks(data)
data = calculate_fvg(data)
data = detect_bos_choch(data)
data = identify_market_structure(data)
data = identify_liquidity_zones(data)
data = detect_engulfing_patterns(data)
data = apply_technical_indicators(data)
ani = FuncAnimation(fig, plot_chart_with_signals, interval=60000)
plt.show()
Aparentemente, você está enfrentando dois problemas diferentes no seu código:
Uso depreciado de chaves inteiras em pandas.Series:
FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use ser.iloc[pos]
Este aviso é causado pelo uso de signals['open_price'][i], onde i é um índice inteiro e o pandas está avisando que isso pode se tornar um problema em versões futuras. Para evitar isso, você deve usar iloc para acessar valores por posição.
Variável new_signals_detected não definida:
UnboundLocalError: cannot access local variable 'new_signals_detected' where it is not associated with a value
Esta exceção ocorre porque a variável new_signals_detected não foi definida antes de ser utilizada. Para resolver isso, você deve definir a variável antes de usá-la.
Para corrigir esses problemas, você pode modificar o seu código da seguinte forma:
Utilize iloc para acessar valores por posição:
Certifique-se de que new_signals_detected esteja sempre definida, independentemente de novas detecções de sinais.
Abaixo está a versão corrigida do método de plotagem:
# Função para plotar gráfico de candlestick com sinais e volatilidade
def plot_chart_with_signals(i):
global data, last_signal_index
update_data()
signals = detect_signals(data)
data = calculate_volatility(data)
volatility_state = get_volatility_state(data)
ax1.clear()
ax2.clear()
ax1.set_title(volatility_state)
time_delta = data.index[1] - data.index[0]
width = time_delta.total_seconds() / (24 * 60 * 60) * 0.8
ax1.bar(data.index, data['close'] - data['open'], width=width, bottom=data['open'], color='black', align='center', label='Candlestick')
ax1.vlines(data.index, data['low'], data['high'], color='black', linewidth=1)
new_signals_detected = False # Inicializa como False
for i in range(len(signals)):
if signals['signal'].iloc[i] == 1:
ax1.scatter(signals.index[i], signals['open_price'].iloc[i], marker='^', color='green', label='Compra')
ax1.text(signals.index[i], signals['open_price'].iloc[i], f'Open: {signals["open_price"].iloc[i]:.5f}\nTP: {signals["tp"].iloc[i]:.5f}\nSL: {signals["sl"].iloc[i]:.5f}', fontsize=10, ha='center', va='bottom', color='green')
if last_signal_index is None or signals.index[i] > last_signal_index:
new_signals_detected = True
elif signals['signal'].iloc[i] == -1:
ax1.scatter(signals.index[i], signals['open_price'].iloc[i], marker='v', color='red', label='Venda')
ax1.text(signals.index[i], signals['open_price'].iloc[i], f'Open: {signals["open_price"].iloc[i]:.5f}\nTP: {signals["tp"].iloc[i]:.5f}\nSL: {signals["sl"].iloc[i]:.5f}', fontsize=10, ha='center', va='top', color='red')
if last_signal_index is None or signals.index[i] > last_signal_index:
new_signals_detected = True
# Adicionar mensagem de liquidez apenas no último sinal
if signals['liquidity_message'].iloc[i]:
ax1.text(signals.index[i], data['high'].iloc[i], signals['liquidity_message'].iloc[i], color='blue', ha='left')
# Atualizar o índice do último sinal verificado
if not signals.empty:
last_signal_index = signals.index[-1]
# Emitir beeps se novos sinais foram detectados
if new_signals_detected:
for _ in range(3):
winsound.Beep(1000, 500)
ax1.set_xlabel('Data')
ax1.set_ylabel('Preço')
ax1.legend(loc='upper left')
ax1.grid(True)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
ax2.plot(data.index, data['volatility'], label='Volatilidade')
ax2.set_xlabel('Data')
ax2.set_ylabel('Volatilidade')
ax2.legend(loc='upper left')
ax2.grid(True)
Nessa modificação:
signals['open_price'][i] foi substituído por signals['open_price'].iloc[i].
A variável new_signals_detected é inicializada como False antes de qualquer uso.
Essas mudanças devem corrigir os problemas que você estava enfrentando.