Python Al-sat Python botu sinyalleri yerinde yollamıyor

Rothanos

Hectopat
Katılım
8 Ocak 2021
Mesajlar
458
Çözümler
23
Yer
Bandırma
Öncelikle konuyu yanlış yere açmış olabilirim, açmışsam düzeltin, çok karmaşık konu olduğu için nereye açacağımı bilemedim.
1753993183005.png
Atmış olduğum grafikte yaptığım botta alış ya da satış sinyali geldiği gibi sinyal yollamasını istiyorum ama botum kırmızı yerlerden yolluyor, işlem ortası yolluyor yani işlem ortasında da işleme girilmez. Python kodlamasını bırakıyorum ( Telegram ve bybit apilerinin karşı yeri dolu normalde güvenlik amaçlı kaldırdım).

Python:
import ccxt.
import pandas as pd.
import numpy as np.
import time.
import datetime.
import ta.
import asyncio.
from telegram import Bot.
from telegram.error import TelegramError.

# --- Ayarlar ---
TIMEFRAME = '5m'.
LIMIT = 205.
UT_KEY = 2
UT_ATR = 1

# --- Telegram Ayarları ---
TELEGRAM_BOT_TOKEN =
TELEGRAM_CHAT_ID =

# Telegram Bot Nesnesi.
try:
 bot = Bot(token=TELEGRAM_BOT_TOKEN)
 print("Telegram bot nesnesi başarıyla oluşturuldu.")
except Exception as e:
 print(f"Telegram bot nesnesi oluşturulurken kritik hata: {e}")
 print("TELEGRAM_BOT_TOKEN'ınızın doğru olduğundan ve 'python-telegram-bot' kütüphanesinin yüklü olduğundan emin olun.")
 bot = None.

# --- Bybit Nesnesi ---
try:
 bybit = ccxt.bybit({
 'apiKey': ,
 'secret': ,
 'enableRateLimit': True,
 'options': {
 'defaultType': 'future',
 },
 'has': { 'fetchServerTime': True },
 })
 bybit.load_time_difference()
 print("Bybit nesnesi başarıyla oluşturuldu ve server zamanı senkronize edildi.")
except Exception as e:
 print(f"Bybit nesnesi oluşturulurken kritik hata: {e}")
 print("API anahtarlarınızın doğru ve geçerli olduğundan, ccxt kütüphanesinin yüklü olduğundan emin olun.")
 bybit = None.

# --- USDT Pariteleri ---
def get_usdt_pairs():
 if not bybit:
 return []
 try:
 markets = bybit.load_markets()
 return [s for s in markets if s.endswith('/USDT') and markets[s]['active']]
 except Exception as e:
 print(f"USDT pariteleri Bybit'ten çekilemedi: {e}")
 return []

# --- OHLCV Verisi ---
def fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=LIMIT):
 if not bybit:
 return None.
 try:
 data = bybit.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
 if not data:
 print(f"[{symbol}] Bybit'ten OHLCV verisi boş geldi.")
 return None.
 df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
 df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
 df.set_index('timestamp', inplace=True)
 return df.
 except Exception as e:
 print(f"[{symbol}] Bybit OHLCV verisi alınamadı: {e}")
 return None.

# === UT Bot ===
def apply_ut_bot(df, key_val=UT_KEY, atr_period=UT_ATR):
 if df.empty or len(df) < atr_period + 1:
 df['UT_Trailing_Stop'] = np.nan
 df['UT_Pos'] = np.nan
 df['ema1'] = np.nan
 df['UT_Buy'] = False.
 df['UT_Sell'] = False.
 return df.

 src = df['close']
 atr_series = ta.volatility.AverageTrueRange(df['high'], df['low'], src, window=atr_period).average_true_range()
 nLoss = key_val * atr_series.

 trailing_stop_list = []
 pos_list = []

 initial_stop = src.iloc[0]
 if not pd.isna(nLoss.iloc[0]):
 initial_stop = src.iloc[0] - nLoss.iloc[0] if src.iloc[0] > (src.iloc[0] - nLoss.iloc[0]) else src.iloc[0] + nLoss.iloc[0]
 trailing_stop_list.append(initial_stop)
 pos_list.append(0)

 for i in range(1, len(df)):
 prev_stop = trailing_stop_list[-1]
 current_src = src.iloc[i]
 prev_src = src.iloc[i-1]
 current_nLoss = nLoss.iloc[i]

 if pd.isna(current_nLoss):
 trailing_stop_list.append(prev_stop)
 pos_list.append(pos_list[-1])
 continue.

 if current_src > prev_stop and prev_src > prev_stop:
 trailing_stop_list.append(max(prev_stop, current_src - current_nLoss))
 elif current_src < prev_stop and prev_src < prev_stop:
 trailing_stop_list.append(min(prev_stop, current_src + current_nLoss))
 else:
 if current_src > prev_stop:
 trailing_stop_list.append(current_src - current_nLoss)
 else:
 trailing_stop_list.append(current_src + current_nLoss)

 if prev_src < trailing_stop_list[i-1] and current_src > trailing_stop_list[i]:
 pos_list.append(1)
 elif prev_src > trailing_stop_list[i-1] and current_src < trailing_stop_list[i]:
 pos_list.append(-1)
 else:
 pos_list.append(pos_list[-1])

 df['UT_Trailing_Stop'] = trailing_stop_list.
 df['UT_Pos'] = pos_list.
 df['ema1'] = src.

 df['UT_Buy'] = (src > df['UT_Trailing_Stop']) & (df['ema1'].shift(1) <= df['UT_Trailing_Stop'].shift(1))
 df['UT_Sell'] = (src < df['UT_Trailing_Stop']) & (df['ema1'].shift(1) >= df['UT_Trailing_Stop'].shift(1))

 df['UT_Buy'] = df['UT_Buy'].fillna(False)
 df['UT_Sell'] = df['UT_Sell'].fillna(False)

 return df.

# === Sinyal Kontrolü ===
def check_signals(df):
 required_data = UT_ATR + 3
 if df.empty or len(df) < required_data:
 return False, False, None, None.

 last_completed_bar = df.iloc[-3]

 ut_buy_signal = bool(last_completed_bar.get('UT_Buy', False))
 ut_sell_signal = bool(last_completed_bar.get('UT_Sell', False))

 signal_price = last_completed_bar['close']
 signal_stop = last_completed_bar.get('UT_Trailing_Stop')

 buy_final = ut_buy_signal.
 sell_final = ut_sell_signal.

 return buy_final, sell_final, signal_stop, signal_price.

# === Telegram'a Asenkron Mesaj Gönder ===
async def send_telegram_message(text):
 if bot:
 try:
 await bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=text, parse_mode='Markdown')
 print(f"Telegram'a başarıyla gönderildi: {text}")
 except TelegramError as e:
 print(f"Telegram'a mesaj gönderilirken hata oluştu: {e}")
 except Exception as e:
 print(f"Bilinmeyen bir hata oluştu: {e}")
 else:
 print("Telegram bot nesnesi başlatılamadı, mesaj gönderilemedi.")

# === Ana Bot Fonksiyonu ===
async def main_loop():
 if not bybit:
 print("Bybit nesnesi başlatılamadığı için bot çalıştırılamıyor.")
 return.

 last_position = {}
 entry_price = {}
 last_signal_time = {}

 while True:
 print(f"\n=== Yeni Bybit Tarama Başladı ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ===")
 pairs = get_usdt_pairs()
 print(f"Toplam {len(pairs)} aktif Bybit USDT çifti bulundu.")

 for p in pairs:
 if p not in last_position:
 last_position[p] = 'none'.
 if p not in entry_price:
 entry_price[p] = 0
 if p not in last_signal_time:
 last_signal_time[p] = datetime.datetime.fromtimestamp(0)

 for symbol in pairs:
 try:
 await asyncio.sleep(bybit.rateLimit / 1000)

 df = fetch_ohlcv(symbol, TIMEFRAME, LIMIT)

 if df is None or df.empty:
 print(f"[{symbol}] OHLCV verisi boş, atlanıyor.")
 continue.

 required_data_for_ind = UT_ATR + 3
 if len(df) < required_data_for_ind:
 print(f"[{symbol}] Yeterli OHLCV verisi (en az {required_data_for_ind} çubuk) Bybit'ten çekilemedi, atlanıyor.")
 continue.

 df = apply_ut_bot(df)

 buy, sell, signal_stop, signal_price = check_signals(df)

 if df.empty:
 print(f"[{symbol}] İşlem sonrası DataFrame boş kaldı, atlanıyor.")
 continue.

 signal_bar_time = df.index[-3]
 current_price = df.iloc[-1]['close']
 current_trailing_stop = df.iloc[-1].get('UT_Trailing_Stop')

 print(f"[{symbol}] Durum: Pozisyon: {last_position[symbol]}, Güncel Fiyat: {current_price:.12f}, Güncel Stop: {current_trailing_stop:.12f}, Buy Sinyal: {buy}, Sell Sinyal: {sell}")

 if last_position[symbol] == 'long' and not pd.isna(current_trailing_stop):
 if current_price < current_trailing_stop:
 msg = f"🛑 **STOP-LOSS** 🛑\n" \
 f"**Borsa:** Bybit\n" \
 f"**Sembol:** {symbol}\n" \
 f"**Pozisyon:** Long (Alım)\n" \
 f"**Çıkış Fiyatı:** {current_price:.12f}\n" \
 f"**Stop Seviyesi:** {current_trailing_stop:.12f}\n" \
 f"**Zaman Dilimi:** {TIMEFRAME}"
 print(msg)
 await send_telegram_message(msg)
 last_position[symbol] = 'none'.

 elif last_position[symbol] == 'short' and not pd.isna(current_trailing_stop):
 if current_price > current_trailing_stop:
 msg = f"🛑 **STOP-LOSS** 🛑\n" \
 f"**Borsa:** Bybit\n" \
 f"**Sembol:** {symbol}\n" \
 f"**Pozisyon:** Short (Satım)\n" \
 f"**Çıkış Fiyatı:** {current_price:.12f}\n" \
 f"**Stop Seviyesi:** {current_trailing_stop:.12f}\n" \
 f"**Zaman Dilimi:** {TIMEFRAME}"
 print(msg)
 await send_telegram_message(msg)
 last_position[symbol] = 'none'.

 elif last_position[symbol] == 'long' and sell:
 if signal_bar_time > last_signal_time[symbol]:
 msg = f"💸 **KAR AL (Take-Profit)** 💸\n" \
 f"**Borsa:** Bybit\n" \
 f"**Sembol:** {symbol}\n" \
 f"**Pozisyon:** Long (Alım)\n" \
 f"**Çıkış Fiyatı:** {current_price:.12f}\n" \
 f"**Giriş Fiyatı:** {entry_price[symbol]:.12f}\n" \
 f"**Zaman Dilimi:** {TIMEFRAME}"
 print(msg)
 await send_telegram_message(msg)
 last_position[symbol] = 'none'.
 last_signal_time[symbol] = signal_bar_time.

 elif last_position[symbol] == 'short' and buy:
 if signal_bar_time > last_signal_time[symbol]:
 msg = f"💸 **KAR AL (Take-Profit)** 💸\n" \
 f"**Borsa:** Bybit\n" \
 f"**Sembol:** {symbol}\n" \
 f"**Pozisyon:** Short (Satım)\n" \
 f"**Çıkış Fiyatı:** {current_price:.12f}\n" \
 f"**Giriş Fiyatı:** {entry_price[symbol]:.12f}\n" \
 f"**Zaman Dilimi:** {TIMEFRAME}"
 print(msg)
 await send_telegram_message(msg)
 last_position[symbol] = 'none'.
 last_signal_time[symbol] = signal_bar_time.

 if last_position[symbol] == 'none':
 if buy:
 if signal_bar_time > last_signal_time[symbol]:
 msg = f"🚀 **AL SİNYALİ** 🚀\n" \
 f"**Borsa:** Bybit\n" \
 f"**Sembol:** {symbol}\n" \
 f"**Fiyat:** {signal_price:.12f}\n" \
 f"**Stop Seviyesi:** {signal_stop:.12f}\n" \
 f"**Zaman Dilimi:** {TIMEFRAME}"
 print(msg)
 await send_telegram_message(msg)
 last_position[symbol] = 'long'.
 entry_price[symbol] = signal_price.
 last_signal_time[symbol] = signal_bar_time.

 elif sell:
 if signal_bar_time > last_signal_time[symbol]:
 msg = f"🔻 **SAT SİNYALİ** 🔻\n" \
 f"**Borsa:** Bybit\n" \
 f"**Sembol:** {symbol}\n" \
 f"**Fiyat:** {signal_price:.12f}\n" \
 f"**Stop Seviyesi:** {signal_stop:.12f}\n" \
 f"**Zaman Dilimi:** {TIMEFRAME}"
 print(msg)
 await send_telegram_message(msg)
 last_position[symbol] = 'short'.
 entry_price[symbol] = signal_price.
 last_signal_time[symbol] = signal_bar_time.

 except Exception as e:
 print(f"[{symbol}] koinini işlerken beklenmedik bir hata oluştu: {e}")
 continue.

 print(f"\n=== Bybit Tarama Tamamlandı ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ===")

 if TIMEFRAME.endswith('m'):
 sleep_minutes = int(TIMEFRAME[:-1])
 elif TIMEFRAME.endswith('h'):
 sleep_minutes = int(TIMEFRAME[:-1]) * 60.
 else:
 sleep_minutes = 60.

 print(f"Sonraki tarama {sleep_minutes} dakika sonra...")
 await asyncio.sleep(sleep_minutes * 60)

# --- Botu Başlat ---
if __name__ == "__main__":
 try:
 asyncio.run(main_loop())
 except KeyboardInterrupt:
 print("Bot kullanıcı tarafından durduruldu.")
 except Exception as e:
 print(f"Bot çalışırken beklenmedik bir hata oluştu: {e}")
 

Technopat Haberler

Yeni konular

Geri
Yukarı