How do i place a stop loss on this basic cAlgo

Created at 30 Jun 2017, 21:51
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!
GA

How do i place a stop loss on this basic cAlgo
30 Jun 2017, 21:51


// -------------------------------------------------------------------------------------------------
I would like to minimise losses in monetary or pips value how can i place a stop loss e.g $50 for the robot to stop trading.
// -------------------------------------------------------------------------------------------------

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 MovingAverage : Robot
    {
        [Parameter("MA Type")]
        public MovingAverageType MAType { get; set; }

        [Parameter()]
        public DataSeries SourceSeries { get; set; }

        [Parameter("Slow Periods", DefaultValue = 10)]
        public int SlowPeriods { get; set; }

        [Parameter("Fast Periods", DefaultValue = 26)]
        public int FastPeriods { get; set; }

        [Parameter("Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double Quantity { get; set; }

       
        private MovingAverage slowMa;
        private MovingAverage fastMa;
        private const string label = "Sample Trend cBot";

        protected override void OnStart()
        {
            fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
            slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
        }

        protected override void OnTick()
        {
            var longPosition = Positions.Find(label, Symbol, TradeType.Buy);
            var shortPosition = Positions.Find(label, Symbol, TradeType.Sell);

            var currentSlowMa = slowMa.Result.Last(0);
            var currentFastMa = fastMa.Result.Last(0);
            var previousSlowMa = slowMa.Result.Last(1);
            var previousFastMa = fastMa.Result.Last(1);

            if (previousSlowMa > previousFastMa && currentSlowMa <= currentFastMa && longPosition == null)
            {
                if (shortPosition != null)
                    ClosePosition(shortPosition);
                ExecuteMarketOrder(TradeType.Buy, Symbol, VolumeInUnits, label);
            }
            else if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa && shortPosition == null)
            {
                if (longPosition != null)
                    ClosePosition(longPosition);
                ExecuteMarketOrder(TradeType.Sell, Symbol, VolumeInUnits, label);
            }
        }

        private long VolumeInUnits
        {
            get { return Symbol.QuantityToVolume(Quantity); }
        }
    }
}


@gabriel@shockmedia.co.zw
Replies

amsman
01 Jul 2017, 05:08

Code with SL and TP added.

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 MovingAverageStrategy : Robot
    {

        //parameters

        [Parameter("MA Type")]
        public MovingAverageType MAType { get; set; }

        [Parameter()]
        public DataSeries SourceSeries { get; set; }

        [Parameter("Slow Periods", DefaultValue = 10)]
        public int SlowPeriods { get; set; }

        [Parameter("Fast Periods", DefaultValue = 26)]
        public int FastPeriods { get; set; }

        [Parameter("Quantity (Lots)", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
        public double Quantity { get; set; }

        [Parameter("TakeProfitPips", DefaultValue = 5, MinValue = 0)]
        public int TP { get; set; }

        [Parameter("StopLossPips", DefaultValue = 5, MinValue = 0)]
        public int SL { get; set; }

        private MovingAverage slowMa;

        private MovingAverage fastMa;

        private const string label = "Sample Trend cBot";

        protected override void OnStart()
        {
            fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
            slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
        }
        protected override void OnTick()
        {
            //declaring variables during ticks
            var longPosition = Positions.Find(label, Symbol, TradeType.Buy);
            var shortPosition = Positions.Find(label, Symbol, TradeType.Sell);
            var currentSlowMa = slowMa.Result.Last(0);
            var currentFastMa = fastMa.Result.Last(0);
            var previousSlowMa = slowMa.Result.Last(1);
            var previousFastMa = fastMa.Result.Last(1);

            if (previousSlowMa > previousFastMa && currentSlowMa <= currentFastMa && longPosition == null)
            {
                if (shortPosition != null)
                    ClosePosition(shortPosition);
                ExecuteMarketOrder(TradeType.Buy, Symbol, VolumeInUnits, label, SL, TP);
            }
            else if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa && shortPosition == null)
            {
                if (longPosition != null)
                    ClosePosition(longPosition);
                ExecuteMarketOrder(TradeType.Sell, Symbol, VolumeInUnits, label, SL, TP);
            }
        }

        private long VolumeInUnits
        {
            get { return Symbol.QuantityToVolume(Quantity); }
        }
    }
}

 

// I had to change the Robot name to MovingAverageStrategy for the code to build correctly.


@amsman

amsman
01 Jul 2017, 07:17

Moving Average Strategies

Moving Average Strategies in theory should be profitable, but with spread and the price algorithms in FX they tend to be the fastest account reducing agent known to man. No matter which MAType or Period Values you use, at the point of crossover the fast MA will bounce up and down over the slow MA giving off numerous false signals which with spread, will result in numerous losing trades before price happily meanders off in a particular direction. We have coded a few Strategy “protections” for MA Crosses but we are constantly refining the logic all the time… 2 steps forward, one step back…. It’s mind numbing.

You have to add second or third (even fourth!) trade confirmation logic so price action does not continually defeat the strategy at the MA crossover point. Either a trade delay mechanism so that the position isn’t opened until the Fast MA has cleared the Slow MA (measured in pips or closed candles) or a second even slower MA that triggers the trade once it has also crossed in the direction of the trend. One indicator (of a great many tested) we use for confirmation is the CCI indicator (-100 / +100) for confirmation, so that the MA Cross will not trigger a trade until the CCI value has crossed above the -100 (-170) for a Buy or passes down through the +100 for a sell. That just covers the crossover points, you also have to have the included logic for when price action pulls back during a trend, generally all the way to the slow MA and tries to shake you out mid trade……. That’s even harder to program for…


@amsman