Do not return true in many cases

Created at 06 Mar 2019, 13:21
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!
nh.zadeh's avatar

nh.zadeh

Joined 11.03.2018

Do not return true in many cases
06 Mar 2019, 13:21


Dear Sir

I wrote a cbot which works in two 15 minutes and one minutes time frame. in subroutins which is started from line 278 to 298, there is many candles which pass all the conditions but the return bool value is false. Please advise

 

// A scalping system using three Smooth Moving Averages on 5 Minutes time frame
// Robot was created by Nasser Hassanzadeh, Feb 2019
// Contaact: nh.zadeh@gmail.com


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

namespace cAlgo
{

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

        [Parameter("Risk %", DefaultValue = 1)]
        public double riskpercent { get; set; }

        [Parameter("Stop Loss", DefaultValue = 20, MinValue = 1)]
        public double StopLoss { get; set; }

        [Parameter("TP1", DefaultValue = 30, MinValue = 1)]
        public double TP1 { get; set; }

        [Parameter("TP2", DefaultValue = 50, MinValue = 1)]
        public double TP2 { get; set; }

        [Parameter("TP1 Percent %", DefaultValue = 50, MinValue = 0)]
        public double TP1Percent { get; set; }

        [Parameter("TP2 Percent %", DefaultValue = 50, MinValue = 0)]
        public double TP2Percent { get; set; }

        [Parameter("Volume in Lot", DefaultValue = 0.5, MinValue = 0)]
        public double lot { get; set; }

        [Parameter("Starting Trading hour", DefaultValue = 0, MinValue = 0)]
        public int StartingTradingHour { get; set; }

        [Parameter("Ending Trading hour", DefaultValue = 23, MinValue = 0)]
        public int EndingTradingHour { get; set; }

        [Parameter("SMA Short Period", DefaultValue = 5, MinValue = 0)]
        public int SMAShortPeriod { get; set; }

        [Parameter("Medium Timeframe", DefaultValue = "Minute15")]
        public TimeFrame MediumTimeFrame { get; set; }

        [Parameter("Small Timeframe", DefaultValue = "Minute")]
        public TimeFrame SmallTimeFrame { get; set; }

        public MarketSeries SmallSeries;
        public MarketSeries MediumSeries;
        private WSMA SMAShort;
        private AverageTrueRange AtrMedium;
        public bool BuyFlag = false, SellFlag = false;
        public bool TP1Flag = false, TP2Flag = false;
        public double StopLossPoint;

        protected override void OnStart()
        {
            SmallSeries = MarketData.GetSeries(SmallTimeFrame);
            MediumSeries = MarketData.GetSeries(MediumTimeFrame);
            SMAShort = Indicators.GetIndicator<WSMA>(SmallSeries.Close, SMAShortPeriod);
            AtrMedium = Indicators.AverageTrueRange(MediumSeries, 14, MovingAverageType.Exponential);
        }

        protected override void OnBar()
        {


            //Find position types
            var longPosition = Positions.FindAll("Nasser" + Symbol.Code, Symbol, TradeType.Buy);
            var shortPosition = Positions.FindAll("Nasser" + Symbol.Code, Symbol, TradeType.Sell);
            var position1 = Positions.Find("Nasser" + Symbol.Code, Symbol);
            if (TradingHour())
            {
                //Open Long Position
                if (!BuyFlag && (Positions.Count(x => x.SymbolCode == Symbol.Code) == 0) && BuyPatternOne())
                {
                    BuyFlag = true;
                    StopLossPoint = Math.Min(MediumSeries.Low.Last(1), MediumSeries.Low.Last(2));
                }
                if (MediumSeries.Close.Last(1) < StopLossPoint)
                {
                    BuyFlag = false;
                }
                if (BuyFlag && PriceCrossSMAUpward())
                {
                    StopLossPoint = Math.Min(MediumSeries.Low.LastValue, Math.Min(MediumSeries.Low.Last(1), MediumSeries.Low.Last(2)));
                    StopLoss = Math.Round((SmallSeries.Close.Last(1) - StopLossPoint) / Symbol.PipSize, 1);
                    lot = VolumeCal(StopLoss);
                    ExecuteMarketOrder(TradeType.Buy, Symbol, Symbol.NormalizeVolumeInUnits(Symbol.QuantityToVolumeInUnits(lot), RoundingMode.Down), "Nasser" + Symbol.Code, StopLoss + 4, null, 0.5);
                    TP1Flag = false;
                    BuyFlag = false;
//                    TP2Flag = false;
                }
            }

            //Open Short Position
            if ((!SellFlag && Positions.Count(x => x.SymbolCode == Symbol.Code) == 0) && SellPatternOne())
            {
                SellFlag = true;
                StopLossPoint = Math.Max(MediumSeries.High.Last(1), MediumSeries.High.Last(2));
            }
            if (MediumSeries.Close.Last(1) > StopLossPoint)
            {
                SellFlag = false;
            }
            if (SellFlag && PriceCrossSMADownward())
            {
                StopLossPoint = Math.Max(MediumSeries.High.LastValue, Math.Max(MediumSeries.High.Last(1), MediumSeries.High.Last(2)));
                StopLoss = Math.Round((StopLossPoint - SmallSeries.Close.Last(1)) / Symbol.PipSize, 1);
                lot = VolumeCal(StopLoss);
                ExecuteMarketOrder(TradeType.Sell, Symbol, Symbol.NormalizeVolumeInUnits(Symbol.QuantityToVolumeInUnits(lot), RoundingMode.Down), "Nasser" + Symbol.Code, StopLoss + 4, null, 0.5);
                TP1Flag = false;
                SellFlag = false;
//                TP2Flag = false;
            }

            //Close Long Position
            //longPosition.Count() >= 1)
            if (false)
            {
                if (BearishHangingMan(1))
                {
                    //                  Print("SL reached and close all positions");
                    ClosePosition(Positions.Find("Nasser" + Symbol.Code));
                    TP1Flag = false;
                    TP2Flag = false;
                }
            }

            //Close Short Position


            //shortPosition.Count() >= 1)
            if (false)
            {
                if (BullishHangingMan(1))
                {
//                    Print("SL reached and close all positions");
                    ClosePosition(Positions.Find("Nasser" + Symbol.Code));
                    TP1Flag = false;
                    TP2Flag = false;
                }
            }
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }

        protected override void OnTick()
        {
            var position1 = Positions.Find("Nasser" + Symbol.Code, Symbol);
            if (Positions.Count(x => x.SymbolCode == Symbol.Code) > 0)
            {
                if (!TP1Flag && position1.Pips >= TP1)
                {
                    int newvol = System.Convert.ToInt32(Symbol.NormalizeVolumeInUnits(Symbol.QuantityToVolumeInUnits(lot * (1 - TP1Percent / 100)), RoundingMode.Down));
                    ModifyPosition(position1, newvol);
                    BreakEven(0.5);
                    TP1Flag = true;
                }
                if (position1.Pips >= TP2)
                {
                    Print("TP2 Reached)");
                    int newvol = System.Convert.ToInt32(Symbol.NormalizeVolumeInUnits(Symbol.QuantityToVolumeInUnits(lot * (1 - (TP1Percent + TP2Percent) / 100)), RoundingMode.Down));
                    ModifyPosition(position1, 0);
                    //  BreakEven(TP1);
//                    Print("Stop Loss moved to TP1");
                    TP1Flag = false;
//                    TP2Flag = true;
                }
            }
        }

        // Volume Calculator
        public double VolumeCal(double SL)
        {
            //return the volume based on lot and not in units, it should be converted to unit to use in C#
            lot = Account.Balance * riskpercent / (SL * 1000);
            return (lot);
        }


        private bool TradingHour()
        {
            if (Time.Hour >= StartingTradingHour && Time.Hour <= EndingTradingHour)
                return true;
            else
                return false;
        }
        // Trailing Stop
        //*******************************
        private void BreakEven(double AddPips)
        {
            var position = Positions.Find("Nasser" + Symbol.Code, Symbol);
            //            if (position == null)
            //            {
            //                Print("Position not found. Stopping cBot");
            //                Stop();
            //                return;
            //            }
            var desiredNetProfitInDepositAsset = AddPips * Symbol.PipValue * position.VolumeInUnits;
            var desiredGrossProfitInDepositAsset = desiredNetProfitInDepositAsset - position.Commissions * 2 - position.Swap;
            var quoteToDepositRate = Symbol.PipValue / Symbol.PipSize;
            var priceDifference = desiredGrossProfitInDepositAsset / (position.VolumeInUnits * quoteToDepositRate);

            var priceAdjustment = GetPriceAdjustmentByTradeType(position.TradeType, priceDifference);
            var breakEvenLevel = position.EntryPrice + priceAdjustment;
            var roundedBreakEvenLevel = RoundPrice(breakEvenLevel, position.TradeType);

            ModifyPosition(position, roundedBreakEvenLevel, position.TakeProfit);

            Print("Stop loss for position DID" + position.Id + " has been moved to break even.");
            Print("Stopping cBot..");

        }

        private void PrintErrorAndStop(string errorMessage)
        {
            Print(errorMessage);
            Stop();

            throw new Exception(errorMessage);
        }


        private double RoundPrice(double price, TradeType tradeType)
        {
            var multiplier = Math.Pow(10, Symbol.Digits);

            if (tradeType == TradeType.Buy)
                return Math.Ceiling(price * multiplier) / multiplier;

            return Math.Floor(price * multiplier) / multiplier;
        }

        private static double GetPriceAdjustmentByTradeType(TradeType tradeType, double priceDifference)
        {
            if (tradeType == TradeType.Buy)
                return priceDifference;

            return -priceDifference;
        }

        // Price Cross SMA Downward
        private bool PriceCrossSMADownward()
        {
            if (SmallSeries.Close.Last(2) >= SMAShort.Result.Last(2) && SmallSeries.Close.Last(1) < SMAShort.Result.Last(1))
                return true;
            else
                return false;
        }


        //Price Cross SMA Upward
        private bool PriceCrossSMAUpward()
        {
            if (SmallSeries.Close.Last(2) <= SMAShort.Result.Last(2) && SmallSeries.Close.Last(1) > SMAShort.Result.Last(1))
                return true;
            else
                return false;
        }
        //Bullish Hanging Man 
        private bool BullishHangingMan(int i)
        {
            if ((MediumSeries.High.Last(i) - Math.Max(MediumSeries.Close.Last(i), MediumSeries.Open.Last(i))) > (5.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))))
                Print("Entered to Bullish Hanging Man Routine");
            if ((MediumSeries.High.Last(i) - MediumSeries.Low.Last(i)) >= (8.0 / 10.0 * AtrMedium.Result.Last(1)) && (MediumSeries.High.Last(i) - Math.Max(MediumSeries.Close.Last(i), MediumSeries.Open.Last(i))) > (5.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))) && (Math.Abs(MediumSeries.Close.Last(i) - MediumSeries.Open.Last(i))) < (4.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))) && (Math.Min(MediumSeries.Open.Last(i), MediumSeries.Close.Last(i)) - MediumSeries.Low.Last(i)) < (3.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))))
            {
                Print("Bullish Candle");
                return true;
            }
            else
                return false;
        }

        //Bearish Hanging Man
        private bool BearishHangingMan(int i)
        {
            if ((Math.Min(MediumSeries.Close.Last(i), MediumSeries.Open.Last(i)) - MediumSeries.Low.Last(i)) > (5.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))))
                Print("Entered to Bearish Hanging Man Routine");
            if ((MediumSeries.High.Last(i) - MediumSeries.Low.Last(i)) >= (8.0 / 10.0 * AtrMedium.Result.Last(i)) && (Math.Min(MediumSeries.Close.Last(i), MediumSeries.Open.Last(i)) - MediumSeries.Low.Last(i)) > (5.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))) && (Math.Abs(MediumSeries.Close.Last(i) - MediumSeries.Open.Last(i))) < (4.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))) && (MediumSeries.High.Last(i) - Math.Max(MediumSeries.Open.Last(i), MediumSeries.Close.Last(i))) < (3.0 / 10.0 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i))))
            {
                Print("Bearish Hanging Man");
                return true;
            }
            else
                return false;
        }

        //Bullish Full Body Candle
        private bool BullishFullBodyCandle(int i)
        {
            if (MediumSeries.Close.Last(i) > MediumSeries.Open.Last(i) && (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i)) > (0.8 * AtrMedium.Result.Last(i)) && (MediumSeries.Close.Last(i) - MediumSeries.Open.Last(i)) > 0.7 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i)))
            {
//                Print("Bullish Full Body Candle");
                return true;
            }
            else
                return false;
        }
        //Bearish Full Body Candle
        private bool BearishFullBodyCandle(int i)
        {
            if (MediumSeries.Close.Last(i) < MediumSeries.Open.Last(i) && (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i)) > (0.8 * AtrMedium.Result.Last(i)) && (MediumSeries.Open.Last(i) - MediumSeries.Close.Last(i)) > 0.7 * (MediumSeries.High.Last(i) - MediumSeries.Low.Last(i)))
            {
                //              Print("Bearish Full Body Candle");
                return true;
            }
            else
                return false;
        }

        // Buy Pattern One includes FullBodyBearishCandle followed by Bulish Hanging Man Candle
        private bool BuyPatternOne()
        {
            if (BearishFullBodyCandle(2) && BullishHangingMan(1))
            {
                Print("Buy Flag is true");
                return true;
            }
            else
                return false;
        }

        // Sell Pattern One includes FullBodyBulishCandle followed by Bearish Hanging Man Candle
        private bool SellPatternOne()
        {
            if (BullishFullBodyCandle(2) && BearishHangingMan(1))
            {
                Print("Sell Flag is true");
                return true;
            }
            else
                return false;
        }
        //Buy Pattern Two incldes three candles 
    }
    /*        private bool BuyPatternTwo()
        {
            if (BearishFullBodyCandle(3) && BearishHangingMan(1) && BullishHangingMan(2))
                return true;
            else
                return false;
        }

        //Sell Pattern Two includes three candles
        private bool SellPatternTwo()
        {
            if (BullishFullBodyCandle(3) && BullishHangingMan(1) && BearishHangingMan(2))
                return true;
            else
                return false;
        }
        //Buy Pattern Three
        private bool BuyPatternThree()
        {
            return true;
        }

        //Sell Pattern Three
        private bool SellPatternThree()
        {
            return true;
        }*/
}


@nh.zadeh
Replies

firemyst
09 Apr 2019, 04:04

Have you tried debugging using Visual Studio? You can put breakpoints and go line-by-line to see where the code is going and why values are being set.

If not, how about posting code with Print statements in every single "if" block?

For example, instead of this:

if (TradingHour())
            {
                //Open Long Position
                if (!BuyFlag && (Positions.Count(x => x.SymbolCode == Symbol.Code) == 0) && BuyPatternOne())
                {
                    BuyFlag = true;
                    StopLossPoint = Math.Min(MediumSeries.Low.Last(1), MediumSeries.Low.Last(2));
                }
                if (MediumSeries.Close.Last(1) < StopLossPoint)
                {
                    BuyFlag = false;
                }
                if (BuyFlag && PriceCrossSMAUpward())
                {
                    StopLossPoint = Math.Min(MediumSeries.Low.LastValue, Math.Min(MediumSeries.Low.Last(1), MediumSeries.Low.Last(2)));
                    StopLoss = Math.Round((SmallSeries.Close.Last(1) - StopLossPoint) / Symbol.PipSize, 1);
                    lot = VolumeCal(StopLoss);
                    ExecuteMarketOrder(TradeType.Buy, Symbol, Symbol.NormalizeVolumeInUnits(Symbol.QuantityToVolumeInUnits(lot), RoundingMode.Down), "Nasser" + Symbol.Code, StopLoss + 4, null, 0.5);
                    TP1Flag = false;
                    BuyFlag = false;
                    //                    TP2Flag = false;
                }
            }

 

Have you tried this and seeing what the output is in the log:

            if (TradingHour())
            {
                Print("Inside TradingHour()");
                //Open Long Position
                if (!BuyFlag && (Positions.Count(x => x.SymbolCode == Symbol.Code) == 0) && BuyPatternOne())
                {
                    BuyFlag = true;
                    StopLossPoint = Math.Min(MediumSeries.Low.Last(1), MediumSeries.Low.Last(2));
                    Print("1");
                }
                if (MediumSeries.Close.Last(1) < StopLossPoint)
                {
                    BuyFlag = false;
                    Print("2");
                }
                if (BuyFlag && PriceCrossSMAUpward())
                {
                    StopLossPoint = Math.Min(MediumSeries.Low.LastValue, Math.Min(MediumSeries.Low.Last(1), MediumSeries.Low.Last(2)));
                    StopLoss = Math.Round((SmallSeries.Close.Last(1) - StopLossPoint) / Symbol.PipSize, 1);
                    lot = VolumeCal(StopLoss);
                    ExecuteMarketOrder(TradeType.Buy, Symbol, Symbol.NormalizeVolumeInUnits(Symbol.QuantityToVolumeInUnits(lot), RoundingMode.Down), "Nasser" + Symbol.Code, StopLoss + 4, null, 0.5);
                    TP1Flag = false;
                    BuyFlag = false;
                    //                    TP2Flag = false;
                    Print("3");
                }
            }

etc etc.

Put the Print statements in every block so you can trace through the code and see what's happening if you can't use Visual Studio debugging.

 


@firemyst