Trades incorrectly being closed

Created at 05 Apr 2024, 08:41
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!
GB

gbg561

Joined 05.04.2024

Trades incorrectly being closed
05 Apr 2024, 08:41


Good morning

I hope someone can help.

I am a novice at bot programming and currently using the cTrader Algo to create a bot for testing. I am looking at a simple 20 & 50 sma crossover bot with trade confirmation from the ADX. Please see an overview as follows;

Monitors the 20 & 50 period sma’s 

Monitors the ADX (Average Directional Index)

Places a single BUY Stop Loss Order after the close of the first candle after the 20 period sma crosses above the 50 period sma and the ADX >20

Places a single SELL Stop Loss Order after the close of the first candle below the 20 period sma crosses below the 50 period sma and the ADX >20

Closes trades;

When the stop loss or take profit targets are triggered 

If the 20 & 50 period sma’s cross before the stop loss or take profit targets are triggered

Allows for manual configuration of the, Start Trade Time, end Trade time, Stop Loss and Take Profit targets.

I have found an anomaly where the bot occasionally appears to be closing trades at the stop loss target i.e.20 pips when a trade has not hit the stop loss target or the sma’s have not crossed;

Please see the complete code below;

Any advice would be greatly appreciated.

Thanks, Gary

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.Indicators;

namespace cAlgo.Robots
{
    [Robot(TimeZone= TimeZones.UTC, AccessRights= AccessRights.None)]
    public class SMACrossADXBot: Robot
    {
        [Parameter("Start Trade Time (HH:MM)", DefaultValue= "08:00")]
        publicstring StartTradeTime{ get; set; }

        [Parameter("End Trade Time (HH:MM)", DefaultValue= "22:00")]
        publicstring EndTradeTime{ get; set; }

        [Parameter("Volume",DefaultValue =10000, MinValue= 1)]
        publicint Volume{ get; set;}
        
        [Parameter("Lot Size",DefaultValue =0.01, MinValue= 0.01)]
        publicdouble LotSize{ get; set; }


        [Parameter("Stop Loss (pips)", DefaultValue= 10)]
        publicint StopLossInPips{ get; set; }

        [Parameter("Take Profit (pips)", DefaultValue= 10)]
        publicint TakeProfitInPips{ get; set; }

        [Parameter("ADX Period",DefaultValue =14)]
        publicint AdxPeriod{ get; set; }

        [Parameter("ADX Threshold",DefaultValue =20)]
        publicdouble AdxThreshold{ get; set; }

        privateMovingAverage sma20;
        privateMovingAverage sma50;
        privateDirectionalMovementSystem dms;
        privateTimeSpan startTradeTime;
        privateTimeSpan endTradeTime;

        protectedoverride voidOnStart()
        {
              
           
           sma20 = Indicators.MovingAverage(Bars.ClosePrices, 20,MovingAverageType.Simple);
            sma50 = Indicators.MovingAverage(Bars.ClosePrices, 50,MovingAverageType.Simple);
            dms = Indicators.DirectionalMovementSystem(AdxPeriod);

            startTradeTime =TimeSpan.Parse(StartTradeTime);
            endTradeTime =TimeSpan.Parse(EndTradeTime);
        }

        protectedoverride voidOnBar()
        {
            if (Server.Time.TimeOfDay< startTradeTime|| Server.Time.TimeOfDay> endTradeTime)
                return;

            if (sma20.Result.HasCrossedAbove(sma50.Result,1) &&dms.ADX.LastValue >AdxThreshold)
            {
                //var volumeInUnits = Symbol.QuantityToVolumeInUnits(Volume);
                var volumeInUnits= Symbol.QuantityToVolumeInUnits(LotSize);
                // ExecuteMarketOrder(TradeType.Buy, SymbolName, volumeInUnits);
                var tradeResult= ExecuteMarketOrder(TradeType.Buy, SymbolName,volumeInUnits,"SMACrossADXBot", StopLossInPips,TakeProfitInPips);

                if (tradeResult.IsSuccessful)
                {
                    Print("Buy order placed at {0}", tradeResult.Position.EntryPrice);
                }
            }
            else if (sma20.Result.HasCrossedBelow(sma50.Result, 1)&& dms.ADX.LastValue> AdxThreshold)
            {
                //var volumeInUnits = Symbol.QuantityToVolumeInUnits(Volume);
                var volumeInUnits= Symbol.QuantityToVolumeInUnits(LotSize);
                var tradeResult= ExecuteMarketOrder(TradeType.Sell, SymbolName,volumeInUnits,"SMACrossADXBot", StopLossInPips,TakeProfitInPips);

                if (tradeResult.IsSuccessful)
                {
                    Print("Sell order placed at {0}", tradeResult.Position.EntryPrice);
                }
            }
        }

        protectedoverride voidOnTick()
        {
            foreach (var position in Positions)
            {
                if (position.SymbolName!= SymbolName|| position.Label != "SMACrossADXBot")
                    continue;

                if (position.TradeType== TradeType.Buy &&sma20.Result.LastValue < sma50.Result.LastValue)
                {
                    ClosePosition(position);
                }
                else if (position.TradeType ==TradeType.Sell&& sma20.Result.LastValue> sma50.Result.LastValue)
                {
                    ClosePosition(position);
                }
            }
        }


@gbg561
Replies

PanagiotisCharalampous
05 Apr 2024, 09:14

Hi Gary,

Please share with us exact cBot parameters, backtesting settings and the trades you think are wrong.

Best regards,

Panagiotis


@PanagiotisCharalampous

gbg561
05 Apr 2024, 11:12 ( Updated at: 07 Apr 2024, 05:23 )

RE: Trades incorrectly being closed

PanagiotisCharalampous said: 

Hi Gary,

Please share with us exact cBot parameters, backtesting settings and the trades you think are wrong.

Best regards,

Panagiotis

Hi Panagiotis

Thanks for your prompt reply.

I have updated my original thread with a screenshot of the issue with the parameters as requested.

Please let me know if there is anything else I should include.

Thanks

Gary


@gbg561