Closed alexrios22 closed 4 years ago
Another bot library / copy with this token is running elsewhere.
But I don't have the bot running elsewhere, what is the correct way to "shut down" the bot?
You call polling twice. Or something like that. Check your code.
Yes, you are right, but I have corrected that and the error persists. I put the new code
# =============================================================================
# Coppock System- Strategy ETF
# Author : Alexander Rios
# Please report bug/issues in the Q&A section
# =============================================================================
# Import necesary libraries
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
#import numpy as np
import yfinance as yahoo_finance
import ta
from datetime import date
import datetime
import telebot
# Ponemos nuestro TOKEN generado con el @BotFather
TOKEN = '#############################'
# Creamos nuestra instancia "mi_bot" a partir de ese TOKEN
mi_bot = telebot.TeleBot(TOKEN, threaded=False,num_threads=1,skip_pending=True)
mi_bot.infinity_polling(True)
chat_id = "############"
start_date ='2017-01-01' #'2000-01-01'
today = date.today()
end_date = today.strftime("%Y-%m-%d")
tickers = ['SPY','QQQ','TLT','IEI','GLD','SLV']
attempt = 0 # initializing passthrough variable
while attempt <=5:
try:
ohlc = yahoo_finance.download(
tickers, start= start_date, end= end_date , interval="1d",
group_by = "ticker", auto_adjust=True)
break
except:
print("failed to fetch data...retrying")
attempt+=1
continue
ohlc.dropna(axis=0,how='all',inplace=True)
#Calculate Indicators
for ticker in tickers:
RSI = ta.momentum.RSIIndicator(ohlc.loc[:,(ticker,'Close')], n= 14, fillna= False)
ohlc.loc[:,(ticker,'RSI')] = RSI.rsi()
#Daily 294, 231, 210
ROC1 = ta.momentum.ROCIndicator(ohlc.loc[:,(ticker,'Close')], n=294, fillna=False)
ROC2 = ta.momentum.ROCIndicator(ohlc.loc[:,(ticker,'Close')], n=231, fillna=False)
AddROC = ROC1.roc() +ROC2.roc()
Coppock = ta.trend.EMAIndicator(ohlc.loc[:,(ticker,'Close')], n=210, fillna=False)
ohlc.loc[:,(ticker,'Coppock')] = Coppock.ema_indicator()
rsi_values = pd.Series()
trades = {}
ticker_signal = {}
stop_loss = {}
stop = {}
counter = {}
Maxportfolio = 2 #Maximo Nro de Activos en Cartera
portfolio = 0 #Nro de Activos en cartera
for ticker in tickers:
ticker_signal[ticker] = ""
trades[ticker] = 0
stop_loss[ticker] = 0
stop[ticker] = 0 #No operar por N Dias
counter[ticker] = 0
ohlc2 = ohlc.tail(20)
for i in range(len(ohlc2)):
for ticker in tickers:
rsi_values[ticker]= ohlc2[ticker]['RSI'][i]
rsi_tickers = rsi_values.sort_values(ascending=False).index
for ticker in rsi_tickers:
if stop[ticker] > 0:
stop[ticker] -= 1
elif ticker_signal[ticker] == "" and stop[ticker] == 0 and portfolio < Maxportfolio:
if ohlc2[ticker]["Coppock"][i-1] < 0 and ohlc2[ticker]["Coppock"][i] >= 0 or ohlc2[ticker]["Coppock"][i] >= 0:
ticker_signal[ticker] = "Buy"
stop_loss[ticker] = 0.92*ohlc2[ticker]["Close"][i]
trades[ticker] = trades[ticker] + 1
portfolio += 1
text = "Entrada en " + ticker + " "+ (ohlc2[ticker].index[i].date()+datetime.timedelta(1)).strftime("%d-%m-%Y") + " con SL: " + str(round(stop_loss[ticker],2))
mi_bot.send_message(chat_id, text)
elif ticker_signal[ticker] == "Buy":
if ohlc2[ticker]["Coppock"][i] < 0 and ohlc2[ticker]["Coppock"][i-1] >= 0:
stop_loss[ticker] = 0
ticker_signal[ticker] = ""
portfolio -= 1
text = "Salida en " + ticker + " "+ (ohlc2[ticker].index[i].date()+datetime.timedelta(1)).strftime("%d-%m-%Y") + " en apertura"
mi_bot.send_message(chat_id, text)
elif ohlc2[ticker]["Close"][i] <= stop_loss[ticker]:
stop[ticker] = 20
stop_loss[ticker] = 0
portfolio -= 1
counter[ticker] += 1
ticker_signal[ticker] = ""
text = "Salida por SL en " + ticker + " "+ (ohlc2[ticker].index[i].date()+datetime.timedelta(1)).strftime("%d-%m-%Y") + " en apertura"
mi_bot.send_message(chat_id, text)
print("terminamos")
I have changed the call for recommendation, but the error persists and there is nothing else running the bot.
mi_bot = telebot.TeleBot(TOKEN, threaded=False,num_threads=1,skip_pending=True)
mi_bot.infinity_polling(True)
I don't know if it will be because the messages are being sent within the "for loop"
Does your code after works well?
It works, but every so often it gives the error
Do I change it to my_bot.polling (True)?
It works, but every so often it gives the error
That is very-very interesting because... polling/infinity_polling is a blocking function. So execution will not go below polling/infinity_polling. If your code works fine this means that you hide some details from us.
Really, I'm not hiding anything, just the token and my chat id.
I only use the bot to send 3 notifications by messages depending on the case that occurs, as it is in the code.
I do not understand.
This is the code
# =============================================================================
# Coppock System- Strategy ETF
# Author : Alexander Rios
# Please report bug/issues in the Q&A section
# =============================================================================
# Import necesary libraries
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
#import numpy as np
import yfinance as yahoo_finance
import ta
from datetime import date
import datetime
import telebot
# Ponemos nuestro TOKEN generado con el @BotFather
TOKEN = '##############################'
# Creamos nuestra instancia "mi_bot" a partir de ese TOKEN
mi_bot = telebot.TeleBot(TOKEN, threaded=False,num_threads=1,skip_pending=True)
#mi_bot.polling(True)
mi_bot.infinity_polling(True)
chat_id = #######
start_date ='2017-01-01' #'2000-01-01'
today = date.today()
end_date = today.strftime("%Y-%m-%d")
tickers = ['SPY','QQQ','TLT','IEI','GLD','SLV']
attempt = 0 # initializing passthrough variable
while attempt <=5:
try:
ohlc = yahoo_finance.download(
tickers, start= start_date, end= end_date , interval="1d",
group_by = "ticker", auto_adjust=True)
break
except:
print("failed to fetch data...retrying")
attempt+=1
continue
ohlc.dropna(axis=0,how='all',inplace=True)
#Calculate Indicators
for ticker in tickers:
RSI = ta.momentum.RSIIndicator(ohlc.loc[:,(ticker,'Close')], n= 14, fillna= False)
ohlc.loc[:,(ticker,'RSI')] = RSI.rsi()
#Daily 294, 231, 210
ROC1 = ta.momentum.ROCIndicator(ohlc.loc[:,(ticker,'Close')], n=294, fillna=False)
ROC2 = ta.momentum.ROCIndicator(ohlc.loc[:,(ticker,'Close')], n=231, fillna=False)
AddROC = ROC1.roc() +ROC2.roc()
Coppock = ta.trend.EMAIndicator(ohlc.loc[:,(ticker,'Close')], n=210, fillna=False)
ohlc.loc[:,(ticker,'Coppock')] = Coppock.ema_indicator()
rsi_values = pd.Series()
trades = {}
ticker_signal = {}
stop_loss = {}
stop = {}
counter = {}
Maxportfolio = 2 #Maximo Nro de Activos en Cartera
portfolio = 0 #Nro de Activos en cartera
for ticker in tickers:
ticker_signal[ticker] = ""
trades[ticker] = 0
stop_loss[ticker] = 0
stop[ticker] = 0 #No operar por N Dias
counter[ticker] = 0
ohlc2 = ohlc.tail(20)
for i in range(len(ohlc2)):
for ticker in tickers:
rsi_values[ticker]= ohlc2[ticker]['RSI'][i]
rsi_tickers = rsi_values.sort_values(ascending=False).index
for ticker in rsi_tickers:
if stop[ticker] > 0:
stop[ticker] -= 1
elif ticker_signal[ticker] == "" and stop[ticker] == 0 and portfolio < Maxportfolio:
if ohlc2[ticker]["Coppock"][i-1] < 0 and ohlc2[ticker]["Coppock"][i] >= 0 or ohlc2[ticker]["Coppock"][i] >= 0:
ticker_signal[ticker] = "Buy"
stop_loss[ticker] = 0.92*ohlc2[ticker]["Close"][i]
trades[ticker] = trades[ticker] + 1
portfolio += 1
text = "Entrada en " + ticker + " "+ (ohlc2[ticker].index[i].date()+datetime.timedelta(1)).strftime("%d-%m-%Y") + " con SL: " + str(round(stop_loss[ticker],2))
mi_bot.send_message(chat_id, text)
elif ticker_signal[ticker] == "Buy":
if ohlc2[ticker]["Coppock"][i] < 0 and ohlc2[ticker]["Coppock"][i-1] >= 0:
stop_loss[ticker] = 0
ticker_signal[ticker] = ""
portfolio -= 1
text = "Salida en " + ticker + " "+ (ohlc2[ticker].index[i].date()+datetime.timedelta(1)).strftime("%d-%m-%Y") + " en apertura"
mi_bot.send_message(chat_id, text)
elif ohlc2[ticker]["Close"][i] <= stop_loss[ticker]:
stop[ticker] = 20
stop_loss[ticker] = 0
portfolio -= 1
counter[ticker] += 1
ticker_signal[ticker] = ""
text = "Salida por SL en " + ticker + " "+ (ohlc2[ticker].index[i].date()+datetime.timedelta(1)).strftime("%d-%m-%Y") + " en apertura"
mi_bot.send_message(chat_id, text)
print("terminamos")
I'm running it from pythonanywhere, with the idea of leaving the bot running as a scheduled task and see, it triggers the error
2020-10-11 12:53:51,371 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:53:55,304 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:53:59,987 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:54:06,186 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:54:12,415 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:54:24,630 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:54:48,933 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
2020-10-11 12:55:37,296 (__init__.py:448 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:
[b'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}']"
I'm running it from pythonanywhere, with the idea of leaving the bot running
Lol. I said that you are hiding details from us. So here they are. Once again:
polling/infinity_polling is a blocking function. So execution will not go below polling/infinity_polling.
When you call polling/infinity_polling your code will not end. So when your scheduler run the code for the first time it will not be finished and continue polling infinintely. Next scheduled run will run the second instance and its polling will conflict with the first instance.
I do not understand
That's sad. You should learn deeper bot programming instead of just copying code from examples.
Please answer these questions before submitting your issue. Thanks!
What version of pyTelegramBotAPI are you using? 3.7.3
What OS are you using? linux
What version of python are you using? 3.8
Hello this is the code that I am running, I have put # where the token and chat id go, but the bot worked fine during some testing and then I throw that error.
And this is the message that appears when executing the routine
Thanks for the help you can give me, the bot is dead, it doesn't respond to anything.