eternnoir / pyTelegramBotAPI

Python Telegram bot api.
GNU General Public License v2.0
8.12k stars 2.03k forks source link

These people don't help #987

Closed alexrios22 closed 4 years ago

alexrios22 commented 4 years ago

Please answer these questions before submitting your issue. Thanks!

  1. What version of pyTelegramBotAPI are you using? 3.7.3

  2. What OS are you using? linux

  3. 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.

# =============================================================================
# Coppock System- Strategy ETF
# Author : Alexander Rios
# =============================================================================

# Import necesary libraries
#import quantstats as qs
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)
mi_bot.polling(True)

chat_id = "##############"

start_date ='2016-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
                #print("porfolio:",portfolio)
                #if i + 1 < len(ohlc2[ticker]):
                    #print('Entrada:',ticker, str(ohlc2[ticker].index[i+1].date()), round(ohlc2[ticker]["Open"][i+1],2))
                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")
mi_bot.polling(False)

And this is the message that appears when executing the routine

2020-10-09 13:37:18,876 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:37:18,879 (__init__.py:420 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-09 13:37:22,820 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:37:22,835 (__init__.py:420 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-09 13:37:27,528 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:37:27,532 (__init__.py:420 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-09 13:37:33,738 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:37:33,742 (__init__.py:420 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-09 13:37:39,960 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:37:39,964 (__init__.py:420 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-09 13:37:52,206 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:37:52,210 (__init__.py:420 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-09 13:38:16,526 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:38:16,530 (__init__.py:420 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-09 13:39:04,906 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:39:04,921 (__init__.py:420 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-09 13:40:12,491 (util.py:66 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[b\'{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}\']',)
Traceback (most recent call last):
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/util.py", line 60, in run
    task(*args, **kwargs)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 279, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/__init__.py", line 249, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 194, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 60, in _make_request
    return _check_result(method_name, result)['result']
  File "/home/alexrios22/.local/lib/python3.8/site-packages/telebot/apihelper.py", line 79, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: 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-09 13:40:12,499 (__init__.py:420 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"}']"

Thanks for the help you can give me, the bot is dead, it doesn't respond to anything.

Badiboy commented 4 years ago

Another bot library / copy with this token is running elsewhere.

alexrios22 commented 4 years ago

But I don't have the bot running elsewhere, what is the correct way to "shut down" the bot?

Badiboy commented 4 years ago

image

image

You call polling twice. Or something like that. Check your code.

alexrios22 commented 4 years ago

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"

Badiboy commented 4 years ago

Does your code after image works well?

alexrios22 commented 4 years ago

It works, but every so often it gives the error

alexrios22 commented 4 years ago

Do I change it to my_bot.polling (True)?

Badiboy commented 4 years ago

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.

alexrios22 commented 4 years ago

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.

alexrios22 commented 4 years ago

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")
alexrios22 commented 4 years ago

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"}']"
Badiboy commented 4 years ago

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.

alexrios22 commented 4 years ago

I do not understand

Badiboy commented 4 years ago

That's sad. You should learn deeper bot programming instead of just copying code from examples.