Category Other  Published on 15/10/2020

reposter

Description

Repost info about trade to telegram channel


using System;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class TelegramBotExample : Robot
    {
        [Parameter("Telegram Bot Key", DefaultValue = "__bot_key__")]
        public string BOT_API_KEY { get; set; }

        // if you know which channel you want to broadcast to, add it here
        // otherwise the bot looks at the people and channels its' interacted with and
        // sends messages to everyone
        [Parameter("ChannelId", DefaultValue = "")]
        public string ChannelId { get; set; }


        List<string> _telegramChannels = new List<string>();

        protected override void OnStart()
        {
            if (string.IsNullOrEmpty(ChannelId))
            {
                _telegramChannels = ParseChannels(GetBotUpdates());
            }
            else
            {
                _telegramChannels.Add(ChannelId);
            }



            // Subscribe to events.
            Positions.Opened += OnPositionOpened;
            Positions.Closed += OnPositionClosed;

        }

        protected override void OnTick()
        {
            // Put your core logic here

        }

        protected override void OnBar()
        {
            // Put your core logic here
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
            // Unsubscribe to events.
            Positions.Opened -= OnPositionOpened;
            Positions.Closed -= OnPositionClosed;
        }


        //  Parses messages for bot and determines which channesl are listening
        private List<string> ParseChannels(string jsonData)
        {
            var matches = new Regex("\"id\"\\:(\\d+)").Matches(jsonData);
            List<string> channels = new List<string>();
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    if (!channels.Contains(m.Groups[1].Value))
                    {
                        channels.Add(m.Groups[1].Value);
                    }
                }
            }
            foreach (var v in channels)
            {
                Print("DEBUG: Found Channel {0} ", v);
            }
            return channels;
        }

        protected int updateOffset = -1;
        private string GetBotUpdates()
        {
            Dictionary<string, string> values = new Dictionary<string, string>();
            if (updateOffset > -1)
            {
                values.Add("offset", (updateOffset++).ToString());
            }

            var jsonData = MakeTelegramRequest(BOT_API_KEY, "getUpdates", values);

            var matches = new Regex("\"message_id\"\\:(\\d+)").Matches(jsonData);
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    int msg_id = -1;
                    int.TryParse(m.Groups[1].Value, out msg_id);
                    if (msg_id > updateOffset)
                    {
                        updateOffset = msg_id;
                    }
                }
            }
            return jsonData;
        }

        private void SendMessageToAllChannels(string message)
        {
            foreach (var c in _telegramChannels)
            {
                SendMessageToChannel(c, message);
            }
        }

        private string SendMessageToChannel(string chat_id, string message)
        {
            var values = new Dictionary<string, string> 
            {
                {
                    "chat_id",
                    chat_id
                },
                {
                    "text",
                    message
                }
            };

            return MakeTelegramRequest(BOT_API_KEY, "sendMessage", values);
        }

        private string MakeTelegramRequest(string api_key, string method, Dictionary<string, string> values)
        {
            string TELEGRAM_CALL_URI = string.Format("https://api.telegram.org/bot{0}/{1}", api_key, method);

            var request = WebRequest.Create(TELEGRAM_CALL_URI);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            StringBuilder data = new StringBuilder();
            foreach (var d in values)
            {
                data.Append(string.Format("{0}={1}&", d.Key, d.Value));
            }
            byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);

            dataStream.Close();

            WebResponse response = request.GetResponse();

            Print("DEBUG {0}", ((HttpWebResponse)response).StatusDescription);

            dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);

            string outStr = reader.ReadToEnd();

            Print("DEBUG {0}", outStr);

            reader.Close();

            return outStr;


        }

        public void OnPositionOpened(PositionOpenedEventArgs args)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // If you didn't set a channel, thenfind channels by looking at the updates
            var data = string.Format("entry price: ={0} \nentry time: {1} \nsymbol: {2}\nstop loss: {3}\ntake profit: {4}", args.Position.EntryPrice, args.Position.EntryTime, args.Position.SymbolName, args.Position.StopLoss, args.Position.TakeProfit);
            Print("DEBUG", args);
            Print("DEBUG", data);
            SendMessageToAllChannels(data);
        }

        public void OnPositionClosed(PositionClosedEventArgs args)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var data = string.Format("net profit: {0}", args.Position.NetProfit);
            SendMessageToAllChannels(data);
        }
    }
}


LA
Lavrik.aw

Joined on 20.09.2020

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: repeater.algo
  • Rating: 5
  • Installs: 1416
  • Modified: 13/10/2021 09:55
Comments
Log in to add a comment.
YA
yakovbilichek · 3 years ago

tell me how to set up a robot to send information about trading to the Telegram channel

YA
yakovbilichek · 3 years ago

подскажи как настроить робота для отправки информации о торговле в Telegram-канал