How to add rRailing Stop Loss to a Robot

Created at 17 Apr 2013, 03: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!
MA

MANDRIL

Joined 28.03.2013

How to add rRailing Stop Loss to a Robot
17 Apr 2013, 03:41


Hi, I'm trying to add a Trailing stop loss to this robot but i'm going crazy using some examples, whether they don't work or they stop my robot.

 

Thanks a lot :)

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

namespace cAlgo.Robots
{
    [Robot]
    public class TradingNewsRobot : Robot        
    {
        [Parameter("News Day (1-5)", DefaultValue=1, MinValue=1, MaxValue=5)]
        public int NewsDay  { get; set; }
                
        [Parameter("News Hour", DefaultValue=14, MinValue=0, MaxValue=23)]
        public int NewsHour  { get; set; }
        
        [Parameter("News Minute", DefaultValue=30, MinValue=0, MaxValue=59)]
        public int NewsMinute  { get; set; }
    
        [Parameter("Pips away", DefaultValue=10)]
        public int PipsAway  { get; set; }
    
        [Parameter("Take Profit", DefaultValue=50)]
        public int TakeProfit  { get; set; }   

        [Parameter("Stop Loss", DefaultValue=10)]
        public int StopLoss  { get; set; }
                
        [Parameter("Volume", DefaultValue=100000, MinValue=10000)]
        public int Volume  { get; set; }               
                
        [Parameter("Seconds Before", DefaultValue=5, MinValue=1)]
        public int SecondsBefore  { get; set; }
        
        [Parameter("Seconds Timeout", DefaultValue=10, MinValue=1)]
        public int SecondsTimeout  { get; set; }
        
        [Parameter("One Cancels Other", DefaultValue=1, MinValue=0, MaxValue=1)]
        public int Oco  { get; set; }
        
        private bool _ordersCreated;
        private PendingOrder _buyOrder;
        private PendingOrder _sellOrder;
        
        protected override void OnStart()
        {
            MarketData.GetMarketDepth(Symbol).Updated += MarketDepth_Updated;
        }
        
        void MarketDepth_Updated()
        {
            if ((int)Server.Time.DayOfWeek == NewsDay && !_ordersCreated)
            {
                var triggerTime = new DateTime(Server.Time.Year, Server.Time.Month, Server.Time.Day, NewsHour, NewsMinute, 0);
                
                if (Server.Time <= triggerTime && (triggerTime - Server.Time).TotalSeconds <= SecondsBefore)
                {
                    _ordersCreated = true;                    
                    var expirationTime = triggerTime.AddSeconds(SecondsTimeout);
                    
                    var sellOrderTargetPrice = Symbol.Bid - PipsAway * Symbol.PipSize;                    
                    Trade.CreateSellStopOrder(Symbol, Volume, sellOrderTargetPrice,
                        sellOrderTargetPrice + StopLoss * Symbol.PipSize, sellOrderTargetPrice - TakeProfit * Symbol.PipSize, expirationTime);    

                    var buyOrderTargetPrice = Symbol.Ask + PipsAway * Symbol.PipSize;
                    Trade.CreateBuyStopOrder(Symbol, Volume, buyOrderTargetPrice,
                        buyOrderTargetPrice - StopLoss * Symbol.PipSize, buyOrderTargetPrice + TakeProfit * Symbol.PipSize, expirationTime);
                }
            }
        }
                
        protected override void OnPendingOrderCreated(PendingOrder newOrder)
        {
            if (newOrder.TradeType == TradeType.Buy)
                _buyOrder = newOrder;
            else
                _sellOrder = newOrder;
        }
        
        protected override void OnPositionOpened(Position openedPosition)
        {
            if (Oco == 1)
            {
                Trade.DeletePendingOrder(_buyOrder);
                Trade.DeletePendingOrder(_sellOrder);
            }
        }        
    }
}

 


@MANDRIL
Replies

MANDRIL
17 Apr 2013, 03:47

Plus Trigger Pips

I forgot to mention, if it is possible to add also a trigger pips that will make begin the Trailing stop immediately. I tried the examples but :(


@MANDRIL

tradermatrix
17 Apr 2013, 12:03

bonjour,

Dans la journée ou en soirée je partagerais mon "scalper programmable".

Il fonctionne avec un déclencheur(trigger) et un stop suiveur(trailing stop).

Vous aurez le choix pour la stratégie . 

Vous pourrez l améliorer  selon vos désirs.

Je dois m absenter un moment.

@+


@tradermatrix

atrader
17 Apr 2013, 14:57

Hi Mandril,

I added the code from the cAlgo samples (Sample Buy/Sell Trailing) to your code and uploaded here: /algos/robots/show/257

 


@atrader

cAlgo_Fanatic
17 Apr 2013, 15:10

The reason the robot stops working is probably in this line:

if ((int) Server.Time.DayOfWeek == NewsDay && !_ordersCreated

ordersCreated is set to true when the first two pending orders are created and never set back to false. 

You probably want to set it back to false when you delete those orders, unless the logic intended is to create 2 pending orders and stop. In that case you may want to stop the robot by adding this line Stop();

right after you delete the orders.


@cAlgo_Fanatic

MANDRIL
18 Apr 2013, 20:33

RE:
atrader said:

Hi Mandril,

I added the code from the cAlgo samples (Sample Buy/Sell Trailing) to your code and uploaded here: /algos/robots/show/257

 

Thanks a lot!!!


@MANDRIL

MANDRIL
18 Apr 2013, 20:33

RE:
cAlgo_Fanatic said:

The reason the robot stops working is probably in this line:

if ((int) Server.Time.DayOfWeek == NewsDay && !_ordersCreated

ordersCreated is set to true when the first two pending orders are created and never set back to false. 

You probably want to set it back to false when you delete those orders, unless the logic intended is to create 2 pending orders and stop. In that case you may want to stop the robot by adding this line Stop();

right after you delete the orders.

Thank you very much!!!


@MANDRIL

2005267
02 Aug 2014, 19:03

RE:

cAlgo_Fanatic said:

Hi,

Having trouble to make it work. 

Can anybody help me please.

forextradingservices2011@hotmail.co.uk

Thanks

 


@2005267

aysos75
02 Aug 2014, 22:40

RE:

MANDRIL said:

Hi, I'm trying to add a Trailing stop loss to this robot but i'm going crazy using some examples, whether they don't work or they stop my robot.

 

Thanks a lot :)

A generic method to add trailling stop to a robot :

/// <summary>
		/// Manage Trail Stop
		/// </summary>
		/// <param name="position">Used position</param>
		/// <param name="robot">instance of the current robot</param>
		/// <param name="trailStart">start of the movement of stoploss</param>
		/// <param name="trailStep">steps stoploss</param>
		/// <param name="trailStopMin">Minimal StopLoss</param>
		/// <param name="isModifyPosition">change the stoploss position or not ?</param>
		/// <returns>The new stoploss</returns>
		public static double? trailStop(this  Position position, Robot robot, int trailStart, int trailStep, int trailStopMin, bool isModifyPosition=true)
		{
			double? newStopLoss = position.StopLoss;	
			
			if (position.Pips > trailStart)
			{
				double actualPrice = position.isBuy() ? robot.Symbol.Bid : robot.Symbol.Ask;
				int factor = position.factor();

				if ((actualPrice - newStopLoss) * factor > (trailStep + trailStopMin) * robot.Symbol.PipSize)
				{
					newStopLoss += factor * trailStep * robot.Symbol.PipSize;

					if (isModifyPosition && newStopLoss != position.StopLoss)
						robot.ModifyPosition(position, newStopLoss, position.TakeProfit.Value);
				}
			}

			return newStopLoss;
		}

The entire library code is at this adress : calgobots


@aysos75