I am trying to create a telegram bot where it will send me automated message in telegram group

I am facing some issues where it sends me only the candle opens as buy or sell message it not meeting my buy and sell condition it send, and I am Getting late message, from the time I start bot it is calculating the minutes if start the bot at some time in between a minute it will give response after one minute from the time bot started its not following the exact minute from my broker or trading view chart time or my system time.

This is the code for my bot :

import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, JobQueue
import yfinance as yf
import talib
import pandas as pd
import time
import numpy as np
import random
from datetime import datetime, timedelta
import requests

Enable logging

logging.basicConfig(level=logging.INFO)

Telegram Bot Token

TOKEN = ‘7367873356:AAHcQ9zvLHGb4iqmqKmPvSAQoJdx2yc8x_E’

List of currency pairs

currency_pairs = [‘EUR_USD’, ‘GBP_NZD’, ‘GBP_USD’, ‘AUD_USD’, ‘USD_CAD’, ‘EUR_NZD’, ‘EUR_CAD’, ‘USD_CHF’,’AUD_NZD’, ‘AUD_CAD’]

Define a function to get forex data

def get_forex_data(currency_pair, is_live=True, api_token=’128a4aa4f3a16000243bc3bf869b6e66-608b7a70e868cdff0c0b1f788beb0cd3′, account_id=’101-001-29295219-001′):
if is_live:
# Set API endpoint and parameters
url = f’https://api-fxpractice.oanda.com/v3/instruments/{currency_pair}/candles?count=100&granularity=M1′
params = {
‘granularity’: ‘M1’, # 1-minute candles
‘count’: 100 # retrieve 100 candles
}
headers = {
‘Authorization’: f’Bearer {api_token}’,
‘Content-Type’: ‘application/json’
}

    # Make API request
    response = requests.get(url, params=params, headers=headers)

    # Check if the response was successful
    if response.status_code == 200:
        data = response.json()
        candles = data['candles']
        df = pd.DataFrame(candles)
        df['time'] = pd.to_datetime([c['time'] for c in candles])
        df.set_index('time', inplace=True)
        df['Open'] = [c['mid']['o'] for c in candles]
        df['High'] = [c['mid']['h'] for c in candles]
        df['Low'] = [c['mid']['l'] for c in candles]
        df['Close'] = [c['mid']['c'] for c in candles]
        return df
    else:
        logging.error(f'Error: {response.status_code}')
        raise Exception(f'Error: {response.status_code}')
else:
    # If not live, use historical data from another source (e.g. Yahoo Finance)
    ticker = yf.Ticker(currency_pair)
    data = ticker.history(period="1d", interval="1m")
    return data

Define a function to calculate the Heikin Ashi candles

def calculate_heikin_ashi(data):
ha_close = [(data[‘Open’][i] + data[‘High’][i] + data[‘Low’][i] + data[‘Close’][i]) / 4 for i in range(len(data[‘Close’]))]
ha_open = [((data[‘Open’][i-1] + data[‘Close’][i-1]) / 2) if i > 0 else data[‘Open’][i] for i in range(len(data[‘Close’]))]
ha_high = [max(data[‘High’][i], ha_open[i], ha_close[i]) for i in range(len(data[‘Close’]))]
ha_low = [min(data[‘Low’][i], ha_open[i], ha_close[i]) for i in range(len(data[‘Close’]))]

return {
    "ha_open": ha_open,
    "ha_high": ha_high,
    "ha_low": ha_low,
    "ha_close": ha_close
}

Define a function to check for signals and send messages

def calculate_buy_sell_conditions(data):
try:
high_array = np.array(data[‘High’].values, dtype=np.double)
low_array = np.array(data[‘Low’].values, dtype=np.double)
close_array = np.array(data[‘Close’].values, dtype=np.double)

    # Buy conditions parameters
    buy_atr_period = 3
    buy_bollinger_band_length = 70
    buy_bollinger_band_multiplier = 1
    
    # Sell conditions parameters
    sell_atr_period = 6
    sell_bollinger_band_length = 80
    sell_bollinger_band_multiplier = 1
    
    # Correctly pass timeperiod as a positional argument for ATR()
    buy_atr = talib.ATR(high_array, low_array, close_array, timeperiod=buy_atr_period)
    sell_atr = talib.ATR(high_array, low_array, close_array, timeperiod=sell_atr_period)
    
    # Calculate EMA (Exponential Moving Average) with a period of 2
    ema = talib.EMA(close_array, timeperiod=2)
    
    # Calculate standard deviation with a period of 2
    std_dev = talib.STDDEV(close_array, timeperiod=2)
    
    # Calculate Bollinger Bands for buy and sell conditions
    buy_upper_band = ema + (buy_bollinger_band_multiplier * buy_atr)
    buy_lower_band = ema - (buy_bollinger_band_multiplier * buy_atr)
    sell_upper_band = ema + (sell_bollinger_band_multiplier * sell_atr)
    sell_lower_band = ema - (sell_bollinger_band_multiplier * sell_atr)
    
    # Define buy and sell conditions based on the updated criteria
    buy_condition = close_array > buy_lower_band
    sell_condition = close_array < sell_upper_band
    
    return buy_condition, sell_condition
except Exception as e:
    logging.error(f"Error calculating buy/sell conditions: {e}")
    return None, None  # Return default values

Define a function to send a message to a group

def send_message_to_group(context, message):
context.bot.send_message(chat_id=-4277995685, text=message) # Replace withyour group chat ID

Define a function to check for signals and send messages

def check_signals(context):
for currency_pair in currency_pairs:
data = get_forex_data(currency_pair)
if data is not None:
buy_condition, sell_condition = calculate_buy_sell_conditions(data)
if buy_condition is not None and sell_condition is not None:
current_price = data[‘Close’].iloc[-1] # Use iloc to access the last element
current_time = datetime.now().strftime(“%H:%M”)
expiration_time = (datetime.now() + timedelta(minutes=3)).strftime(“%H:%M”)
if buy_condition[-1]:
message = f”{currency_pair}: Buy at {current_price} (Expiration: {expiration_time})”
send_message_to_group(context, message)
elif sell_condition[-1]:
message = f”{currency_pair}: Sell at {current_price} (Expiration: {expiration_time})”
send_message_to_group(context, message)

Define a function to handle the /start command

def start(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text=”Welcome to the chandru Trading Bot!/binary command to get a trading signal”)

Create the Telegram bot

def main():

# Add handlers for the /start command
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))

# Create a job queue to check for signals every 1 minute
job_queue = updater.job_queue
job_queue.run_repeating(check_signals, interval=60, first=0)
job_queue.start()

updater.start_polling()
updater.idle()

if name == ‘main‘:
main()

I am expecting to solve this problem

New contributor

chandru thiyagarajan 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