cBot interacts with Telegram and receive signals

Created at 14 Dec 2023, 00:22
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
LA

larocca.mario12

Joined 11.12.2023

cBot interacts with Telegram and receive signals
14 Dec 2023, 00:22


Hi, I create this bot that when I send a signal to my telegram bot it should execute the order, but it doesn't. It doesn't give me any error so I don't understand why it doesn't work. This is the code:

Can someone help to fix this problem? Thank you so much!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types;
using System.Text.RegularExpressions;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class Telegram : Robot
    {
        [Parameter(DefaultValue = "Hello world!")]
        public string Message { get; set; }

        [Parameter("Bot Token", DefaultValue = "", Group = "Telegram Notifications")]
        public string BotToken { get; set; }

        [Parameter("Chat ID", DefaultValue = "", Group = "Telegram Notifications")]
        public string ChatID { get; set; }

        [Parameter(DefaultValue = "")]
        public string Forex { get; set; }

        [Parameter(DefaultValue = 10)]
        public double TakeProfit { get; set; }

        [Parameter(DefaultValue = 10)]
        public double StopLoss { get; set; }

        [Parameter(DefaultValue = 0)]
        public double Order { get; set; }

        [Parameter(DefaultValue = "")]
        public string TradeSymbol { get; set; }

        [Parameter(DefaultValue = "")]
        public string Tipo { get; set; }

        protected override void OnStart()
        {
            //System.Diagnostics.Debugger.Launch();
            
            //configure telegram security protocol.
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


            var botClient = new TelegramBotClient("[TELEGRAM BOT TOKEN]");

            using CancellationTokenSource cts = new();

            // StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
            ReceiverOptions receiverOptions = new()
            {
                AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates
            };

            botClient.StartReceiving(
                updateHandler: HandleUpdateAsync,
                pollingErrorHandler: HandlePollingErrorAsync,
                receiverOptions: receiverOptions,
                cancellationToken: cts.Token
            );

            async Task MainAsync()
            {
                var me = await botClient.GetMeAsync();

                Console.WriteLine($"Start listening for @{me.Username}");
                Console.ReadLine();

                // Send cancellation request to stop bot
                cts.Cancel();
            }

            // Chiamata a MainAsync
            MainAsync().GetAwaiter().GetResult();

            async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
            {
                // Only process Message updates: https://core.telegram.org/bots/api#message
                if (update.Message is not { } message)
                    return;

                // Only process text messages
                if (message.Text is not { } messageText)
                    return;

                var chatId = message.Chat.Id;

                Console.WriteLine($"Received a '{messageText}' message in chat {chatId}.");

                // Check if the message contains the specified pattern
                var tradePattern = @"(BUY|SELL) ([A-Z]+) ([0-9.]+)\s+SL ([0-9.]+)\s+TP ([0-9.]+)";
                var match = Regex.Match(messageText, tradePattern);

                string tradeTypeStr = null, entryPriceStr = null, stopLossStr = null, takeProfitStr = null;

                if (match.Success)
                {
                    var tradeType = match.Groups[1].Value;
                    var symbol = match.Groups[2].Value;
                    var entryPrice = match.Groups[3].Value;
                    var stopLoss = match.Groups[4].Value;
                    var takeProfit = match.Groups[5].Value;

                    // Convert string values to appropriate types
                    var convertedTradeType = tradeTypeStr.ToUpper() == "BUY" ? TradeType.Buy : TradeType.Sell;
                    var convertedEntryPrice = double.Parse(entryPriceStr);
                    var convertedStopLoss = double.Parse(stopLossStr);
                    var convertedTakeProfit = double.Parse(takeProfitStr);

                    Print($"Trade Type: {convertedTradeType}");
                    Print($"Symbol: {symbol}");
                    Print($"Entry Price: {convertedEntryPrice}");
                    Print($"Stop Loss: {convertedStopLoss}");
                    Print($"Take Profit: {convertedTakeProfit}");

                    ExecuteMarketOrder(convertedTradeType, symbol, 1000, "", convertedStopLoss, convertedTakeProfit);

                    // Respond to the user
                    var responseMessage = $"Trade information received:\n" +
                                          $"Trade Type: {tradeType}\n" +
                                          $"Symbol: {symbol}\n" +
                                          $"Entry Price: {entryPrice}\n" +
                                          $"Stop Loss: {stopLoss}\n" +
                                          $"Take Profit: {takeProfit}";

                    Order = 1;
                    TakeProfit = convertedTakeProfit;
                    StopLoss = convertedStopLoss;
                    TradeSymbol = symbol;
                    Tipo = tradeType;
                    Forex = symbol;

                    // Echo received message text
                    await botClient.SendTextMessageAsync(
                        chatId: chatId,
                        text: responseMessage,
                        cancellationToken: cancellationToken);

                }
                else
                {
                    // If the message does not match the pattern, provide a generic response
                    var errorMessage = "Invalid trade format. Please use a format like:\n" +
                                       "SELL GBPJPY 183.65\n" +
                                       "SL 184.50\n" +
                                       "TP 180.00";

                    // Echo the error message
                    await botClient.SendTextMessageAsync(
                        chatId: chatId,
                        text: errorMessage,
                        cancellationToken: cancellationToken);
                }
            }


            Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
            {
                var ErrorMessage = exception switch
                {
                    ApiRequestException apiRequestException
                        => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                    _ => exception.ToString()
                };

                Console.WriteLine(ErrorMessage);
                return Task.CompletedTask;

            }
        }

        protected override void OnTick()
        {
           if (Order == 1)
            {
                var convertedTradeType = Tipo.ToUpper() == "BUY" ? TradeType.Buy : TradeType.Sell;
                ExecuteMarketOrder(convertedTradeType, Forex, 1000, "", StopLoss, TakeProfit);
                Order = 0;
            }
        }

        protected override void OnStop()
        {
            
        }
    }
}

@larocca.mario12