Get Signals into cBot from Custom Indicator

Created at 04 Aug 2020, 10:18
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!
VA

vamsi.rc

Joined 05.05.2020

Get Signals into cBot from Custom Indicator
04 Aug 2020, 10:18


Hi Team,

 

I am working on my own strategy to identify potential reversals which is working almost 80 to 90 percent. But, if I apply the same in cBot, its still working, but not as per my plan. So I will try to explain the issue which helps you people can understand.

Below is the image with signals from Indicator.

INDICATOR CODE: (BELOW CODE WILL NOT PLOT SIGNALS LIKE SHOWN ABOVE, JUST GIVEN FOR YOUR UNDERSTANDING)

using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
using System.Data.SqlClient;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class STRSSignals : Indicator
    {
        #region "Declarations"
        [Parameter("Display Arrow Signal", DefaultValue = true)]
        public bool DisplayArrowSignal { get; set; }

        [Parameter("Opp Signal Validate", DefaultValue = true)]
        public bool OppSignalValidation { get; set; }

        [Parameter("Arrow Spacing from Line", DefaultValue = 3)]
        public int ArrowSpacing { get; set; }

        

        public string upArrow = "▲";
        public string downArrow = "▼";
        public bool bullishArrowDrawn = false;
        public bool bearishArrowDrawn = false;
        public int SignalIndex;
        public RelativeStrengthIndex rsi;

        public bool RSIBullish = false, RSIBearish = false;
        public bool IsBullish, IsBearish;
        public DateTime lastsignaltime;
        public string signal;
        public string signalstatus;
        public int signalBackPeriods;

        #endregion

        //[Output("Signal")]
        public IndicatorDataSeries SignalsData;

        //[Output("Signal Index")]
        public IndicatorDataSeries SignalsIndexData;

       

        protected override void Initialize()
        {
            rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, RSIPeriod);
        }

        public override void Calculate(int index)
        {
            int s = 0;

            IsBullish = false;
            IsBearish = false;

            int period = 1;

            RSIBullish = rsi.Result.HasCrossedAbove(10, period);
            RSIBearish = rsi.Result.HasCrossedBelow(10, period);

            IsBullish = RSIBullish;
            IsBearish = RSIBearish;

            if (IsBullish)
            {
                SignalIndex = index;
                DisplayArrows(index, "Buy");
                lastsignaltime = Bars.OpenTimes.Last(SignalIndex);
                signal = "Buy";
                SignalsData[index] = 1;
                SignalsIndexData[index] = index;
            }

            if (IsBearish)
            {
                SignalIndex = index;
                DisplayArrows(index, "Sell");
                lastsignaltime = Bars.OpenTimes.Last(SignalIndex);
                signal = "Sell";
                SignalsData[index] = 2;
                SignalsIndexData[index] = index;
            }

            if (SignalIndex == index)
            {
                signalstatus = "Running";
            }

            if (SignalIndex < index)
            {
                signalstatus = "Confirmed";
                signalBackPeriods = index - SignalIndex;
            }



            Chart.DrawStaticText("LastSignalTime", SetNewLine(s) + "Last Signal Time \t: " + "\t" + lastsignaltime.ToString("yyyy-MM-dd HH:mm:ss"), VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("LastSignalIndex", SetNewLine(s) + "Last Signal Index \t: " + "\t" + SignalIndex + " Current Index : " + index, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("LastSignal", SetNewLine(s) + "Last Signal \t: " + "\t" + signal, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("TimeFrame", SetNewLine(s) + "Time Frame \t: " + "\t" + Chart.TimeFrame, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("SignalStatus", SetNewLine(s) + "Signal Status \t: " + "\t" + signalstatus, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("SignalBackPeriodsCount", SetNewLine(s) + "Periods Ago \t: " + "\t" + signalBackPeriods, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
        }

        public string SetNewLine(int count)
        {
            string _newline = "";
            int i = 0;

            while (i < count)
            {
                _newline = _newline + Environment.NewLine;
                i++;
            }

            return _newline;
        }

        public void DisplayArrows(int index, string signal)
        {
            int idx;
            if (DisplayArrowSignal)
            {
                if (signal == "Buy")
                {
                    if (OppSignalValidation)
                    {
                        if (!bullishArrowDrawn)
                        {
                            idx = index;
                            // _breakoutCandleIndexBuy;
                            double y = Bars.LowPrices.Last(0) - (Symbol.PipSize * ArrowSpacing);
                            string TextName = string.Format("BuySignal {0}", idx);
                            ChartObjects.DrawText(TextName, upArrow, idx, y, VerticalAlignment.Top, HorizontalAlignment.Center, Colors.Green);
                            bullishArrowDrawn = true;
                            bearishArrowDrawn = false;
                        }
                    }
                    else
                    {
                        idx = index;
                        // _breakoutCandleIndexBuy;
                        double y = Bars.LowPrices.Last(0) - (Symbol.PipSize * ArrowSpacing);
                        string TextName = string.Format("BuySignal {0}", idx);
                        ChartObjects.DrawText(TextName, upArrow, idx, y, VerticalAlignment.Top, HorizontalAlignment.Center, Colors.Green);
                        bullishArrowDrawn = true;
                        bearishArrowDrawn = false;
                    }
                }
                else if (signal == "Sell")
                {
                    if (OppSignalValidation)
                    {
                        if (!bearishArrowDrawn)
                        {
                            idx = index;
                            // _breakoutCandleIndexSell;
                            double y = Bars.HighPrices.Last(0) + (Symbol.PipSize * ArrowSpacing);
                            string TextName = string.Format("SellSignal {0}", idx);
                            ChartObjects.DrawText(TextName, downArrow, idx, y, VerticalAlignment.Bottom, HorizontalAlignment.Center, Colors.Red);
                            bearishArrowDrawn = true;
                            bullishArrowDrawn = false;
                        }
                    }
                    else
                    {
                        idx = index;
                        // _breakoutCandleIndexSell;
                        double y = Bars.HighPrices.Last(0) + (Symbol.PipSize * ArrowSpacing);
                        string TextName = string.Format("SellSignal {0}", idx);
                        ChartObjects.DrawText(TextName, downArrow, idx, y, VerticalAlignment.Bottom, HorizontalAlignment.Center, Colors.Red);
                        bearishArrowDrawn = true;
                        bullishArrowDrawn = false;
                    }

                }
            }
        }
    }
}

I want to use above signals and place orders based on some conditions from cBot. To do so, I am using below code which is returning NULL always, even the signal is active.

CBOT CODE:

        public STRSSignals strssignals;

        protected override void OnStart()
        {
            strssignals = Indicators.GetIndicator<STRSSignals>(false, false, 3);

            // Subscribe to the positions opened event.
            Positions.Opened += PositionsOnOpened;

            // Subscribe to the positions closed event.
            //Positions.Closed += PositionsOnClosed;

            //// Subscribe to the positions modified event.
            //Positions.Modified += OnPositionsModified;

            //// Subscribe to the pending order created event.
            //PendingOrders.Created += OnPendingOrdersCreated;

            //// Subscribe to the pending order modified event.
            //PendingOrders.Modified += OnPendingOrdersModified;

            //// Subscribe to the pending order cancelled event.
            //PendingOrders.Cancelled += OnPendingOrdersCancelled;
        }

        bool IsBullish, IsBearish;
        protected override void OnBar()
        {
            
            // To here I want to get Signal from Indicator to cBot and assign values to IsBullish / IsBearish. So, then I will place orders like below. (I created my own methods to place orders).

            try
            {
                string signal = strssignals.SignalsData.Last(1).ToString();
                string signalindex = strssignals.SignalsIndexData.Last(1).ToString();

                Print(signal + " - " + signalindex);

            }
            catch (Exception ex)
            {
                Print(ex.Message + " - OB001");
            }

            try
            {
                if (IsBullish == true)
                {
                    if (AllowTrading)
                    {
                        ClosePositions(TradeType.Buy, SymbolName.ToString());

                        PlaceOrder(TradeType.Buy, Bars.HighPrices.Last(1), SymbolName, "RB - " + Chart.TimeFrame, TargetPips, 0, Symbol.PipSize);
                    }
                }

                if (IsBearish == true)
                {
                    if (AllowTrading)
                    {
                        ClosePositions(TradeType.Sell, SymbolName.ToString());

                        PlaceOrder(TradeType.Sell, Bars.LowPrices.Last(1), SymbolName, "RS - " + Chart.TimeFrame , 0, Symbol.PipSize);
                    }
                }
            }
            catch (Exception ex)
            {
                Print(ex.Message + " - PO002");
            }
        }

OnBar, I am getting below error.

04/08/2020 07:17:00.917 | Object reference not set to an instance of an object. - OB001

 

Now, when I try using the Public variable in Indicator like below and its returning always NULL. 

In simple words, I want to place order on Buy or Sell Signals from Indicator. 

How to accomplish this scenario to proceed further.

Thank you 

R C Vamsi Vardhan


@vamsi.rc
Replies

PanagiotisCharalampous
04 Aug 2020, 10:30

Hi Vamsi,

I cannot build this indicator. Can you please provide the actual working indicator and cBot?

Best Regards,

Panagiotis 

Join us on Telegram

 


@PanagiotisCharalampous

vamsi.rc
04 Aug 2020, 10:59

RE:

Complete Build and Code available in this below link.

https://drive.google.com/drive/folders/1av4y9hrZbepsJhJ5LUQoUw-oj6ZyvuEd?usp=sharing

 

INDICATOR CODE:

using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
using System.Data.SqlClient;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class STRSSignalsv2 : Indicator
    {
        #region "Declarations"
        [Parameter("Display Arrow Signal", DefaultValue = true)]
        public bool DisplayArrowSignal { get; set; }

        [Parameter("Opp Signal Validate", DefaultValue = true)]
        public bool OppSignalValidation { get; set; }

        [Parameter("Arrow Spacing from Line", DefaultValue = 3)]
        public int ArrowSpacing { get; set; }

        [Parameter("RSI Period", DefaultValue = 14)]
        public int RSIPeriod { get; set; }

        public string upArrow = "▲";
        public string downArrow = "▼";
        public bool bullishArrowDrawn = false;
        public bool bearishArrowDrawn = false;
        public int SignalIndex;
        public RelativeStrengthIndex rsi;

        public bool RSIBullish = false, RSIBearish = false;
        public bool IsBullish, IsBearish;
        public DateTime lastsignaltime;
        public string signal;
        public string signalstatus;
        public int signalBackPeriods;

        #endregion

        //[Output("Signal")]
        public IndicatorDataSeries SignalsData;

        //[Output("Signal Index")]
        public IndicatorDataSeries SignalsIndexData;



        protected override void Initialize()
        {
            #region "Initilization"
            rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, RSIPeriod);

            #endregion
        }


        public override void Calculate(int index)
        {
            int s = 0;

            IsBullish = false;
            IsBearish = false;

            int period = 1;

            #region "Logic"
            RSIBullish = rsi.Result.HasCrossedAbove(10, period) ||             /*rsi.Result.HasCrossedAbove(20, period) ||*/rsi.Result.HasCrossedAbove(30, period) ||             /*rsi.Result.HasCrossedAbove(40, period) ||*/            /*rsi.Result.HasCrossedAbove(50, period) ||*/            /*rsi.Result.HasCrossedAbove(60, period) ||*/rsi.Result.HasCrossedAbove(70, period) ||             /*rsi.Result.HasCrossedAbove(80, period) ||*/            /*|| rsi.Result.HasCrossedAbove(100, period)*/rsi.Result.HasCrossedAbove(90, period);
            RSIBearish = rsi.Result.HasCrossedBelow(10, period) ||             /*rsi.Result.HasCrossedBelow(20, period) ||*/rsi.Result.HasCrossedBelow(30, period) ||             /*rsi.Result.HasCrossedBelow(40, period) ||*/            /*rsi.Result.HasCrossedBelow(50, period) ||*/            /*rsi.Result.HasCrossedBelow(60, period) ||*/rsi.Result.HasCrossedBelow(70, period) ||             /*rsi.Result.HasCrossedBelow(80, period) ||*/            /*|| rsi.Result.HasCrossedBelow(100, period)*/rsi.Result.HasCrossedBelow(90, period);

            IsBullish = RSIBullish;
            IsBearish = RSIBearish;
            #endregion

            if (IsBullish)
            {
                SignalIndex = index;
                DisplayArrows(index, "Buy");
                lastsignaltime = Bars.OpenTimes.Last(SignalIndex);
                signal = "Buy";
                SignalsData[index] = 1;
                SignalsIndexData[index] = index;
            }

            if (IsBearish)
            {
                SignalIndex = index;
                DisplayArrows(index, "Sell");
                lastsignaltime = Bars.OpenTimes.Last(SignalIndex);
                signal = "Sell";
                SignalsData[index] = 2;
                SignalsIndexData[index] = index;
            }



            if (SignalIndex == index)
            {
                signalstatus = "Running";
            }

            if (SignalIndex < index)
            {
                signalstatus = "Confirmed";
                signalBackPeriods = index - SignalIndex;
            }



            Chart.DrawStaticText("LastSignalTime", SetNewLine(s) + "Last Signal Time \t: " + "\t" + lastsignaltime.ToString("yyyy-MM-dd HH:mm:ss"), VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("LastSignalIndex", SetNewLine(s) + "Last Signal Index \t: " + "\t" + SignalIndex + " Current Index : " + index, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("LastSignal", SetNewLine(s) + "Last Signal \t: " + "\t" + signal, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("TimeFrame", SetNewLine(s) + "Time Frame \t: " + "\t" + Chart.TimeFrame, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("SignalStatus", SetNewLine(s) + "Signal Status \t: " + "\t" + signalstatus, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
            s = s + 1;
            Chart.DrawStaticText("SignalBackPeriodsCount", SetNewLine(s) + "Periods Ago \t: " + "\t" + signalBackPeriods, VerticalAlignment.Top, HorizontalAlignment.Left, Color.Aqua);
        }

        public string SetNewLine(int count)
        {
            string _newline = "";
            int i = 0;

            while (i < count)
            {
                _newline = _newline + Environment.NewLine;
                i++;
            }

            return _newline;
        }

        public void DisplayArrows(int index, string signal)
        {
            int idx;
            if (DisplayArrowSignal)
            {
                if (signal == "Buy")
                {
                    if (OppSignalValidation)
                    {
                        if (!bullishArrowDrawn)
                        {
                            idx = index;
                            // _breakoutCandleIndexBuy;
                            double y = Bars.LowPrices.Last(0) - (Symbol.PipSize * ArrowSpacing);
                            string TextName = string.Format("BuySignal {0}", idx);
                            ChartObjects.DrawText(TextName, upArrow, idx, y, VerticalAlignment.Top, HorizontalAlignment.Center, Colors.Green);
                            bullishArrowDrawn = true;
                            bearishArrowDrawn = false;
                        }
                    }
                    else
                    {
                        idx = index;
                        // _breakoutCandleIndexBuy;
                        double y = Bars.LowPrices.Last(0) - (Symbol.PipSize * ArrowSpacing);
                        string TextName = string.Format("BuySignal {0}", idx);
                        ChartObjects.DrawText(TextName, upArrow, idx, y, VerticalAlignment.Top, HorizontalAlignment.Center, Colors.Green);
                        bullishArrowDrawn = true;
                        bearishArrowDrawn = false;
                    }
                }
                else if (signal == "Sell")
                {
                    if (OppSignalValidation)
                    {
                        if (!bearishArrowDrawn)
                        {
                            idx = index;
                            // _breakoutCandleIndexSell;
                            double y = Bars.HighPrices.Last(0) + (Symbol.PipSize * ArrowSpacing);
                            string TextName = string.Format("SellSignal {0}", idx);
                            ChartObjects.DrawText(TextName, downArrow, idx, y, VerticalAlignment.Bottom, HorizontalAlignment.Center, Colors.Red);
                            bearishArrowDrawn = true;
                            bullishArrowDrawn = false;
                        }
                    }
                    else
                    {
                        idx = index;
                        // _breakoutCandleIndexSell;
                        double y = Bars.HighPrices.Last(0) + (Symbol.PipSize * ArrowSpacing);
                        string TextName = string.Format("SellSignal {0}", idx);
                        ChartObjects.DrawText(TextName, downArrow, idx, y, VerticalAlignment.Bottom, HorizontalAlignment.Center, Colors.Red);
                        bearishArrowDrawn = true;
                        bullishArrowDrawn = false;
                    }

                }
            }
        }
    }
}

 

cBot:

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class STRSSignalsBotv2 : Robot
    {
        #region "Parameters"
        [Parameter("Allow Trading", DefaultValue = true, Group = "Trading")]
        public bool AllowTrading { get; set; }

        [Parameter("LotSize", DefaultValue = 0.01, Group = "Trading")]
        public double Quantity { get; set; }

        [Parameter("Label", DefaultValue = "RTBv1", Group = "Trading")]
        public string BandsLabel { get; set; }

        [Parameter("Order Expire Minutes", DefaultValue = 0, Group = "Trading")]
        public int OrderExpireMinutes { get; set; }

        [Parameter("Double Lot Size On Loss", DefaultValue = false, Group = "Trading")]
        public bool DoubleLotSize { get; set; }

        [Parameter("Max Double Lot Size", DefaultValue = 0.04, Group = "Trading")]
        public double MaxDoubleQuantity { get; set; }

        [Parameter("Allow Order Expire", DefaultValue = false, Group = "Trading")]
        public bool OrderExpire { get; set; }

        [Parameter("Allow Opp Position Close", DefaultValue = true, Group = "Trading")]
        public bool AllowOppPosClose { get; set; }

        [Parameter("Allow Opp Pending Orders Cancel", DefaultValue = true, Group = "Trading")]
        public bool AllowOppPendingOrdersCancelled { get; set; }

        [Parameter("Allow Limit Orders", DefaultValue = true, Group = "Trading")]
        public bool AllowLimitOrders { get; set; }

        [Parameter("Allow Target In Pips", DefaultValue = true, Group = "Profit")]
        public bool AllowPipsTarget { get; set; }

        [Parameter("Target In Pips", DefaultValue = 10, Group = "Profit")]
        public int TargetPips { get; set; }

        [Parameter("Allow StopLoss", DefaultValue = false, Group = "StopLoss")]
        public bool AllowStopLoss { get; set; }

        [Parameter("Allow Target", DefaultValue = false, Group = "Profit")]
        public bool AllowTarget { get; set; }

        [Parameter("RSI Period", DefaultValue = 14)]
        public int RSIPeriod { get; set; }

        #endregion

        public STRSSignalsv2 strssignals;

        protected override void OnStart()
        {
            strssignals = Indicators.GetIndicator<STRSSignalsv2>(false, false, 3, 4);

            // Subscribe to the positions opened event.
            Positions.Opened += PositionsOnOpened;

            // Subscribe to the positions closed event.
            //Positions.Closed += PositionsOnClosed;

            //// Subscribe to the positions modified event.
            //Positions.Modified += OnPositionsModified;

            //// Subscribe to the pending order created event.
            //PendingOrders.Created += OnPendingOrdersCreated;

            //// Subscribe to the pending order modified event.
            //PendingOrders.Modified += OnPendingOrdersModified;

            //// Subscribe to the pending order cancelled event.
            //PendingOrders.Cancelled += OnPendingOrdersCancelled;
        }

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

        bool IsBullish, IsBearish;
        protected override void OnBar()
        {
            try
            {
                string signal = strssignals.SignalsData.Last(1).ToString();
                string signalindex = strssignals.SignalsIndexData.Last(1).ToString();

                Print(signal + " - " + signalindex);

            } catch (Exception ex)
            {
                Print(ex.Message + " - OB001");
            }



            //try
            //{
            //    if (IsBullish == true)
            //    {
            //        if (AllowTrading)
            //        {
            //            ClosePositions(TradeType.Buy, SymbolName.ToString());

            //            PlaceOrder(TradeType.Buy, Bars.HighPrices.Last(1), SymbolName, "RB - " + Chart.TimeFrame + " - " + Convert.ToDateTime(Bars.OpenTimes.Last(0)).ToString("yyyy-MM-dd HH:mm:ss"), TargetPips, 0, Symbol.PipSize);
            //        }
            //    }

            //    if (IsBearish == true)
            //    {
            //        if (AllowTrading)
            //        {
            //            ClosePositions(TradeType.Sell, SymbolName.ToString());

            //            PlaceOrder(TradeType.Sell, Bars.LowPrices.Last(1), SymbolName, "RS - " + Chart.TimeFrame + " - " + Convert.ToDateTime(Bars.OpenTimes.Last(0)).ToString("yyyy-MM-dd HH:mm:ss"), 0, Symbol.PipSize);
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Print(ex.Message + " - PO002");
            //}
        }


        private void ClosePositions(TradeType tradeType, string symbol)
        {
            if (AllowOppPosClose)
            {
                if (tradeType == TradeType.Buy)
                {
                    var possell = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbol).Where(pos => pos.TradeType == TradeType.Sell);

                    //if (possell.Count() > 0)
                    //{
                    foreach (Position sellpos in possell)
                    {
                        ClosePosition(possell.First());
                    }
                    //}
                }

                if (tradeType == TradeType.Sell)
                {
                    var posbuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbol).Where(pos => pos.TradeType == TradeType.Buy);

                    //if (posbuy.Count() > 0)
                    //{
                    foreach (Position buypos in posbuy)
                    {
                        ClosePosition(posbuy.First());
                    }
                    //}
                }
            }
        }

        private void PlaceOrder(TradeType ttype, double entryPrice, string symbolName, string commentSuffix, double takeProfit = 0, double stopLoss = 0, double pipsize = 0)
        {
            int buyposcount = 0, sellposcount = 0;
            //, buyordcount = 0, sellordcount = 0;

            double Qty;

            Qty = Quantity;

            try
            {




                if (!(AllowStopLoss))
                {
                    stopLoss = 0;
                }

                //if (AllowStopLoss)
                //{
                //    stopLoss = Math.Abs((entryPrice - stopLoss) / pipsize);
                //}

                if (!(AllowTarget))
                {
                    takeProfit = 0;
                }

                if (AllowPipsTarget)
                {
                    if (takeProfit == 0)
                    {
                        takeProfit = TargetPips;
                    }
                }

                //if (AllowPipsStopLoss)
                //{
                //    if (stopLoss == 0)
                //    {
                //        stopLoss = StoplossPips;
                //    }
                //}

                //// Lot Optimization
                if (History.Where(his => his.SymbolName == SymbolName).Where(his => his.Label == BandsLabel).Count() > 0)
                {
                    var prevtrade = History.Where(his => his.SymbolName == SymbolName).Where(his => his.Label == BandsLabel).Last();
                    //Print(prevtrade.PositionId + " - " + prevtrade.TradeType + " - " + prevtrade.EntryTime + " - " + prevtrade.Quantity + " - " + prevtrade.ClosingTime + " - " + prevtrade.NetProfit);

                    if (DoubleLotSize)
                    {
                        if (prevtrade.NetProfit < 0)
                        {
                            if (prevtrade.Quantity < MaxDoubleQuantity)
                            {
                                Qty = prevtrade.Quantity * 2;
                            }

                            if (prevtrade.Quantity == MaxDoubleQuantity)
                            {
                                Qty = MaxDoubleQuantity;
                                takeProfit = 0;
                            }

                        }
                    }
                }

                var volumeInUnits = Symbol.QuantityToVolumeInUnits(Qty);
                DateTime OrderExpire = Server.Time.AddMinutes(OrderExpireMinutes);

                try
                {


                    if (ttype == TradeType.Buy)
                    {
                        var pendingOrders = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Buy);
                        foreach (PendingOrder o in pendingOrders)
                        {
                            o.Cancel();
                        }

                        // Finding if any open positions with same signal
                        buyposcount = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Buy).Count();



                        //< MaxOpenPosPerSymbol)
                        if (buyposcount == 0)
                        {
                            if (AllowLimitOrders)
                            {
                                if (entryPrice <= Bars.ClosePrices.LastValue)
                                {
                                    if (OrderExpireMinutes > 0)
                                    {
                                        var result = PlaceLimitOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
                                    }
                                    if (OrderExpireMinutes == 0)
                                    {
                                        var result = PlaceLimitOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
                                    }
                                }
                                else if (entryPrice >= Bars.ClosePrices.LastValue)
                                {
                                    if (OrderExpireMinutes > 0)
                                    {
                                        var result = PlaceStopOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
                                    }
                                    if (OrderExpireMinutes == 0)
                                    {
                                        var result = PlaceStopOrder(tradeType: TradeType.Buy, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
                                    }
                                }
                            }
                            else
                            {
                                var result = ExecuteMarketOrder(TradeType.Buy, symbolName, volumeInUnits, BandsLabel, stopLoss, takeProfit, "Market - " + commentSuffix, false);
                            }
                        }
                    }

                    if (ttype == TradeType.Sell)
                    {


                        // Finding and Cancelling any old same signal pending orders
                        var pendingOrdersSell = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Sell);
                        foreach (PendingOrder o in pendingOrdersSell)
                        {
                            o.Cancel();
                        }

                        // Finding if any open positions with same signal
                        sellposcount = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == symbolName).Where(pos => pos.TradeType == TradeType.Sell).Count();

                        // < MaxOpenPosPerSymbol)
                        if (sellposcount == 0)
                        {
                            if (AllowLimitOrders)
                            {
                                if (entryPrice <= Bars.ClosePrices.LastValue)
                                {
                                    if (OrderExpireMinutes > 0)
                                    {
                                        var result = PlaceStopOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
                                    }
                                    if (OrderExpireMinutes == 0)
                                    {
                                        var result = PlaceStopOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Stop - " + commentSuffix, hasTrailingStop: false);
                                    }
                                }
                                else if (entryPrice >= Bars.ClosePrices.LastValue)
                                {
                                    if (OrderExpireMinutes > 0)
                                    {
                                        var result = PlaceLimitOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: OrderExpire, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
                                    }
                                    if (OrderExpireMinutes == 0)
                                    {
                                        var result = PlaceLimitOrder(tradeType: TradeType.Sell, symbolName: symbolName, volume: volumeInUnits, targetPrice: entryPrice, label: BandsLabel, stopLossPips: stopLoss, takeProfitPips: takeProfit, expiration: null, comment: "Limit - " + commentSuffix, hasTrailingStop: false);
                                    }
                                }
                            }
                            else
                            {
                                var result = ExecuteMarketOrder(TradeType.Sell, symbolName, volumeInUnits, BandsLabel, stopLoss, takeProfit, "Market - " + commentSuffix, false);
                            }
                        }
                    }
                } catch (Exception ex)
                {
                    Print(ex.Message + " - PO001");
                }
            } catch (Exception ex)
            {
                Print(ex.Message + " - POM001");
            }
        }

        #region "Order Events"
        private void PositionsOnOpened(PositionOpenedEventArgs args)
        {
            var apos = args.Position;
            //Print("Position opened at {0}", pos.EntryPrice);

            //if (AllowOppPosClose)
            //{
            //    if (apos.TradeType == TradeType.Buy)
            //    {
            //        var possell = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == apos.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);

            //        //if (possell.Count() > 0)
            //        //{
            //        foreach (Position sellpos in possell)
            //        {
            //            ClosePosition(possell.First());
            //        }
            //        //}
            //    }

            //    if (apos.TradeType == TradeType.Sell)
            //    {
            //        var posbuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == apos.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);

            //        //if (posbuy.Count() > 0)
            //        //{
            //        foreach (Position buypos in posbuy)
            //        {
            //            ClosePosition(posbuy.First());
            //        }
            //        //}
            //    }
            //}

            //TrailStopLoss(TrailStoplossIndex, "Position", apos);

        }

        private void PositionsOnClosed(PositionClosedEventArgs args)
        {
            // the reason for closing can be captured.
            switch (args.Reason)
            {
                case PositionCloseReason.StopLoss:
                    Print("Position closed as stop loss was hit");
                    break;

                case PositionCloseReason.StopOut:
                    Print("Position closed as it was stopped out");
                    break;

                case PositionCloseReason.TakeProfit:
                    Print("Position closed as take profit was hit");
                    //if (args.Position.TradeType == TradeType.Buy)
                    //{
                    //    var pendingOrdersSell = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);

                    //    foreach (PendingOrder o in pendingOrdersSell)
                    //    {
                    //        o.Cancel();
                    //    }

                    //    var positionsSell = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);

                    //    foreach (Position o in positionsSell)
                    //    {
                    //        o.Close();
                    //    }
                    //}
                    //if (args.Position.TradeType == TradeType.Sell)
                    //{
                    //    var pendingOrdersBuy = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);

                    //    foreach (PendingOrder o in pendingOrdersBuy)
                    //    {
                    //        o.Cancel();
                    //    }

                    //    var positionsBuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == args.Position.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);

                    //    foreach (Position o in positionsBuy)
                    //    {
                    //        o.Close();
                    //    }
                    //}
                    break;
            }
        }

        private void OnPositionsModified(PositionModifiedEventArgs args)
        {
            var pos = args.Position;
            //Print("Position modified with a new stop loss of {0} pips", pos.ModifyStopLossPips);
        }

        private void OnPendingOrdersCreated(PendingOrderCreatedEventArgs obj)
        {
            var order = obj.PendingOrder;

            if (AllowOppPendingOrdersCancelled)
            {
                if (order.TradeType == TradeType.Buy)
                {
                    var pendingOrdersSell = PendingOrders.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == order.SymbolName).Where(pos => pos.TradeType == TradeType.Sell);

                    foreach (PendingOrder o in pendingOrdersSell)
                    {
                        o.Cancel();
                    }
                }

                if (order.TradeType == TradeType.Sell)
                {
                    var pendingOrdersBuy = Positions.Where(pos => pos.Label == BandsLabel).Where(pos => pos.SymbolName == order.SymbolName).Where(pos => pos.TradeType == TradeType.Buy);

                    foreach (PendingOrder o in pendingOrdersBuy)
                    {
                        o.Cancel();
                    }
                }
            }

            //Print(" A {0} Pending order has been created.", order.OrderType);
        }

        private void OnPendingOrdersModified(PendingOrderModifiedEventArgs obj)
        {
            var order = obj.PendingOrder;
            //Print("Pending order modified with a new target price of {0}", order.ModifyTargetPrice);
        }

        private void OnPendingOrdersCancelled(PendingOrderCancelledEventArgs obj)
        {
            switch (obj.Reason)
            {
                case PendingOrderCancellationReason.Cancelled:
                    Print("Pending order was cancelled");
                    break;

                case PendingOrderCancellationReason.Expired:
                    Print("Pending order has expired");
                    break;

                case PendingOrderCancellationReason.Rejected:
                    Print("Pending order was rejected");
                    break;
            }
        }

        #endregion

    }
}

PanagiotisCharalampous said:

Hi Vamsi,

I cannot build this indicator. Can you please provide the actual working indicator and cBot?

Best Regards,

Panagiotis 

Join us on Telegram

 

 


@vamsi.rc

PanagiotisCharalampous
04 Aug 2020, 11:58

Hi Vamsi,

To get rid of the exception, you need to change 

        //[Output("Signal")]
        public IndicatorDataSeries SignalsData;

        //[Output("Signal Index")]
        public IndicatorDataSeries SignalsIndexData;

to


        [Output("Signal")]
        public IndicatorDataSeries SignalsData { get; set; }

        [Output("Signal Index")]
        public IndicatorDataSeries SignalsIndexData { get; set; }

Best Regards,

Panagiotis 

Join us on Telegram


@PanagiotisCharalampous

vamsi.rc
04 Aug 2020, 12:03 ( Updated at: 21 Dec 2023, 09:22 )

RE:

If I use it as Output Parameter, it plots the data series on chart. Then the chart looks like this.

In this case, I should use 2 Indicators one for display and another for cBot. Let me try this.

PanagiotisCharalampous said:

Hi Vamsi,

To get rid of the exception, you need to change 

        //[Output("Signal")]
        public IndicatorDataSeries SignalsData;

        //[Output("Signal Index")]
        public IndicatorDataSeries SignalsIndexData;

to


        [Output("Signal")]
        public IndicatorDataSeries SignalsData { get; set; }

        [Output("Signal Index")]
        public IndicatorDataSeries SignalsIndexData { get; set; }

Best Regards,

Panagiotis 

Join us on Telegram

 


@vamsi.rc