Python <-> Pine Script — индикатор разницы EMAPython

Программы на Python
Anonymous
Python <-> Pine Script — индикатор разницы EMA

Сообщение Anonymous »

У меня есть код для расчета EMA.

Но после его запуска мои данные не совпадают с Pine Script.
Я перепробовал все библиотеки и методы. Пожалуйста, дайте мне совет.
Вот код Python:

Код: Выделить всё

def pine_ema(prices, length):
if len(prices) < length:
raise ValueError("Недостаточно данных для расчета EMA")

alpha = 2 / (length + 1)
ema = [None] * len(prices)

# Инициализация первого значения EMA
ema[0] = prices[0]

for i in range(1, len(prices)):
ema[i] = round((prices[i] * alpha) + (ema[i - 1] * (1 - alpha)), 3)

return ema

async def get_candlestick_data():
try:
bybit = Bybit()
candles = await bybit.get_kline_data('BTCUSDC', '1', total_limit=5000)
print(f' len = {len(candles)}')
if candles:
timestamps = []
prices = []
opens = []
highs = []
lows = []

for candle in candles:
timestamp = datetime.datetime.fromtimestamp(int(candle[0]) / 1000)
timestamps.append(timestamp)
opens.append(float(candle[1]))  # Open price открытия
highs.append(float(candle[2]))  # Max price
lows.append(float(candle[3]))  # Min price
prices.append(float(candle[4]))  # Closed price
return timestamps, opens, highs, lows, prices
else:
print("Err get data")
return None, None, None, None, None
except Exception as err:
print(f"err: {err}")
return None, None, None, None, None
async def print_candle_data_and_ema(ema_length):
timestamps, opens, highs, lows, prices = await get_candlestick_data()
if prices is not None and timestamps is not None:
ema_values = pine_ema(prices, ema_length)
for timestamp, price, ema in zip(timestamps, prices, ema_values):
print(f"Time: {timestamp}, Closed: {price}, EMA ({ema_length}): {ema}")
Вот код сценария Pine:

Код: Выделить всё

    //@version=5
indicator(title="CM_MacD_Ult_MTF with EMA Logging", shorttitle="CM_Ult_MacD_MTF_Log", overlay=false)

// Исходные данные
source = close

pine_ema(src, length) =>
alpha = 2 / (length + 1)
var float sum = na
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])

useCurrentRes = input(true, title="Use Current Chart Resolution?")
resCustom = input.timeframe(title="Use Different Timeframe? Uncheck Box Above", defval="60")
smd = input(true, title="Show MacD &  Signal Line? Also Turn Off Dots Below")
sd = input(true, title="Show Dots When MacD Crosses Signal Line?")
sh = input(true, title="Show Histogram?")
macd_colorChange = input(true, title="Change MacD Line Color-Signal Line Cross?")
hist_colorChange = input(true, title="MacD Histogram 4 Colors?")

// Выбор разрешения графика
res = useCurrentRes ? timeframe.period : resCustom

// Параметры EMA и сигнальной линии
fastLength = input.int(7, minval=1, title="Fast EMA Length")
slowLength = input.int(24, minval=1, title="Slow EMA Length")
signalLength = input.int(7, minval=1, title="Signal Line Length")

// Вычисление EMA
fastMA = pine_ema(source, fastLength)
slowMA = ta.ema(source, slowLength)

log.info("Close {0}",close)
log.info("Fast EMA (Length {0}): {1}", fastLength, fastMA)

//log.info("Fast EMA (Length {0}): {1}", fastLength, fastMA)
// log.info("Slow EMA (Length {0}): {1}", slowLength, slowMA)
Вот результат работы Python

Код: Выделить всё

Time: 2024-09-26 19:05:00, Closed: 64335.16, EMA (7): 64348.542
Time: 2024-09-26 19:04:00, Closed: 64419.39, EMA (7): 64366.254
Time: 2024-09-26 19:03:00, Closed: 64455.62, EMA (7): 64388.595
Time: 2024-09-26 19:02:00, Closed: 64417.08, EMA (7): 64395.716
Time: 2024-09-26 19:01:00, Closed: 64430.52, EMA (7): 64404.417
Time: 2024-09-26 19:00:00, Closed: 64425.32, EMA (7): 64409.643
Вот результат работы Pine Script

Код: Выделить всё

[2024-09-26T19:05:00.000+07:00]: Close 64,335.16
[2024-09-26T19:05:00.000+07:00]: Fast EMA (Length 7): 64,399.531
[2024-09-26T19:04:00.000+07:00]: Close 64,419.39
[2024-09-26T19:04:00.000+07:00]: Fast EMA (Length 7): 64,420.988
[2024-09-26T19:03:00.000+07:00]: Close 64,455.62
[2024-09-26T19:03:00.000+07:00]: Fast EMA (Length 7): 64,421.521
[2024-09-26T19:02:00.000+07:00]: Close 64,417.08
[2024-09-26T19:02:00.000+07:00]: Fast EMA (Length 7): 64,410.155
[2024-09-26T19:01:00.000+07:00]: Close 64,430.52
[2024-09-26T19:01:00.000+07:00]: Fast EMA (Length 7): 64,407.847
[2024-09-26T19:00:00.000+07:00]: Close 64,425.32
[2024-09-26T19:00:00.000+07:00]: Fast EMA (Length 7): 64,400.289

Я проверил библиотеки:
Pandas, pandas_ta, ta, Ta-lib.

Подробнее здесь: https://stackoverflow.com/questions/790 ... icator-ema

Вернуться в «Python»