Stop robot when a pair reaches certain amount of loss

Created at 31 Jul 2019, 16:46
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!
CT

ctid1373829

Joined 19.07.2019 Blocked

Stop robot when a pair reaches certain amount of loss
31 Jul 2019, 16:46


Hi, it would be great help if someone could please combine these two codes.  I have been trying whole day but no success.  Basically its a martingle robot.  I want to add an option that when certin amount of loss in that SYMBOL/chart has reached, robot will stop and close all opene positions (in that SYMBOL/chart only).  Amount of loss can be entered in pips in the option box

Regards 

 

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

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MartingaleRobot : Robot
    {
        [Parameter("Initial Volume", DefaultValue = 10000, MinValue = 0)]
        public int InitialVolume { get; set; }

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

        [Parameter("Take Profit", DefaultValue = 40)]
        public int TakeProfit { get; set; }
        
        private Random random = new Random();

        protected override void OnStart()
        {
            Positions.Closed += OnPositionsClosed;

            ExecuteOrder(InitialVolume, GetRandomTradeType());
        }

        private void ExecuteOrder(long volume, TradeType tradeType)
        {
            var result = ExecuteMarketOrder(tradeType, Symbol, volume, "Martingale", StopLoss, TakeProfit);

            if (result.Error == ErrorCode.NoMoney)
                Stop();
        }

        private void OnPositionsClosed(PositionClosedEventArgs args)
        {
            Print("Closed");
            var position = args.Position;

            if (position.Label != "Martingale" || position.SymbolCode != Symbol.Code)
                return;

            if (position.GrossProfit > 0)
            {
                ExecuteOrder(InitialVolume, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder((int)position.Volume * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}
private double startingBalance;
private const double BalancePercent = 0.10;
 
protected override void OnStart()
{
    startingBalance = Account.Balance;
}
protected override void OnTick()
{
    CheckBalance();
    //...
}
 
private void CheckBalance()
{            
    if (Account.Equity <= startingBalance * BalancePercent)
    {
        // close all account positions
        foreach (var pos in Account.Positions)
        {
            Trade.Close(pos);
        }
        Stop(); // Stop the robot
    }
}

 


Replies

AlgoGuru
01 Aug 2019, 10:06

Hi ,

Martingale is the most dangerous system. I do not recommend to you and to everybody to use it.

I have been developing FX systems since 2010. I used to use/develop Martingale and Grid systems  from 2012 - 2014 but all of them are time bomb.

I have seen lot of crashed real accounts by Martingale. It requires huge balance at least 50 000$ for 0.01 starting lot and all balance is risk at every trade.

Martingale robots go head to wall. It has not deep trend analysis. Sometimes enter the market with blind eyes. As your sample shows (randomly).

This is the best way to lose.

The good system require the following elements:

- Identify where the price  moves. (Up, down or range?)

- Try to catch the good momentum when to enter the market on the right side with good Risk/reward ratio

- Use proper money management

These are the 3 most important legs for success. If one or more missing: you will fail!

You can see some better systems at my site: www.algoguru.hu

Best Regards,

AlgoGURU


@AlgoGuru

firemyst
20 Aug 2019, 17:48

One option you have is to keep a running total of your robot using a C# Dictionary<string,double> object in your close event method:

//Keep the running total of losses and consecutive trade losses
                    if (_runningTotalsGainLoss.ContainsKey(p1.Label))
                        _runningTotalsGainLoss[p1.Label] += p1.NetProfit;
                    else
                        _runningTotalsGainLoss.Add(p1.Label, p1.NetProfit);

And then do a simple check:

if (_runningTotalsGainLoss[p1.Label] < [your loss threshold parameter])
                    {
                        Print("WARNING! Running total {0} has fallen below {1} threshold! Stopping bot for \"{2}\"!", String.Format("{0:$#,###.00}", _runningTotalsGainLoss[p1.Label]), String.Format("{0:$#,###.00}", [your loss threshold parameter]), p1.Label);
                        Stop();
                        return;
                    }

 


@firemyst