Crypto Bot with BollingerBands

Joined
Feb 3, 2023
Messages
1
Reaction score
0
Can anyone help me with my Code im trying to programm my first crypto bot and need your help.

import ccxt
import time
import yfinance as yf


API_KEY = input("Your API Key : ")
SECRET_KEY = input("Your Secret Key : ")

# Verbindung zu Börse aufbauen
exchange = ccxt.bitvavo ({
'apiKey': API_KEY,
'secret': SECRET_KEY,
})

symbol = 'BTC/USDT'

# Berechnung der Bollinger Bänder mit yFinance
equity = yf.Ticker("AAPL")
data = equity.history(period='1y')
df = data[['Close']]

sma = df.rolling(window=20).mean().dropna()
rstd = df.rolling(window=20).std().dropna()

upper_band = sma + 2 * rstd
lower_band = sma - 2 * rstd

upper_band = upper_band.rename(columns={'Close': 'upper'})
lower_band = lower_band.rename(columns={'Close': 'lower'})
bb = df.join(upper_band).join(lower_band)
bb = bb.dropna()

buyers = bb[bb['Close'] <= bb['lower']]
sellers = bb[bb['Close'] >= bb['upper']]


# Stop Loss Level
stop_loss = 0.005
Anzahl = 75
# Ausführung des Bot-Tradings
while True:
# Preise abrufen
ticker = exchange.fetch_ticker(symbol)


# Geld pro Trade in USDT
cost=20
price = ticker['last']
amount=cost/price



# Handels Order setzen
if price == buyers:
# kaufen
exchange.create_order(symbol, 'limit', 'buy', amount, price)
buy_price = ticker['last']

elif price == sellers:
# Stop Loss Überprüfung
if price < stop_loss * buyers:
# verkaufen
exchange.create_order(symbol, 'limit', 'sell',amount, price)

# Pause von 5 Sekunden
time.sleep(5)

import plotly.io as pio
import plotly.graph_objects as go

pio.templates.default = "plotly_dark"

fig = go.Figure()
fig.add_trace(go.Scatter(x=lower_band.index,
y=lower_band['lower'],
name='Lower Band',
line_color='rgba(173,204,255,0.2)'
))
fig.add_trace(go.Scatter(x=upper_band.index,
y=upper_band['upper'],
name='Upper Band',
fill='tonexty',
fillcolor='rgba(173,204,255,0.2)',
line_color='rgba(173,204,255,0.2)'
))
fig.add_trace(go.Scatter(x=df.index,
y=df['Close'],
name='Close',
line_color='#636EFA'
))
fig.add_trace(go.Scatter(x=sma.index,
y=sma['Close'],
name='SMA',
line_color='#FECB52'
))
fig.add_trace(go.Scatter(x=buyers.index,
y=buyers['Close'],
name='Buyers',
mode='markers',
marker=dict(
color='#00CC96',
size=10,
)
))
fig.add_trace(go.Scatter(x=sellers.index,
y=sellers['Close'],
name='Sellers',
mode='markers',
marker=dict(
color='#EF553B',
size=10,
)
))
fig.show()

This is my Code but something seems to be wrong with creating the Orders.
 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
Can anyone help me with my Code im trying to programm my first crypto bot and need your help.

import ccxt
import time
import yfinance as yf


API_KEY = input("Your API Key : ")
SECRET_KEY = input("Your Secret Key : ")

# Verbindung zu Börse aufbauen
exchange = ccxt.bitvavo ({
'apiKey': API_KEY,
'secret': SECRET_KEY,
})

symbol = 'BTC/USDT'

# Berechnung der Bollinger Bänder mit yFinance
equity = yf.Ticker("AAPL")
data = equity.history(period='1y')
df = data[['Close']]

sma = df.rolling(window=20).mean().dropna()
rstd = df.rolling(window=20).std().dropna()

upper_band = sma + 2 * rstd
lower_band = sma - 2 * rstd

upper_band = upper_band.rename(columns={'Close': 'upper'})
lower_band = lower_band.rename(columns={'Close': 'lower'})
bb = df.join(upper_band).join(lower_band)
bb = bb.dropna()

buyers = bb[bb['Close'] <= bb['lower']]
sellers = bb[bb['Close'] >= bb['upper']]


# Stop Loss Level
stop_loss = 0.005
Anzahl = 75
# Ausführung des Bot-Tradings
while True:
# Preise abrufen
ticker = exchange.fetch_ticker(symbol)


# Geld pro Trade in USDT
cost=20
price = ticker['last']
amount=cost/price



# Handels Order setzen
if price == buyers:
# kaufen
exchange.create_order(symbol, 'limit', 'buy', amount, price)
buy_price = ticker['last']

elif price == sellers:
# Stop Loss Überprüfung
if price < stop_loss * buyers:
# verkaufen
exchange.create_order(symbol, 'limit', 'sell',amount, price)

# Pause von 5 Sekunden
time.sleep(5)

import plotly.io as pio
import plotly.graph_objects as go

pio.templates.default = "plotly_dark"

fig = go.Figure()
fig.add_trace(go.Scatter(x=lower_band.index,
y=lower_band['lower'],
name='Lower Band',
line_color='rgba(173,204,255,0.2)'
))
fig.add_trace(go.Scatter(x=upper_band.index,
y=upper_band['upper'],
name='Upper Band',
fill='tonexty',
fillcolor='rgba(173,204,255,0.2)',
line_color='rgba(173,204,255,0.2)'
))
fig.add_trace(go.Scatter(x=df.index,
y=df['Close'],
name='Close',
line_color='#636EFA'
))
fig.add_trace(go.Scatter(x=sma.index,
y=sma['Close'],
name='SMA',
line_color='#FECB52'
))
fig.add_trace(go.Scatter(x=buyers.index,
y=buyers['Close'],
name='Buyers',
mode='markers',
marker=dict(
color='#00CC96',
size=10,
)
))
fig.add_trace(go.Scatter(x=sellers.index,
y=sellers['Close'],
name='Sellers',
mode='markers',
marker=dict(
color='#EF553B',
size=10,
)
))
fig.show()

This is my Code but something seems to be wrong with creating the Orders.
There are a few issues with the code:

  1. The if statement condition is not correct:
YAML:
if price == buyers:

It should be checking if the current price is below the lower band. The condition should be:

CSS:
if price <= buyers['lower'].iloc[-1]:


Humm : Similar issue with the elif statement:

Python:
elif price == sellers:

It should be checking if the current price is above the upper band. The condition should be:

CSS:
elif price >= sellers['upper'].iloc[-1]:

The stop_loss variable should be calculated based on the buy_price and not buyers :

Makefile:
stop_loss = buy_price * stop_loss

- The time.sleep(5) should be outside the while loop so that it only pauses for 5 seconds once.

-The amount variable is not being updated inside the while loop so you will always be trading the same amount.

Finally, Anzahl is not being used in the code, so you can remove it.

The corrected code would look like:

Python:
import ccxt
import time
import yfinance as yf


API_KEY = input("Your API Key : ")
SECRET_KEY = input("Your Secret Key : ")

# Verbindung zu Börse aufbauen
exchange = ccxt.bitvavo ({
'apiKey': API_KEY,
'secret': SECRET_KEY,
})

symbol = 'BTC/USDT'

# Berechnung der Bollinger Bänder mit yFinance
equity = yf.Ticker("AAPL")
data = equity.history(period='1y')
df = data[['Close']]

sma = df.rolling(window=20).mean().dropna()
rstd = df.rolling(window=20).std().dropna()

upper_band = sma + 2 * rstd
lower_band = sma - 2 * rstd

upper_band = upper_band.rename(columns={'Close': 'upper'})
lower_band = lower_band.rename(columns={'Close': 'lower'})
bb = df.join(upper_band).join(lower_band)
bb = bb.dropna()

buyers = bb[bb['Close'] <= bb['lower']]
sellers = bb[bb['Close'] >= bb['upper']]


# Stop Loss Level
stop_loss = 0.005

# Ausführung des Bot-Tradings
while True:
    # Preise abrufen
    ticker = exchange.fetch_ticker(symbol)
    price = ticker['last']
    
    # Geld pro Trade in USDT
    cost=20
    amount = cost/price
    
    # Handels Order setzen
    if price <= buyers['lower'].iloc[-1]:
        # kaufen
        exchange.create_order(symbol, 'limit', 'buy', amount, price)
        buy_price = ticker['last']
        stop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top