i want to add a take profit and a stop loss to the sample trend robot how do i do it?

Created at 25 Jun 2013, 20:40
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!
HA

hamza786

Joined 24.06.2013

i want to add a take profit and a stop loss to the sample trend robot how do i do it?
25 Jun 2013, 20:40


i want to add a take profit and stop loss to the sample trend robot. how do i do it?

 


@hamza786
Replies

tradermatrix
25 Jun 2013, 22:01

using System.Collections.Generic;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Robots
{
    [Robot]
    public class SampleMultiplePositions : Robot
    {
        private readonly List<Position> _listPosition = new List<Position>();

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

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

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

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

        [Parameter(DefaultValue = 100000)]
        public int Volume { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 100)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 100)]
        public int TakeProfit { get; set; }

        [Parameter("Trigger (pips)", DefaultValue = 10)]
        public int Trigger { get; set; }

        [Parameter("Trailing Stop (pips)", DefaultValue = 10)]
        public int TrailingStop { get; set; }


        [Parameter("MinBalance", DefaultValue = 40000)]
        public double MinBalance { get; set; }

        [Parameter("MinLoss", DefaultValue = -200.0)]
        public double MinLoss { get; set; }
        

        private MovingAverage _slowMa;
        private MovingAverage _fastMa;
        

        ///
        /// Initialize Indicators
        ///
        protected override void OnStart()
        {
            _fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
            _slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
        }
        protected override void OnBar()
        {

            if (Trade.IsExecuting) return;
            
            int lastIndex = _slowMa.Result.Count - 2;
            int prevIndex = _slowMa.Result.Count - 3;

            double currentSlowMa = _slowMa.Result[lastIndex];
            double currentFastMa = _fastMa.Result[lastIndex];

            double previousSlowMa = _slowMa.Result[prevIndex];
            double previousFastMa = _fastMa.Result[prevIndex];

            // Condition to Buy
            if (previousSlowMa > previousFastMa && currentSlowMa <= currentFastMa )
            {
                if(_listPosition.Count < 3)
                    Buy();
            }

            // Condition to Sell
            if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa )
            {
                if (_listPosition.Count < 3)
                    Sell();
            }
            
            // Trailing Stop for all positions
            SetTrailingStop();

            // Some condition to close all positions
            if (Account.Balance < MinBalance)
            {
                CloseAllPositions();
            }

            // Some condition to close one position
            foreach (Position position in _listPosition)
            {
                if (position.GrossProfit < MinLoss)
                {
                    ClosePosition(position);
                }                
            }

        }

        ///
        /// Add newly opened position to list and set stop loss and take profit
        ///
        ///
        protected override void OnPositionOpened(Position openedPosition)
        {
            _listPosition.Add(openedPosition);

            double? stopLossPrice = null;
            double? takeProfitSize = null;

            if (StopLoss != 0)
            {
                if (openedPosition.TradeType == TradeType.Buy)
                {
                    stopLossPrice = openedPosition.EntryPrice - StopLoss*Symbol.PipSize;
                }
                else
                {
                    stopLossPrice = openedPosition.EntryPrice + StopLoss*Symbol.PipSize;
                }
            }

            if (TakeProfit != 0)
            {
                if (openedPosition.TradeType == TradeType.Buy)
                {
                    takeProfitSize = openedPosition.EntryPrice + TakeProfit*Symbol.PipSize;
                }
                else
                {
                    takeProfitSize = openedPosition.EntryPrice - TakeProfit * Symbol.PipSize;
                }
            }

            Trade.ModifyPosition(openedPosition, stopLossPrice, takeProfitSize);

        }

        ///
        /// Remove closed position from list
        ///
        ///
        protected override void OnPositionClosed(Position closedPosition)
        {
            if (_listPosition.Contains(closedPosition))
            {
                _listPosition.Remove(closedPosition);
            }
        }

        ///
        /// Create Buy Order
        ///
        private void Buy()
        {
            Trade.CreateBuyMarketOrder(Symbol, Volume);
        }

        ///
        /// Create Sell Order
        ///
        private void Sell()
        {
            Trade.CreateSellMarketOrder(Symbol, Volume);
        }

        ///
        ///  When the profit in pips is above or equal to Trigger the stop loss will start trailing the spot price.
        //   TrailingStop defines the number of pips the Stop Loss trails the spot price by. If Trigger is 0 trailing will begin immediately. 
        ///
        private void SetTrailingStop()
        {
            foreach (Position position in _listPosition)
            {

                if (position.TradeType == TradeType.Sell)
                {
                    double distance = position.EntryPrice - Symbol.Ask;

                    if (distance >= Trigger * Symbol.PipSize)
                    {
                        double newStopLossPrice = Symbol.Ask + TrailingStop * Symbol.PipSize;

                        if (position.StopLoss == null || newStopLossPrice < position.StopLoss)
                        {
                            Trade.ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                        }
                    }
                }
                else
                {
                    double distance = Symbol.Bid - position.EntryPrice;

                    if (distance >= Trigger * Symbol.PipSize)
                    {
                        double newStopLossPrice = Symbol.Bid - TrailingStop * Symbol.PipSize;
                        if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                        {
                            Trade.ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                        }
                    }
                }
            }
        }

        ///
        /// Close all position in list
        ///
        private void CloseAllPositions()
        {
            foreach (Position position in _listPosition)
            {
                ClosePosition(position);
            }
        }

        ///
        /// Close Position
        ///
        ///
        private void ClosePosition(Position pos)
        {
            if (pos == null) 
                return;
            
            Trade.Close(pos);

        }

    }
}

 


@tradermatrix

hamza786
26 Jun 2013, 16:46

RE: error


im getting two errors like this ... error Expected class, delegate, enum, interface, or struct


@hamza786

cAlgo_Fanatic
26 Jun 2013, 17:51

See the solution here /algos/robots/show/309


@cAlgo_Fanatic

hamza786
26 Jun 2013, 19:36

RE:
cAlgo_Fanatic said:

See the solution here /algos/robots/show/309


thank you very much


@hamza786