Can someone help me Fix this Bot !!

Created at 09 Sep 2022, 12:49
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!
MO

moiz.forex

Joined 05.09.2022

Can someone help me Fix this Bot !!
09 Sep 2022, 12:49


Hey Community of the best programmers and the best Bot creation guys..

I paid someone for this BOT and now couldnt get hold of that person.  I want some changes in this Bot. 
The person who made this for me made it very complicated . What are my requirements 

  • Buy on any time frame when the Price is cutting the 30 RSI from downside. ( It should not Buy when the price coming down and touching the 30 point of RSI, It Should only buy when the RSI line comes from 28 point and touches the 30 level.
  • Sell at 70 RSI same condition where sell only when the price is coming from 71+ points and coming down and touching 70 Rsi then only sell
  • Stop loss option
  • Tralling Stop option
  • Take Profit option in bot

That is it what i want all the other stuff is not required.

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

namespace cAlgo.Robots
{

    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class CandleScalper : Robot
    {

        [Parameter("Order Identification Label", Group = "Settings", DefaultValue = "")]
        public string TheLabel { get; set; }

        [Parameter("Trade Direction", Group = "Settings", DefaultValue = DirectionSelector.Both)]
        public DirectionSelector TheDirection { get; set; }

        [Parameter("Close trades on new bar", Group = "Trade Close", DefaultValue = false)]
        public bool EndAtCandle { get; set; }

        [Parameter("Minutes before market close", Group = "Trade Close", DefaultValue = 15, MinValue = 0, Step = 1)]
        public int MinutesToClose { get; set; }
        
        [Parameter("Volume (in lots)", Group = "Volume Settings", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
        public double Volume { get; set; }

        [Parameter("Stop Loss", Group = "Stop Loss Settings", DefaultValue = SLSelector.Pips)]
        public SLSelector TheStopLoss { get; set; }
        
        [Parameter("Pips", Group = "Stop Loss Settings", DefaultValue = 0, MinValue = 0, Step = 0.1)]
        public double SLPips { get; set; }
                
        [Parameter("Take Profit", Group = "Take Profit Settings", DefaultValue = TPSelector.Pips)]
        public TPSelector TheTakeProfit { get; set; }
        
        [Parameter("Pips", Group = "Take Profit Settings", DefaultValue = 0, MinValue = 0, Step = 0.1)]
        public double TPPips { get; set; }
                                
        [Parameter("Active", Group = "Trade Session", DefaultValue = false)]
        public bool TradeTime { get; set; }

        [Parameter("Start Hour", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 23, Step = 1)]
        public int StartTimeHour { get; set; }

        [Parameter("Start Minute", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 59, Step = 1)]
        public int StartTimeMinutes { get; set; }

        [Parameter("Stop Hour", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 23, Step = 1)]
        public int StopTimeHour { get; set; }

        [Parameter("Stop Minute", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 59, Step = 1)]
        public int StopTimeMinutes { get; set; }

        [Parameter("UTC adjustment", Group = "Trade Session", DefaultValue = 0, MinValue = -12, MaxValue = 14, Step = 1)]
        public int UTC { get; set; }
        
        [Parameter("Enable", Group = "Optimization", DefaultValue = false)]
        public bool Optimizing { get; set; }

        private string _label, _longlabel, _shortlabel;
        private double _lots, _sl, _tp;

        public enum DirectionSelector
        {
            Both,
            LongOnly,
            ShortOnly
        }

        public enum SLSelector
        {
            Pips,
            Dynamic
        }
 
        public enum TPSelector
        {
            Pips
        }
        
        public enum ColorSelector
        {
            Blue,
            Cyan,
            Red,
            Pink,
            Green,
            Orange,
            Yellow,
            Purple
        }

        protected override void OnStart()
        {
            Initialize();

            Positions.Opened += Position_Opens;
            Positions.Closed += Position_Closes;
        }

        private void Initialize()
        {
            _label = SymbolName + "|" + this.TimeFrame + "|" + TheLabel;
            _longlabel = "Long" + "|" + _label;
            _shortlabel = "Short" + "|" + _label; 
        }
   
        protected override void OnTick()
        {
            int mins = Symbol.MarketHours.TimeTillClose().Minutes;
            int hours = Symbol.MarketHours.TimeTillClose().Hours;            
            if(hours == 0 && mins <= MinutesToClose)
            {
                foreach(var pos in Positions)
                {
                    if(pos.Label == _shortlabel || pos.Label == _longlabel)
                    {
                        pos.Close();
                    }                
                }
                
            }
        }
        
        protected override void OnBar()
        {    

            if(EndAtCandle)
            {
                foreach(var pos in Positions)
                {
                    if(pos.Label == _shortlabel || pos.Label == _longlabel)
                    {
                        pos.Close();
                    }
                } 
            }
            
            foreach(var ord in PendingOrders)
            {
                if(ord.Label.Contains(_label))
                {
                    CancelPendingOrder(ord);    
                }
            }
            
            bool tradetime = !TradeTime ? true : TimeManagement(StartTimeHour, StartTimeMinutes, StopTimeHour, StopTimeMinutes) ? true : false;
            int index = Bars.Count - 1;

            if (tradetime)
            {                
                if(Bars.ClosePrices.Last(1) - Bars.OpenPrices.Last(1) > 0) 
                {
                    if(TheDirection != DirectionSelector.ShortOnly)
                    {
                    TradeParameterCalculations("Long", "Green");
                    var ordstop = PlaceStopOrder(TradeType.Buy, SymbolName, _lots, Bars.HighPrices.Last(1), _longlabel, _sl, _tp);
                    }

                    if(TheDirection != DirectionSelector.LongOnly)
                    {
                    TradeParameterCalculations("Short", "Green");
                    var ordlimit = PlaceStopOrder(TradeType.Sell, SymbolName, _lots, Bars.OpenPrices.Last(1), _shortlabel, _sl, _tp);
                    }
                }
                else
                {
                    if(TheDirection != DirectionSelector.LongOnly)
                    {
                    TradeParameterCalculations("Short", "Red");
                    var ordstop = PlaceStopOrder(TradeType.Sell, SymbolName, _lots, Bars.LowPrices.Last(1), _shortlabel, _sl, _tp);
                    }

                    if(TheDirection != DirectionSelector.ShortOnly)
                    {
                    TradeParameterCalculations("Long", "Red");
                    var ordlimit = PlaceStopOrder(TradeType.Buy, SymbolName, _lots, Bars.OpenPrices.Last(1), _longlabel, _sl, _tp);
                    }
                }
            }
        }
        
        void Position_Opens(PositionOpenedEventArgs obj)
        {

        }

        void Position_Closes(PositionClosedEventArgs obj)
        {

        }

        private void TradeParameterCalculations(string direction, string barColor)
        {

            if (direction.Equals("Long"))
            {
                if(TheStopLoss == SLSelector.Pips)
                {
                    _sl = SLPips;
                }
                else
                {
                    if(barColor == "Green")
                    {
                        double sllevel = Bars.OpenPrices.Last(1);
                        _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                    else
                    {
                        double sllevel = Bars.LowPrices.Last(1);
                        _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                }
            }

            if (direction.Equals("Short"))
            {
                if(TheStopLoss == SLSelector.Pips)
                {
                    _sl = SLPips;
                }
                else
                {
                    if(barColor == "Green")
                    {
                        double sllevel = Bars.HighPrices.Last(1); 
                        _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                    else
                    {
                        double sllevel = Bars.OpenPrices.Last(1);
                       _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                }
            }

            if(TheTakeProfit == TPSelector.Pips)
                _tp = TPPips;
            
            _lots = CalculateRisk(_sl);

        }

        protected double CalculateRisk(double stoploss)
        {
            double exactVolume = Symbol.QuantityToVolumeInUnits(Volume);
            return Symbol.NormalizeVolumeInUnits(exactVolume, RoundingMode.ToNearest);
        }
           
        private Color GetColor(ColorSelector color)
        {

            switch (color)
            {
                case ColorSelector.Blue:
                    {
                        return Color.Blue;
                    }
                 case ColorSelector.Cyan:
                    {
                        return Color.Cyan;
                    }
                 case ColorSelector.Red:
                    {
                        return Color.Red;
                    }
                 case ColorSelector.Pink:
                    {
                        return Color.Pink;
                    }
                 case ColorSelector.Green:
                    {
                        return Color.Green;
                    }
                 case ColorSelector.Yellow:
                    {
                        return Color.Yellow;
                    }
                 case ColorSelector.Purple:
                    {
                        return Color.Purple;
                    }
                 case ColorSelector.Orange:
                    {
                        return Color.Orange;
                    }
                 default:
                    return Color.White;
             }

        }

        private bool TimeManagement(int startH, int startM, int stopH, int stopM)
        {

            bool tradetime;
            bool tradehours;

            int currentHours = Server.Time.Hour;
            int currentMinutes = Server.Time.Minute;

            int startHour = startH - UTC;
            int stopHour = stopH - UTC;

            if (stopM == 0)
                tradehours = startHour < stopHour ? startHour <= currentHours && currentHours < stopHour : startHour <= currentHours || currentHours < stopHour;
            else
                tradehours = startHour < stopHour ? startHour <= currentHours && currentHours <= stopHour : startHour <= currentHours || currentHours <= stopHour;

            if (tradehours)
            {
                if (startHour == currentHours && startM != 0)
                    tradetime = startM <= currentMinutes;
                else if (stopHour == currentHours && stopM != 0)
                    tradetime = stopM >= currentMinutes;
                else
                    tradetime = true;
            }
            else
                tradetime = false;

            return tradetime;
        }
  
        protected override void OnStop()
        {
            foreach (var ord in PendingOrders)
            {
                if (ord.Label.Contains(_label))
                    CancelPendingOrder(ord);
            }
        }
        
    }

}


@moiz.forex
Replies

prosteel1
09 Sep 2022, 15:45

RE:

Seems to be a fair bit missing in my opinion for a properly working cbot without all sorts of bugs and strange things going on.

I would like to work with others to produce an open source cbot that actually places trades with stoploss and takeprofit correctly with all the checks to avoid all the pitfalls when things go wrong.

I am open to making this simple cbot using what I have learnt and used from this site, if others are willing to contribute. If we all contributed we could produce an open source sample cbot that works well.

 

The above CalculateRisk method is 2 lines:

protected double CalculateRisk(double stoploss)
        {
            double exactVolume = Symbol.QuantityToVolumeInUnits(Volume);
            return Symbol.NormalizeVolumeInUnits(exactVolume, RoundingMode.ToNearest);
        }

Compare that to what I have (not counting my CalculateMargin and CalculateVolume methods):

private void CalculateRisk()
        {
            PositionRisk = 0.0;
            OrderRisk = 0.0;
            if (Positions.Count > 0)
            {
                Position[] longpositions = Positions.FindAll("Long");
                var longpos = longpositions;
                foreach (var pos in longpos)
                {
                    if (pos.Comment != "" && pos.StopLoss != null && pos.StopLoss < pos.EntryPrice)
                    {
                        double SL = Convert.ToDouble(pos.StopLoss);
                        double posrisk = 0;
                        posrisk = Math.Round((((pos.EntryPrice - SL) / Symbols.GetSymbolInfo(pos.SymbolName).PipSize) * Symbols.GetSymbolInfo(pos.SymbolName).PipValue * pos.VolumeInUnits) - (2 * pos.Commissions) - pos.Swap, 2);
                        Print("pos.SymbolName = " + pos.SymbolName + ", posrisk= " + posrisk);
                        PositionRisk += posrisk;
                    }
                }
                Position[] shortpositions = Positions.FindAll("Short");
                var shortpos = shortpositions;
                foreach (var pos in shortpos)
                {
                    if (pos.Comment != "" && pos.StopLoss != null && pos.StopLoss > pos.EntryPrice)
                    {
                        double SL = Convert.ToDouble(pos.StopLoss);
                        double posrisk = 0;
                        posrisk = Math.Round((((SL - pos.EntryPrice) / Symbols.GetSymbolInfo(pos.SymbolName).PipSize) * Symbols.GetSymbolInfo(pos.SymbolName).PipValue * pos.VolumeInUnits) - (2 * pos.Commissions) - pos.Swap, 2);
                        Print("pos.SymbolName = " + pos.SymbolName + ", posrisk = " + posrisk);
                        PositionRisk += posrisk;
                    }
                }
            }

            if (PendingOrders.Count > 0)
            {
                foreach (var order in PendingOrders)
                {
                    if (order.Comment != "")
                    {
                        var splitted = order.Comment.Split(' ');
                        double ep = Convert.ToDouble(splitted[2]);
                        double sl = Convert.ToDouble(splitted[4]);
                        double tp = Convert.ToDouble(splitted[5]);
                        if (order.TradeType == TradeType.Buy)
                        {
                            double orderrisk = 0;
                            orderrisk = Math.Round((((ep - sl) / Symbols.GetSymbolInfo(order.SymbolName).PipSize) * Symbols.GetSymbolInfo(order.SymbolName).PipValue * order.VolumeInUnits), 2);
                            Print("order.SymbolName = " + order.SymbolName + ", orderrisk = " + orderrisk);
                            OrderRisk += orderrisk;
                        }
                        if (order.TradeType == TradeType.Sell)
                        {
                            double orderrisk = 0;
                            orderrisk = Math.Round((((sl - ep) / Symbols.GetSymbolInfo(order.SymbolName).PipSize) * Symbols.GetSymbolInfo(order.SymbolName).PipValue * order.VolumeInUnits), 2);
                            Print("order.SymbolName = " + order.SymbolName + ", orderrisk = " + orderrisk);
                            OrderRisk += orderrisk;
                        }
                    }
                }
            }
        }

 

I think we are getting to a point in this community where our code is all similar and we should form an opensource focussed group to make good bots rather than the simple examples.

If anyone else is interested please say so!


@prosteel1

moiz.forex
09 Sep 2022, 18:22

RE: RE: I have no Idea where is RSI in this brother

Prosteel,

 

The Orignal Bot mentioned above was made too much complicated and there was no point where he added RSI which I orignally wanted. He added time zone. Cuts off a trade if the other trade is open. So much unnecesry things he added and the main thing which i asked was missing. 

 Can you explain a bit what yoe have done here in this what you made.

 

Thank you

 

 

 

 

 

prosteel1 said:

Seems to be a fair bit missing in my opinion for a properly working cbot without all sorts of bugs and strange things going on.

I would like to work with others to produce an open source cbot that actually places trades with stoploss and takeprofit correctly with all the checks to avoid all the pitfalls when things go wrong.

I am open to making this simple cbot using what I have learnt and used from this site, if others are willing to contribute. If we all contributed we could produce an open source sample cbot that works well.

 

The above CalculateRisk method is 2 lines:

protected double CalculateRisk(double stoploss)
        {
            double exactVolume = Symbol.QuantityToVolumeInUnits(Volume);
            return Symbol.NormalizeVolumeInUnits(exactVolume, RoundingMode.ToNearest);
        }

Compare that to what I have (not counting my CalculateMargin and CalculateVolume methods):

private void CalculateRisk()
        {
            PositionRisk = 0.0;
            OrderRisk = 0.0;
            if (Positions.Count > 0)
            {
                Position[] longpositions = Positions.FindAll("Long");
                var longpos = longpositions;
                foreach (var pos in longpos)
                {
                    if (pos.Comment != "" && pos.StopLoss != null && pos.StopLoss < pos.EntryPrice)
                    {
                        double SL = Convert.ToDouble(pos.StopLoss);
                        double posrisk = 0;
                        posrisk = Math.Round((((pos.EntryPrice - SL) / Symbols.GetSymbolInfo(pos.SymbolName).PipSize) * Symbols.GetSymbolInfo(pos.SymbolName).PipValue * pos.VolumeInUnits) - (2 * pos.Commissions) - pos.Swap, 2);
                        Print("pos.SymbolName = " + pos.SymbolName + ", posrisk= " + posrisk);
                        PositionRisk += posrisk;
                    }
                }
                Position[] shortpositions = Positions.FindAll("Short");
                var shortpos = shortpositions;
                foreach (var pos in shortpos)
                {
                    if (pos.Comment != "" && pos.StopLoss != null && pos.StopLoss > pos.EntryPrice)
                    {
                        double SL = Convert.ToDouble(pos.StopLoss);
                        double posrisk = 0;
                        posrisk = Math.Round((((SL - pos.EntryPrice) / Symbols.GetSymbolInfo(pos.SymbolName).PipSize) * Symbols.GetSymbolInfo(pos.SymbolName).PipValue * pos.VolumeInUnits) - (2 * pos.Commissions) - pos.Swap, 2);
                        Print("pos.SymbolName = " + pos.SymbolName + ", posrisk = " + posrisk);
                        PositionRisk += posrisk;
                    }
                }
            }

            if (PendingOrders.Count > 0)
            {
                foreach (var order in PendingOrders)
                {
                    if (order.Comment != "")
                    {
                        var splitted = order.Comment.Split(' ');
                        double ep = Convert.ToDouble(splitted[2]);
                        double sl = Convert.ToDouble(splitted[4]);
                        double tp = Convert.ToDouble(splitted[5]);
                        if (order.TradeType == TradeType.Buy)
                        {
                            double orderrisk = 0;
                            orderrisk = Math.Round((((ep - sl) / Symbols.GetSymbolInfo(order.SymbolName).PipSize) * Symbols.GetSymbolInfo(order.SymbolName).PipValue * order.VolumeInUnits), 2);
                            Print("order.SymbolName = " + order.SymbolName + ", orderrisk = " + orderrisk);
                            OrderRisk += orderrisk;
                        }
                        if (order.TradeType == TradeType.Sell)
                        {
                            double orderrisk = 0;
                            orderrisk = Math.Round((((sl - ep) / Symbols.GetSymbolInfo(order.SymbolName).PipSize) * Symbols.GetSymbolInfo(order.SymbolName).PipValue * order.VolumeInUnits), 2);
                            Print("order.SymbolName = " + order.SymbolName + ", orderrisk = " + orderrisk);
                            OrderRisk += orderrisk;
                        }
                    }
                }
            }
        }

 

I think we are getting to a point in this community where our code is all similar and we should form an opensource focussed group to make good bots rather than the simple examples.

If anyone else is interested please say so!

 


@moiz.forex