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
chandru thiyagarajan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.