Untitled
plain_text
a month ago
32 kB
0
Indexable
Never
from concurrent.futures import thread from zlib import Z_BEST_COMPRESSION, Z_BEST_SPEED, Z_BLOCK import requests from tradingview_ta import TA_Handler, Interval import time from datetime import datetime import requests import pandas as pd import threading import plotly.graph_objects as go # pip install plotly==5.10.0 import vectorbt as vbt import pandas_ta as ta import webbrowser import numpy as np import math from prophet import Prophet from prophet.plot import plot_plotly, plot_components_plotly import matplotlib.pyplot as plt import matplotlib.image as mpimg import mplfinance as mpf import yfinance as yf import pytz print("Başlıyoruz...") pd.set_option('display.max_rows', None) now = datetime.now() zaman = now.strftime("%d-%m-%y %H:%M:%S") url = "https://fapi.binance.com/fapi/v1/ticker/24hr" r = requests.get(url) result = r.json() symbols = [] for i in result: vol = i['volume'] sembol = i['symbol'] symbols.append(sembol) while True: print("DENİZHAN TOY COİN TARAMA PROGRAMINA HOŞ GELDİNİZ MENU YU KULLANMAK İÇİN NUMARA GİRMELİSİNİZ", "\n MENU 0 == exit" "\n MENU 1 == 5 DK RSI TARAMA " "\n MENU 2 == ADX TARAMA" "\n MENU 3 == 1 Dk ARTIŞ TARAMA" "\n MENU 4 == COİN SORGULA" "\n MENU 5 == GENEL SORGULAMA" "\n MENU 6 == 4 SAATLİK RSI + MA + DESTEK DİRENÇ" "\n MENU 7 == GRAFİK BAKAR" "\n MENU 8 == RSI modul" "\n MENU 9 == BACKTEST modul") menu = input('Yapmak istediğiniz işlemi seçiniz:') def rsiscan(): yuksek = [] alcak = [] for i in symbols: tesla = TA_Handler() tesla.set_symbol_as(i) tesla.set_exchange_as_crypto_or_stock("BINANCE") tesla.set_screener_as_crypto() tesla.set_interval_as(Interval.INTERVAL_5_MINUTES) try: analiz = tesla.get_analysis() ta = tesla.get_indicators() #print(i,analiz.indicators['change']) except Exception as e: continue if (ta['RSI'] <= 30) & (ta['RSI[1]'] >= 30): yuksek.append({"symbols":i,"PRİCE": ta['close'],"SMA10" : ta['SMA10'], "SMA20": ta['SMA20'],"BOL": ta['BB.upper'],"RSI":ta['RSI'],"ADX+DI":ta['ADX+DI'],"ADX-DI":ta['ADX-DI'],"support":ta['Pivot.M.Fibonacci.S1'],"resisdant":ta['Pivot.M.Fibonacci.R1']}) if (ta['RSI'] > 70) & (ta['RSI[1]'] < 70): alcak.append({"symbols":i,"PRİCE": ta['close'],"SMA10" : ta['SMA10'], "SMA20": ta['SMA20'],"BOL": ta['BB.upper'],"RSI":ta['RSI'],"ADX+DI":ta['ADX+DI'],"ADX-DI":ta['ADX-DI'],"support":ta['Pivot.M.Fibonacci.S1'],"resisdant":ta['Pivot.M.Fibonacci.R1']}) elif "": print("Başka yok... Dönüyoruz") dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) print("AL") print(data.to_markdown()) print("SAT") print(data2.to_markdown()) def artis1(): for i in symbols: tesla = TA_Handler() tesla.set_symbol_as(i) tesla.set_exchange_as_crypto_or_stock("BINANCE") tesla.set_screener_as_crypto() tesla.set_interval_as(Interval.INTERVAL_1_MINUTE) try: analiz = tesla.get_analysis() ta = tesla.get_indicators() #print(i,analiz.indicators['change']) except Exception as e: continue if ta['change'] > 1: print(i,ta['change']) print(f" 5 dakikalık {i}",{"symbols":i,"PRİCE": ta['close'],"SMA10" : ta['SMA10'], "SMA20": ta['SMA20'],"BOL": ta['BB.upper'],"RSI":ta['RSI'],"ADX+DI":ta['ADX+DI'],"ADX-DI":ta['ADX-DI'],"support":ta['Pivot.M.Fibonacci.S1'],"resisdant":ta['Pivot.M.Fibonacci.R1']}) if ta['change'] < -1: print(i,ta['change']) print(f"5 dakikalık {i}",{"symbols":i,"PRİCE": ta['close'],"SMA10" : ta['SMA10'], "SMA20": ta['SMA20'],"BOL": ta['BB.upper'],"RSI":ta['RSI'],"ADX+DI":ta['ADX+DI'],"ADX-DI":ta['ADX-DI'],"support":ta['Pivot.M.Fibonacci.S1'],"resisdant":ta['Pivot.M.Fibonacci.R1']}) def artis5(): yuksek = [] alcak = [] for i in symbols: tesla = TA_Handler() tesla.set_symbol_as(i) tesla.set_exchange_as_crypto_or_stock("BINANCE") tesla.set_screener_as_crypto() tesla.set_interval_as(Interval.INTERVAL_5_MINUTES) try: analiz = tesla.get_analysis() ta = tesla.get_indicators() except Exception as e: continue if (ta['ADX+DI'] > ta['ADX-DI']) & (ta['ADX+DI[1]'] < ta['ADX-DI[1]']): yuksek.append({"symbols":i,"PRİCE": ta['close'],"SMA10" : ta['SMA10'], "SMA20": ta['SMA20'],"BOL": ta['BB.upper'],"RSI":ta['RSI'],"ADX+DI":ta['ADX+DI'],"ADX-DI":ta['ADX-DI'],"support":ta['Pivot.M.Fibonacci.S1'],"resisdant":ta['Pivot.M.Fibonacci.R1']}) if (ta['ADX+DI'] < ta['ADX-DI']) & (ta['ADX+DI[1]'] > ta['ADX-DI[1]']): alcak.append({"symbols":i,"PRİCE": ta['close'],"SMA10" : ta['SMA10'], "SMA20": ta['SMA20'],"BOL": ta['BB.upper'],"RSI":ta['RSI'],"ADX+DI":ta['ADX+DI'],"ADX-DI":ta['ADX-DI'],"support":ta['Pivot.M.Fibonacci.S1'],"resisdant":ta['Pivot.M.Fibonacci.R1']}) elif "": print("Başka yok... Dönüyoruz") dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) print("AL") print(data.to_markdown()) print("SAT") print(data2.to_markdown()) def sorgu(): sembol = input('SORMAK İSTEDİĞİN COİN? :').upper()+"USDT" yuksek = [] alcak = [] day = TA_Handler(symbol=sembol,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_1_DAY) four = TA_Handler(symbol=sembol,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_4_HOURS) hour = TA_Handler(symbol=sembol,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_1_HOUR) fiveteen = TA_Handler(symbol=sembol,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_15_MINUTES) five = TA_Handler(symbol=sembol,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_5_MINUTES) try: recoday = day.get_analysis().summary["RECOMMENDATION"] recofour = four.get_analysis().summary["RECOMMENDATION"] recohour = hour.get_analysis().summary["RECOMMENDATION"] recofiveteen = fiveteen.get_analysis().summary["RECOMMENDATION"] recofive = five.get_analysis().summary["RECOMMENDATION"] ta = five.get_indicators() destek1 = ta['Pivot.M.Fibonacci.S1'] destek2 = ta['Pivot.M.Fibonacci.S2'] destek3 = ta['Pivot.M.Fibonacci.S3'] orta = ta['Pivot.M.Fibonacci.Middle'] direnc1 = ta['Pivot.M.Fibonacci.R1'] direnc2 = ta['Pivot.M.Fibonacci.R2'] direnc3 = ta['Pivot.M.Fibonacci.R3'] except Exception as e: pass # print({"SYMBOL":i,"FİYAT":ta['close'],"REC5M":reco}) if "BUY" in recoday: yuksek.append({"SYMBOL":sembol,"FİYAT":ta['close'],"REC5M":recofive,"REC15M":recofiveteen,"REC1H":recohour,"REC4H":recofour,"destek1":destek1,"destek2":destek2,"destek3":destek3,"orta":orta,"direnc1":direnc1,"direnc2":direnc2,"direnc3":direnc3}) if "SELL" in recoday : # print({"SYMBOL":i,"FİYAT":ta['close'],"REC5M":reco}) alcak.append({"SYMBOL":sembol,"FİYAT":ta['close'],"REC5M":recofive,"REC15M":recofiveteen,"REC1H":recohour,"REC4H":recofour,"destek1":destek1,"destek2":destek2,"destek3":destek3,"orta":orta,"direnc1":direnc1,"direnc2":direnc2,"direnc3":direnc3}) elif "": print("Başka yok... Dönüyoruz") dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) print(data.to_markdown()) print(data2.to_markdown()) def genel(): yuksek = [] alcak = [] for i in symbols: day = TA_Handler(symbol=i,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_1_DAY) four = TA_Handler(symbol=i,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_4_HOURS) hour = TA_Handler(symbol=i,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_1_HOUR) fiveteen = TA_Handler(symbol=i,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_15_MINUTES) five = TA_Handler(symbol=i,screener="crypto",exchange="BINANCE",interval=Interval.INTERVAL_5_MINUTES) try: recoday = day.get_analysis().summary["RECOMMENDATION"] recofour = four.get_analysis().summary["RECOMMENDATION"] recohour = hour.get_analysis().summary["RECOMMENDATION"] recofiveteen = fiveteen.get_analysis().summary["RECOMMENDATION"] recofive = five.get_analysis().summary["RECOMMENDATION"] ta = five.get_indicators() destek1 = ta['Pivot.M.Fibonacci.S1'] destek2 = ta['Pivot.M.Fibonacci.S2'] destek3 = ta['Pivot.M.Fibonacci.S3'] orta = ta['Pivot.M.Fibonacci.Middle'] direnc1 = ta['Pivot.M.Fibonacci.R1'] direnc2 = ta['Pivot.M.Fibonacci.R2'] direnc3 = ta['Pivot.M.Fibonacci.R3'] except Exception as e: continue if recoday == "STRONG_BUY": # print({"SYMBOL":i,"FİYAT":ta['close'],"REC5M":reco}) yuksek.append({"SYMBOL":i,"FİYAT":ta['close'],"REC5M":recofive,"REC15M":recofiveteen,"REC1H":recohour,"REC4H":recofour,"destek1":destek1,"destek2":destek2,"destek3":destek3,"orta":orta,"direnc1":direnc1,"direnc2":direnc2,"direnc3":direnc3}) if recoday == "STRONG_SELL": # print({"SYMBOL":i,"FİYAT":ta['close'],"REC5M":reco}) yuksek.append({"SYMBOL":i,"FİYAT":ta['close'],"REC5M":recofive,"REC15M":recofiveteen,"REC1H":recohour,"REC4H":recofour,"destek1":destek1,"destek2":destek2,"destek3":destek3,"orta":orta,"direnc1":direnc1,"direnc2":direnc2,"direnc3":direnc3}) elif "": print("Başka yok... Dönüyoruz") dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) dfy = pd.DataFrame.from_dict(yuksek) dfa = pd.DataFrame.from_dict(alcak) data = pd.DataFrame(dfy) data2 = pd.DataFrame(dfa) print("AL") print(data.to_markdown()) print("SAT") print(data2.to_markdown()) def grafik(): chart = input('Sembol giriniz:').upper()+"USDT" print("ZAMAN DİLİMİ") print("örnek olarak", "\n 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo") interva = input('zaman dilimi giriniz:') limits = '1000' url2 = 'https://api.binance.com/api/v3/klines?symbol='+chart+'&interval='+interva+'&limit='+limits r = requests.get(url2) results = r.json() df = pd.DataFrame(results, columns=['dateTime', 'open', 'high', 'low', 'close', 'volume', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol', 'takerBuyQuoteVol', 'ignore']) df.dateTime = pd.to_datetime(df.dateTime, unit='ms') df.closeTime = pd.to_datetime(df.closeTime, unit='ms') def calculate_window(df): window = 0 previous_color = None for i in range(len(df)): df['open'] = pd.to_numeric(df['open'], errors='coerce') df['close'] = pd.to_numeric(df['close'], errors='coerce') df['high'] = pd.to_numeric(df['high'], errors='coerce') df['low'] = pd.to_numeric(df['low'], errors='coerce') heikin_ashi_candle = (df['open'][i] + df['close'][i] + df['high'][i] + df['low'][i]) / 4 if i == 0: df.loc[i, 'ha_close'] = df['close'][i] df.loc[i, 'ha_open'] = df['open'][i] else: df.loc[i, 'ha_close'] = (df['close'][i] + df['close'][i - 1] + df['open'][i - 1] + df['open'][i]) / 4 df.loc[i, 'ha_open'] = (df['open'][i - 1] + df['ha_close'][i]) / 2 df.loc[i, 'ha_high'] = max(df['high'][i], df['ha_open'][i], df['ha_close'][i]) df.loc[i, 'ha_low'] = min(df['low'][i], df['ha_open'][i], df['ha_close'][i]) if df.loc[i, 'ha_close'] > df.loc[i, 'ha_open']: df.loc[i, 'heikin_ashi'] = 'green' else: df.loc[i, 'heikin_ashi'] = 'red' for i in range(1, len(df)): if df['heikin_ashi'][i] == 'green' and previous_color == 'red': window += 1 previous_color = df['heikin_ashi'][i] return window window = calculate_window(df) def find_support_resistance(df, window=window,pct_change =0.05): rolling_max = df['high'].rolling(window=window).max() rolling_min = df['low'].rolling(window=window).min() df['support'] = rolling_min df['resistance'] = rolling_max df['new_resistance'] = df['resistance'].shift(1) df.loc[df['resistance']<df['new_resistance'], 'new_resistance'] = df['resistance'] return df df = find_support_resistance(df, window=window,pct_change = 0.05) plt.plot(df['dateTime'], df['high'], color='red') plt.plot(df['dateTime'], df['low'], color='green') plt.plot(df['dateTime'], df['close'], color='purple') plt.plot(df['dateTime'], df['open'], color='green') plt.plot(df['dateTime'], df['support'], color='green') plt.plot(df['dateTime'], df['resistance'], color='red') plt.xlabel('Tarih') plt.ylabel('Fiyat') plt.title('Destek ve Direnç Noktaları') plt.show() sor = input('GRAFİK AÇILSINMI? E/H ?:').upper() if sor == "E": url = 'https://www.binance.com/en/futures/'+chart print(url) webbrowser.open(url) else: "Grafik açıldı kapanıyor." def destek(): yuksek = [] alcak = [] indicators = [] for i in symbols: tesla = TA_Handler() tesla.set_symbol_as(i) tesla.set_exchange_as_crypto_or_stock("BINANCE") tesla.set_screener_as_crypto() tesla.set_interval_as(Interval.INTERVAL_4_HOURS) try: analiz = tesla.get_analysis() ta = tesla.get_indicators() destek1 = ta['Pivot.M.Fibonacci.S1'] destek2 = ta['Pivot.M.Fibonacci.S2'] destek3 = ta['Pivot.M.Fibonacci.S3'] orta = ta['Pivot.M.Fibonacci.Middle'] direnc1 = ta['Pivot.M.Fibonacci.R1'] direnc2 = ta['Pivot.M.Fibonacci.R2'] direnc3 = ta['Pivot.M.Fibonacci.R3'] fiyat = ta['close'] except Exception as e: continue if ta['RSI'] > 70: yuksek.append({"symbol": i,"Price":fiyat, "RSI":ta['RSI'],"MA10":ta['SMA10'],"MA20":ta['SMA20'],"MA30":ta['SMA30'],"MA50": ta['SMA50'], "MA100":ta['SMA100'],"Destek1":destek1,"Direnç1":direnc1}) if ta['RSI'] < 30: alcak.append({"symbol": i,"Price":fiyat, "RSI":ta['RSI'],"MA10":ta['SMA10'],"MA20":ta['SMA20'],"MA30":ta['SMA30'],"MA50": ta['SMA50'], "MA100":ta['SMA100'],"Destek1" :destek1,"Direnç1":direnc1}) bouth = pd.DataFrame.from_dict(yuksek) sold = pd.DataFrame.from_dict(alcak) markbouth = bouth.to_markdown(tablefmt="grid") marksold = sold.to_markdown(tablefmt="grid") print("YÜKSEKLER:") print(bouth) print("ALÇAKLAR") print(sold) def rsimodul(): print("RSİ MODULU ÇALIŞTIRILIYOR") while True: print("DENİZHAN TOY COİN TARAMA PROGRAMINA HOŞ GELDİNİZ MENU YU KULLANMAK İÇİN NUMARA GİRMELİSİNİZ", "\n MENU 0 == BACK" "\n MENU 1 == 5 DK RSI 70 ÜSTÜ " "\n MENU 2 == 5 Dk RSI 30 ALTI" "\n MENU 3 == 15 DK RSI 70 ÜSTÜ" "\n MENU 4 == 15 Dk RSI 30 ALTICOİN SORGULA" "\n MENU 5 == TEKNİĞİ İYİ OLANLAR" "\n MENU 6 == YUKSELENLER" "\n MENU 7 == 1 SAATLİK DESTEKDE" "\n MENU 8 == 1 SAATLİK DİRENCDE" "\n MENU 9 == GÜVENİLİR OLANLAR" "\n MENU E == EXİT") menu = input('Yapmak istediğiniz işlemi seçiniz:') url = "https://quantifycrypto.com/api/v1.0/common/init-table?currency=USD&fields=qc_key,price_usd,price5min,rsi5min,rsi15min,atr5min,atr15min,&exchange=binance" result = requests.get(url).json() df = pd.DataFrame.from_dict(result['data']) new_cols = ["qc_key","price_usd","rsi5min","rsi15min","atr5min","atr15min"] df=df.reindex(columns=new_cols) # df = df.apply(pd.to_numeric, errors='coerce').round(2) def guven(): print("YUKSEK GUVENLİLER") url = "https://quantifycrypto.com/api/v1.0/common/init-table?currency=USD&fields=qc_key,safe_score,price5min,rsi5min,rsi15min,atr5min,atr15min,&exchange=binance" result = requests.get(url).json() df = pd.DataFrame.from_dict(result['data']) new_cols = ["qc_key","price_usd","rsi5min","rsi15min","safe_score","atr5min","atr15min"] df=df.reindex(columns=new_cols) print(df.loc[df['safe_score'] > 65]) def rsi5minover(): print("OVERBOTH") print("rsi5min") print(df.loc[df['rsi5min'] > 70]) def rsi5minsold(): print("OVERBOTH") print("rsi5min") print(df.loc[df['rsi5min'] < 30]) def rsi15minover(): print("OVERBOTH") print("rsi15min") print(df.loc[df['rsi15min'] > 70]) def rsi15minsold(): print("OVERBOTH") print("rsi15min") print(df.loc[df['rsi15min'] < 30]) def teknik(): print("teknikskor") print("YUKSEK OLANLAR") print(df.loc[df['technical_score'] > 75]) def price(): print("YUKSELENLER") print(df.loc[df['price5min'] > 0.001]) def destek(): print("Destekde olanlar") filtered_df = df[df['price_usd'] == df['support1h']] print(filtered_df) def direnc(): print("direnc de olanlar") filtered_df = df[df['price_usd'] == df['resistance1h']] print(filtered_df) if menu == "1": print(rsi5minover()) if menu == "2": print("RSI 30 ALTI") print(rsi5minsold()) if menu == "3": print("RSİ 15 70 üSTÜ") print(rsi15minover()) if menu == "4": print("RSİ 15 30 ALTI") print(rsi15minsold()) if menu == "5": print(teknik()) if menu == "6": print(price()) if menu == "7": print(destek()) if menu == "8": print(direnc()) if menu == "9": print(guven()) if menu == "0": print("DENİZHAN TOY COİN TARAMA PROGRAMINA HOŞ GELDİNİZ MENU YU KULLANMAK İÇİN NUMARA GİRMELİSİNİZ",) print( "\n MENU 0 == exit" "\n MENU 1 == 5 DK RSI TARAMA " "\n MENU 2 == ADX TARAMA" "\n MENU 3 == 1 Dk ARTIŞ TARAMA" "\n MENU 4 == COİN SORGULA" "\n MENU 5 == GENEL SORGULAMA" "\n MENU 6 == 4 SAATLİK RSI + MA + DESTEK DİRENÇ" "\n MENU 7 == GRAFİK BAKAR" "\n MENU 8 == rsi modul" "\n MENU 9 == BACKTEST modul") break def backtest(): while True: print("SUPER TREND BACKTESTER") print("5 DAKİKALIKDA 1 GÜN ÖNCEYE GÖRE EN İYİ PAREMETLER İÇİN") symbol = input('Sembol gir:').upper() if symbol == "0": print("\n MENU 0 == exit" "\n MENU 1 == 5 DK RSI TARAMA " "\n MENU 2 == ADX TARAMA" "\n MENU 3 == 1 Dk ARTIŞ TARAMA" "\n MENU 4 == COİN SORGULA" "\n MENU 5 == GENEL SORGULAMA" "\n MENU 6 == 4 SAATLİK RSI + MA + DESTEK DİRENÇ" "\n MENU 7 == GRAFİK BAKAR" "\n MENU 8 == rsi modul" "\n MENU 9 == BACKTEST modul") break stock_list = symbol+"USDT" day = input('Kaç günlük?:') interva = input('zaman dilimi giriniz:') binance_data = vbt.BinanceData.download(stock_list, start=day+'day ago UTC', end='now UTC', interval=interva) binance_data = binance_data.update() df = binance_data.get() def Supertrend(df, atr_period, multiplier): high = df['High'] low = df['Low'] close = df['Close'] # calculate ATR price_diffs = [high - low, high - close.shift(), close.shift() - low] true_range = pd.concat(price_diffs, axis=1) true_range = true_range.abs().max(axis=1) # default ATR calculation in supertrend indicator atr = true_range.ewm(alpha=1/atr_period,min_periods=atr_period).mean() # df['atr'] = df['tr'].rolling(atr_period).mean() # HL2 is simply the average of high and low prices hl2 = (high + low) / 2 # upperband and lowerband calculation # notice that final bands are set to be equal to the respective bands final_upperband = upperband = hl2 + (multiplier * atr) final_lowerband = lowerband = hl2 - (multiplier * atr) # initialize Supertrend column to True supertrend = [True] * len(df) for i in range(1, len(df.index)): curr, prev = i, i-1 # if current close price crosses above upperband if close[curr] > final_upperband[prev]: supertrend[curr] = True # if current close price crosses below lowerband elif close[curr] < final_lowerband[prev]: supertrend[curr] = False # else, the trend continues else: supertrend[curr] = supertrend[prev] # adjustment to the final bands if supertrend[curr] == True and final_lowerband[curr] < final_lowerband[prev]: final_lowerband[curr] = final_lowerband[prev] if supertrend[curr] == False and final_upperband[curr] > final_upperband[prev]: final_upperband[curr] = final_upperband[prev] # to remove bands according to the trend direction if supertrend[curr] == True: final_upperband[curr] = np.nan else: final_lowerband[curr] = np.nan return pd.DataFrame({ 'Supertrend': supertrend, 'Final Lowerband': final_lowerband, 'Final Upperband': final_upperband }, index=df.index) atr_period = 10 atr_multiplier = 3.0 supertrend = Supertrend(df, atr_period, atr_multiplier) df = df.join(supertrend) print(df.tail(5)) def backtest_supertrend(df, investment): is_uptrend = df['Supertrend'] close = df['Close'] # initial condition in_position = False equity = investment commission = 5 share = 0 entry = [] exit = [] for i in range(2, len(df)): # if not in position & price is on uptrend -> buy if not in_position and is_uptrend[i]: share = math.floor(equity / close[i] / 100) * 100 equity -= share * close[i] entry.append((i, close[i])) in_position = True # print(f'Buy {share} shares at {round(close[i],2)} on {df.index[i].strftime("%Y/%m/%d")}') # if in position & price is not on uptrend -> sell elif in_position and not is_uptrend[i]: equity += share * close[i] - commission exit.append((i, close[i])) in_position = False # print(f'Sell at {round(close[i],2)} on {df.index[i].strftime("%Y/%m/%d")}') # if still in position -> sell all share if in_position: equity += share * close[i] - commission earning = equity - investment roi = round(earning/investment*100,2) print(f'Earning from investing $100k is ${round(earning,2)} (ROI = {roi}%)') return entry, exit, roi entry, exit, roi = backtest_supertrend(df, 100000) def find_optimal_parameter(df): # predefine several parameter sets atr_period = [2, 4, 6, 8,10] atr_multiplier = [1.0, 1.5, 2.0, 2.5, 3.0,3.2,3.4,3.5] roi_list = [] # for each period and multiplier, perform backtest for period, multiplier in [(x,y) for x in atr_period for y in atr_multiplier]: new_df = df supertrend = Supertrend(df, period, multiplier) supertrend.columns = ["Supertrend2", "Final Lowerband2", "Final Upperband2"] new_df = df.join(supertrend) new_df = new_df[period:] entry, exit, roi = backtest_supertrend(new_df, 100000) roi_list.append((period, multiplier, roi)) print(pd.DataFrame(roi_list, columns=['ATR_period','Multiplier','ROI'])) # return the best parameter set return max(roi_list, key=lambda x:x[2]) optimal_param = find_optimal_parameter(df) print(f'EN İYİ: ATR Period={optimal_param[0]}, Multiplier={optimal_param[1]}, ROI={optimal_param[2]}') time.sleep(2) binance_data = binance_data.update() df = binance_data.get() atr_period = 7 multiplier = 2.5 pd.set_option('display.max_rows', None) def Supertrend(df, atr_period, multiplier): high = df['High'] low = df['Low'] close = df['Close'] # calculate ATR price_diffs = [high - low, high - close.shift(), close.shift() - low] true_range = pd.concat(price_diffs, axis=1) true_range = true_range.abs().max(axis=1) # default ATR calculation in supertrend indicator atr = true_range.ewm(alpha=1/atr_period,min_periods=atr_period).mean() # df['atr'] = df['tr'].rolling(atr_period).mean() # HL2 is simply the average of high and low prices hl2 = (high + low) / 2 # upperband and lowerband calculation # notice that final bands are set to be equal to the respective bands final_upperband = upperband = hl2 + (multiplier * atr) final_lowerband = lowerband = hl2 - (multiplier * atr) # initialize Supertrend column to True supertrend = [True] * len(df) for i in range(1, len(df.index)): curr, prev = i, i-1 # if current close price crosses above upperband if close[curr] > final_upperband[prev]: supertrend[curr] = True # if current close price crosses below lowerband elif close[curr] < final_lowerband[prev]: supertrend[curr] = False # else, the trend continues else: supertrend[curr] = supertrend[prev] # adjustment to the final bands if supertrend[curr] == True and final_lowerband[curr] < final_lowerband[prev]: final_lowerband[curr] = final_lowerband[prev] if supertrend[curr] == False and final_upperband[curr] > final_upperband[prev]: final_upperband[curr] = final_upperband[prev] # to remove bands according to the trend direction if supertrend[curr] == True: final_upperband[curr] = np.nan else: final_lowerband[curr] = np.nan return pd.DataFrame({ 'Supertrend': supertrend, 'Final Lowerband': final_lowerband, 'Final Upperband': final_upperband }, index=df.index) def find_optimal_parameteturn (df): # predefine several parameter sets atr_period = [2,4,6,7, 8, 9, 10,12,14,16] atr_multiplier = [1.0, 1.5, 2.0, 2.5, 3.0] roi_list = [] # for each period and multiplier, perform backtest for period, multiplier in [(x,y) for x in atr_period for y in atr_multiplier]: new_df = df supertrend = Supertrend(df, period, multiplier) new_df = df.join(supertrend) new_df = new_df[period:] entry, exit, roi = backtest_supertrend(new_df, 100000) roi_list.append((period, multiplier, roi)) print(pd.DataFrame(roi_list, columns=['ATR_period','Multiplier','ROI'])) # return the best parameter set return max(roi_list, key=lambda x:x[2]) print(f'Best parameter set: ATR Period={optimal_param[0]}, Multiplier={optimal_param[1]}, ROI={optimal_param[2]}') print(find_optimal_parameter(df)) return backtest() if menu == "1": t1 = threading.Thread(target=rsiscan(), daemon=True) t1.start() t1.join() print(rsiscan()) if menu == "2": t2 = threading.Thread(target=artis5(), daemon=True) t2.start() t2.join() print(artis5()) if menu == "3": t3 = threading.Thread(target=artis1(), daemon=True) t3.start() t3.join() print(artis1()) if menu == "4": t4 = threading.Thread(target=sorgu(), daemon=True) t4.start() t4.join() print(sorgu()) if menu == "5": t5 = threading.Thread(target=genel(), daemon=True) t5.start() t5.join() print(genel()) if menu == "6": t6 = threading.Thread(target=destek(), daemon=True) t6.start() t6.join() print(destek()) if menu == "7": t7 = threading.Thread(target=grafik(), daemon=True) t7.start() t7.join() print(grafik()) if menu == "8": t8 = threading.Thread(target=rsimodul(), daemon=True) t8.start() t8.join() print(rsimodul()) if menu == "9": t9 = threading.Thread(target=backtest(), daemon=True) t9.start() t9.join() print(backtest()) if menu == "0": print("PROGRAM KAPATILIYOR") break if menu == "": print("DENİZHAN TOY COİN TARAMA PROGRAMINA HOŞ GELDİNİZ MENU YU KULLANMAK İÇİN NUMARA GİRMELİSİNİZ", "\n MENU 0 == exit" "\n MENU 1 == 5 DK RSI TARAMA " "\n MENU 2 == ADX TARAMA" "\n MENU 3 == 1 Dk ARTIŞ TARAMA" "\n MENU 4 == COİN SORGULA" "\n MENU 5 == GENEL SORGULAMA" "\n MENU 6 == 4 SAATLİK RSI + MA + DESTEK DİRENÇ" "\n MENU 7 == GRAFİK BAKAR" "\n MENU 8 == rsi modul" "\n MENU 9 == BACKTEST modul")