0

hi there i m still trying to get trade bot and try to plot them with their time and low price data. i wanna get buy signals that i ve specified at if condition (when macdh turns from negative to positive). then i want to plot them at a data. but can not add them at buy_signal=[] place.
my error is self.plotData(buy_signals = buy_signals) IndexError: list index out of range

import requests
import json
from stockstats import StockDataFrame as Sdf
import plotly.graph_objects as go
from plotly.offline import plot


class TradingModel:
    def __init__(self, symbol):
        self.symbol = symbol
        self.df = self.getData


    def getData(self):

        # define URL
        base = 'https://api.binance.com'
        endpoint = '/api/v3/klines'
        params = '?&symbol='+self.symbol+'&interval=4h'

        url = base + endpoint + params

        # download data
        data = requests.get(url)
        dictionary = data.json()

        # put in dataframe and clean-up
        df = pd.DataFrame.from_dict(dictionary)
        df = df.drop(range(6, 12), axis=1)


        # rename columns and stockstasts
        col_names = ['time', 'open', 'high', 'low', 'close', 'volume']
        df.columns = col_names
        stock = Sdf.retype(df)


        for col in col_names:
            df[col]=df[col].astype(float)
        #defined macdh
        df['macdh']=stock['macdh']


        return  (df)

    def strategy(self):
        df = self.df
        buy_signals=[]
        for i in range(1, len(df['close'])):
                if df['macdh'].iloc[-1]>0 and df['macdh'].iloc[-2]<0:
                    buy_signals.append([df['time'][i], df['low'][i]])

        self.plotData(buy_signals = buy_signals)





    def plotData(self,buy_signal=False):
        df=self.df
        candle=go.Candlestick(
            x=df['time'],
            open=df['open'],
            close=df['close'],
            high=df['high'],
            low=df['low'],
            name="Candlesticks"
        )
        macdh=go.Scatter(
            x=df['time'],
            y=df['macdh'],
            name="Macdh",
            line = dict(color=('rgba(102, 207, 255, 50)')))

        Data=[candle,macdh]

        if buy_signals:
            buys = go.Scatter(
                    x = [item[0] for item in buy_signals],
                    y = [item[1] for item in buy_signals],
                    name = "Buy Signals",
                    mode = "markers",
                )

            sells = go.Scatter(
                    x = [item[0] for item in buy_signals],
                    y = [item[1]*1.04 for item in buy_signals],
                    name = "Sell Signals",
                    mode = "markers",
                )

            data = [candle, macdh, buys, sells]


        # style and display
        layout = go.Layout(title = self.symbol)
        fig = go.Figure(data = data, layout = layout)

        plot(fig, filename=self.symbol)

def Main():
    symbol = "BTCUSDT"
    model = TradingModel(symbol)
    model.strategy()

if __name__ == '__main__':
    Main() ```
6
  • it would be helpful if you could make it more readable by only posting the relevant parts of your code? Commented May 18, 2020 at 21:18
  • Why are you cross-posting this in r? Any r relevant question you have? Commented May 18, 2020 at 21:19
  • @ShanR sorry i ve posted suggested ones i m editing it Commented May 18, 2020 at 21:21
  • @EmmaH if i can ad buy signal list others will be done Commented May 18, 2020 at 21:22
  • I cannot actually find self.plotData(buy_signals[i]) in your code, only self.plotData(buy_signals = buy_signals) Commented May 18, 2020 at 21:25

1 Answer 1

1

You need to replace :

self.plotData(buy_signals[i]) by self.plotData(buy_signals)

def plotData(self,buy_signal=False): by def plotData(self,buy_signals=None):

And it should be good to go !

Sign up to request clarification or add additional context in comments.

8 Comments

it works but i got another problem. if buy_signals==True: NameError: name 'buy_signals' is not defined
when i type this mate buysignals list is empty
I can't see any if buy_signals==True: in your code
when i add [print(buy_signals)] under if condition i got a empty list
if df['macdh'].iloc[-1]>0 and df['macdh'].iloc[-2]<0: buy_signals.append([df['time'][i], df['low'][i]]) print(buy_signals) this list is empty
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.