Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
6.9 kB
4
Indexable
Never
import ccxt
import pandas as pd
import talib as ta
import numpy as np
import plotly.graph_objects as go

# Binance API bilgilerini girin
api_key = ""
secret = ""
market = "spot"
symbol = 'RSR/USDT'
timeframe = '1h'
pivot_length = 21
datalength = 1000

# Binance bağlantısını oluşturun
binance = ccxt.binance({
    "apiKey": api_key,
    "secret": secret,
    'options': {
        'defaultType': market,
        'defaultMarginMode': 'isolated'
    },
    'enableRateLimit': False
})

# OHLCV verilerini alın ve DataFrame'e dönüştürün
ohlcvs = binance.fetch_ohlcv(symbol, timeframe=timeframe, limit=datalength)
df = pd.DataFrame(ohlcvs, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
df['date'] = pd.to_datetime(df['date'], unit='ms')

# Pivot noktalarını bulmak için bir fonksiyon oluşturun
def is_pivot(candles, window):
    low_values = df.iloc[candles - window:candles + window + 1]['low'].values
    high_values = df.iloc[candles - window:candles + window + 1]['high'].values
    pivot_low = np.all(df.iloc[candles]['low'] <= low_values)
    pivot_high = np.all(df.iloc[candles]['high'] >= high_values)
    if pivot_high and pivot_low:
        return 3
    elif pivot_high:
        return 1
    elif pivot_low:
        return 2
    else:
        return 0

# Pivot noktalarını hesaplayın
df['isPivot'] = np.vectorize(is_pivot)(df.index, pivot_length)

# 'pointpos' sütununu oluşturun
df['pointpos'] = np.where(df['isPivot'] == 2, df['low'],
                          np.where(df['isPivot'] == 1, df['high'], np.nan))

# Pivot high ve low değerlerini alın
pivot_highs = df[df['isPivot'] == 1]['high']
pivot_lows = df[df['isPivot'] == 2]['low']

# Eğimi hesaplayan fonksiyon
def calculate_slope(x1, y1, x2, y2):
    return (y2 - y1) / (x2 - x1)

# ATR hesaplayın
df['atr'] = ta.ATR(df['high'], df['low'], df['close'], timeperiod=50)
df['atr'].bfill(inplace=True)

# Trend çizgilerini oluşturun
def create_trend_lines(pivot_points, direction='high'):
    lines = []
    for i in range(1, len(pivot_points)):
        if (direction == 'high' and pivot_points.iloc[i] < pivot_points.iloc[i-1]) or \
           (direction == 'low' and pivot_points.iloc[i] > pivot_points.iloc[i-1]):
            start_index = pivot_points.index[i-1]
            finish_index = pivot_points.index[i]
            slope = calculate_slope(start_index, pivot_points.iloc[i-1], finish_index, pivot_points.iloc[i])
            lines.append({
                'first_index': start_index,
                'second_index': finish_index,
                'slope': slope,
                'continue_drawing': True,
                'finish_index': None,
                'line': None
            })
    return lines

highlines = create_trend_lines(pivot_highs, 'high')
lowlines = create_trend_lines(pivot_lows, 'low')

# Trend çizgileri için yeni sütunlar oluştur
high_trend_columns = [f'high_trend_{i+1}' for i in range(len(highlines))]
low_trend_columns = [f'low_trend_{i+1}' for i in range(len(lowlines))]

for col in high_trend_columns + low_trend_columns:
    df[col] = np.nan

def draw_trend_lines(df, lines, pivot_points, trend_columns):
    last_index = df.index[-1]
    for idx, line in enumerate(lines):
        start_index = line['first_index']
        finish_index = line['second_index']
        slope = line['slope']
        x_values = [start_index, finish_index]
        y_values = [pivot_points.loc[start_index], pivot_points.loc[finish_index]]
        continue_drawing = True
        while finish_index < last_index and continue_drawing:
            if 'high' in trend_columns[idx]:
                condition = (df['close'].loc[finish_index-1] < y_values[-2] + df['atr'][finish_index-1]) and (df['close'].loc[finish_index] < y_values[-1] + df['atr'][finish_index])
            else:
                condition = (df['close'].loc[finish_index-1] > y_values[-2] - df['atr'][finish_index-1]) and (df['close'].loc[finish_index] > y_values[-1] - df['atr'][finish_index])

            if condition:
                finish_index += 1
                x_values.append(finish_index)
                y_values.append(y_values[-1] + slope)
            else:
                continue_drawing = False
                line['continue_drawing'] = False
        line['finish_index'] = finish_index
        line['line'] = {'x': x_values, 'y': y_values}
        
        for i, x in enumerate(x_values):
            if x < len(df):
                df.at[x, trend_columns[idx]] = y_values[i]

    # Son 5 mumdan önce biten trend çizgilerini kaldır
    cutoff_index = last_index - 5
    for col in trend_columns:
        last_trend_index = df[col].last_valid_index()
        if last_trend_index is not None and last_trend_index < cutoff_index:
            df.drop(columns=[col], inplace=True)

draw_trend_lines(df, highlines, pivot_highs, high_trend_columns)
draw_trend_lines(df, lowlines, pivot_lows, low_trend_columns)

# Kapanış fiyatını ve hacmi grafiğe ekleyin
fig = go.Figure(data=[go.Candlestick(x=np.array(df['date']),
                                     open=df['open'],
                                     high=df['high'],
                                     low=df['low'],
                                     close=df['close'])])
fig.add_scatter(x=np.array(df['date']), y=df['pointpos'], mode="markers",
                marker=dict(size=5, color="MediumPurple"),
                name="Pivot")
fig.add_trace(go.Bar(x=np.array(df['date']), y=df['volume'], yaxis='y2', name='Volume'))

# High trend çizgilerini ekle
for line in highlines:
    if line['finish_index'] >= df.index[-1] - 5:
        fig.add_trace(go.Scatter(x=np.array(df['date'].iloc[line['line']['x']]),
                                 y=line['line']['y'],
                                 mode='lines',
                                 line=dict(color='green', width=2),
                                 name='High Trend'))

# Low trend çizgilerini ekle
for line in lowlines:
    if line['finish_index'] >= df.index[-1] - 5:
        fig.add_trace(go.Scatter(x=np.array(df['date'].iloc[line['line']['x']]),
                                 y=line['line']['y'],
                                 mode='lines',
                                 line=dict(color='red', width=2),
                                 name='Low Trend'))

# Grafiği güncelle ve göster
fig.update_layout(xaxis_rangeslider_visible=False,
                  title=f'{symbol} Price with Trend Lines Based on Pivot Points ({pivot_length}) in {timeframe}',
                  xaxis_title='Date', yaxis_title='Price',
                  yaxis2=dict(title='Volume', overlaying='y', side='right'))

fig.show()
print(df)
bit = pd.Timestamp.utcnow()
print(f"{bit} bitti..")
Leave a Comment