is there any solution for pine to python

I want to convert twin range filter in trading view indicator to python code but results does not same

trading view indicator pine script:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator(title=’Twin Range Filter’, overlay=true, timeframe=”)
source = input(defval=close, title=’Source’)
showsignals = input(title=’Show Buy/Sell Signals ?’, defval=true)
per1 = input.int(defval=27, minval=1, title=’Fast period’)
mult1 = input.float(defval=1.6, minval=0.1, title=’Fast range’)
per2 = input.int(defval=55, minval=1, title=’Slow period’)
mult2 = input.float(defval=2, minval=0.1, title=’Slow range’)
smoothrng(x, t, m) =>
wper = t * 2 – 1
avrng = ta.ema(math.abs(x – x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng1 = smoothrng(source, per1, mult1)
smrng2 = smoothrng(source, per2, mult2)
smrng = (smrng1 + smrng2) / 2
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x – r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x – r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(source, smrng)
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
STR = filt + smrng
STS = filt – smrng
FUB = 0.0
FUB := STR < nz(FUB[1]) or close[1] > nz(FUB[1]) ? STR : nz(FUB[1])
FLB = 0.0
FLB := STS > nz(FLB[1]) or close[1] < nz(FLB[1]) ? STS : nz(FLB[1])
TRF = 0.0
TRF := nz(TRF[1]) == FUB[1] and close <= FUB ? FUB : nz(TRF[1]) == FUB[1] and close >= FUB ? FLB : nz(TRF[1]) == FLB[1] and close >= FLB ? FLB : nz(TRF[1]) == FLB[1] and close <= FLB ? FUB : FUB
long = ta.crossover(close, TRF)
short = ta.crossunder(close, TRF)
plotshape(showsignals and long, title=’Long’, text=’BUY’, style=shape.labelup, textcolor=color.white, size=size.tiny, location=location.belowbar, color=color.rgb(0, 19, 230))
plotshape(showsignals and short, title=’Short’, text=’SELL’, style=shape.labeldown, textcolor=color.white, size=size.tiny, location=location.abovebar, color=color.rgb(0, 19, 230))
alertcondition(long, title=’Long’, message=’Long’)
alertcondition(short, title=’Short’, message=’Short’)
Trfff = plot(TRF)
mPlot = plot(ohlc4, title=”, style=plot.style_circles, linewidth=0)
longFillColor = close > TRF ? color.green : na
shortFillColor = close < TRF ? color.red : na
fill(mPlot, Trfff, title=’UpTrend Highligter’, color=longFillColor, transp=90)
fill(mPlot, Trfff, title=’DownTrend Highligter’, color=shortFillColor, transp=90)

my python code:

    import time
    import pandas as pd
    import math

    import numpy as np
    import win32api
    from binance.client import Client
    from datetime import datetime#timedelta, 
    #------------------------

    binance_api_key9 =    ''    #Enter your own API-key here
    binance_api_secret9 = '' #Enter your own API-secret

    binance_client = Client(api_key=binance_api_key9, api_secret=binance_api_secret9)


    def ema(series, period):
        return series.ewm(span=period, adjust=False).mean()

    def smoothrng(source, t, m):
        wper = t * 2 - 1
        avrng = ema(abs(source - source.shift(1)), t)
        smoothrng = ema(avrng, wper) * m
        return smoothrng

    def rngfilt(source, smrng):
        filt = source.copy()
        for i in range(1, len(source)):
            if source[i] > filt[i - 1]:
                filt[i] = filt[i - 1] if source[i] - smrng[i] < filt[i - 1] else source[i] - smrng[i]
            elif source[i] + smrng[i] > filt[i - 1]:
                filt[i] = filt[i - 1]
            else:
                filt[i] = source[i] + smrng[i]
        return filt

    def twin_range_filter(df, per1=27, mult1=1.6, per2=55, mult2=2.0):
        # Source data (close prices)
        source = df['close']
        
        # Smooth Average Range Calculation
        smrng1 = smoothrng(source, per1, mult1)
        smrng2 = smoothrng(source, per2, mult2)
        smrng = (smrng1 + smrng2) / 2

        # Range Filter
        filt = rngfilt(source, smrng)
        
        # Trend Determination
        upward = (filt > filt.shift(1)).cumsum()
        downward = (filt < filt.shift(1)).cumsum()
        
        # Long and Short Conditions
        long_cond = (source > filt) & ((source > source.shift(1)) & (upward > 0) | (source < source.shift(1)) & (upward > 0))
        short_cond = (source < filt) & ((source < source.shift(1)) & (downward > 0) | (source > source.shift(1)) & (downward > 0))

        # Initial Condition Tracking
        cond_ini = pd.Series(np.where(long_cond, 1, np.where(short_cond, -1, 0)))
        cond_ini = cond_ini.shift(1).fillna(0)
        
        # Long and Short Signals
        long_signal = long_cond & (cond_ini == -1)
        short_signal = short_cond & (cond_ini == 1)
        
        # Add signals to DataFrame
        df['long'] = long_signal
        df['short'] = short_signal

        return df


    st=binance_client.get_server_time()['serverTime']

    gt = binance_client.get_server_time()
    tt=time.gmtime(int((gt["serverTime"])/1000))
    ww=win32api.SetSystemTime(tt[0],tt[1],0,tt[2],tt[3],tt[4],tt[5],0)
    startint=st-(5000)*240*60000
    print('start kline')
    kk1=[]
    data=[]
    sy='BTCUSDT'
    filename = 'C:\Users\Administrator\Desktop\Btwin\%s4h.csv'  % (sy)
    kk = binance_client.futures_klines(symbol=sy, interval='4h', startTime=startint)
    while kk[-1][6]<float(st):
        #print(kk[-1][6])
        kk2 = binance_client.futures_klines(symbol=sy, interval='4h', startTime=kk[-1][6])
        kk.extend(kk2)
    for line in kk:
        kk1.append([pd.to_datetime(int(line[0])+12600000, unit='ms'),float(line[1]),float(line[2]),float(line[3]),float(line[4]),0,0,0,0,0,0,0])
        data.append(float(line[4]))



    data1 = pd.DataFrame({'close': data })

    result = twin_range_filter(data1)
    for i in range(0,len(kk1)):
        kk1[i][9]=result['close'][i]
        kk1[i][10]=result['long'][i]
        kk1[i][11]=result['short'][i]
    print(kk1)
    kkn=pd.DataFrame(kk1 ,columns = ['timestamp', 'open', 'high', 'low', 'close', '0', '0','0', '0', '0','0','0'        ])
            
        #print(kkt[-1])
    kkn.to_csv(filename)

New contributor

reza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật