Martingale cbot

Created at 06 Oct 2015, 19:39
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!
NI

nirin

Joined 09.12.2013

Martingale cbot
06 Oct 2015, 19:39


Hi,

Please help,

With the code below, how can i insert my own signals from indicators without using a random Sell or Buy order,

and stop to double the volume amount after 3 consecutive loss trades (every position from my signals).

 

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 SampleMartingalecBot : Robot
    {
        [Parameter("Initial Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double InitialQuantity { 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(InitialQuantity, GetRandomTradeType());
        }

        private void ExecuteOrder(double quantity, TradeType tradeType)
        {
            var volumeInUnits = Symbol.QuantityToVolume(quantity);
            var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "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(InitialQuantity, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder(position.Quantity * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}

 


@nirin
Replies

ClickAlgo
06 Oct 2015, 21:20

To reference custom indicators on ctdn look at this:-

/api/guides/indicators#el8

The link below shows an example of how to use the generic in-built indicators in cAlgo.

/forum/calgo-reference-samples/56


@ClickAlgo

moneybiz
06 Oct 2015, 21:23

It's not hard to do but you need to learn C# and cAlgo to code your own bots since you're asking for complete robot.

If you don't want to learn or need some assistance there are people who can help you.
There is a member named Paul Hayes (and maybe others too), as far as I remember he is giving coding lessons as well as teaches how to code robots in cAlgo.
If you want you can check his profile or you can ask for help in jobs section.

No money no honey. :)


@moneybiz

moneybiz
06 Oct 2015, 21:24

Haha, interesting coincidence. He also replied to your message before mine.

That's the guy who can help you.


@moneybiz

ClickAlgo
07 Oct 2015, 08:35

That is very kind of you moneybiz, thank you.


@ClickAlgo

tradermatrix
07 Oct 2015, 15:50

RE:

nirin said:

Hi,

Please help,

With the code below, how can i insert my own signals from indicators without using a random Sell or Buy order,

and stop to double the volume amount after 3 consecutive loss trades (every position from my signals).

 

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 SampleMartingalecBot : Robot
    {
        [Parameter("Initial Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double InitialQuantity { 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(InitialQuantity, GetRandomTradeType());
        }

        private void ExecuteOrder(double quantity, TradeType tradeType)
        {
            var volumeInUnits = Symbol.QuantityToVolume(quantity);
            var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "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(InitialQuantity, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder(position.Quantity * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}

 

Hello
according to this model,
you can add a martingale your robots.
"Max Run" allows you to adjust the number of rounds you want and control your losses.
example
if volume 10000
and loss maxi 40000
set "max run" 41000 .... so stop loss has touched 40000 ....
 martingale stop... complete series ....
back to other trades
there is no doubt of other solutions,
I am using this method.
Best regards.

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


        [Parameter(DefaultValue = " TrenD ")]
        public string cBotLabel { get; set; }

        [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 = 5)]
        public int FastPeriods { get; set; }

        [Parameter(DefaultValue = 3)]
        public int MaxPositions { get; set; }

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

        [Parameter("Stop Loss 1    (pips)", DefaultValue = 120)]
        public int sl1 { get; set; }

        [Parameter("Take Profit 1  (pips)", DefaultValue = 30)]
        public int tp1 { get; set; }

        ////////////////////////////////martingale///////////////////////////////////////

        [Parameter("Start martingale ", DefaultValue = true)]
        public bool Startmartingale { get; set; }

        [Parameter("Stop Loss martingale ", DefaultValue = 120)]
        public double sl2 { get; set; }

        [Parameter("Take Profit martingale ", DefaultValue = 120)]
        public double tp2 { get; set; }

        [Parameter("Multiplier Ordre ", DefaultValue = 2.1)]
        public double Multiplier { get; set; }

        [Parameter(" Max Run ", DefaultValue = 41000)]
        public int MaxRun { get; set; }

        private MovingAverage slowMa;
        private MovingAverage fastMa;


        private const string label2 = " TrenD.X ";



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

        protected override void OnBar()
        {

            var cBotPositions = Positions.FindAll(cBotLabel);

            if (cBotPositions.Length > MaxPositions)
                return;



            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)

                ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, cBotLabel, sl1, tp1);


            else if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa)


                ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, cBotLabel, sl1, tp1);



        }


        private void OnPositionsClosed(PositionClosedEventArgs args)
        {
            if (Startmartingale == true)
            {

                Print("Closed");
                var position = args.Position;
                if (position.Label != cBotLabel || position.SymbolCode != Symbol.Code)
                    if (position.Label != label2 || position.SymbolCode != Symbol.Code)
                        return;
                if (position.GrossProfit < 0)
                {

                    {
                        ExecuteOrder(getNewVolume((int)position.Volume), position.TradeType);
                    }
                }
            }
        }
        private void ExecuteOrder(long volume, TradeType tradeType)
        {
            var result = ExecuteMarketOrder(tradeType, Symbol, volume, label2, sl2, tp2);
            if (result.Error == ErrorCode.NoMoney)
                Stop();
        }

        private int getNewVolume(int posVol)
        {
            var newVol = posVol * 2;
            newVol = Math.Min(newVol, MaxRun);
            if (newVol == MaxRun)
                newVol = Volume;
            Print("newVol = {0}", newVol);
            return newVol;
        }
    }
}

 


@tradermatrix

tradermatrix
07 Oct 2015, 21:42

to make operational:

 [Parameter("Multiplier Ordre ", DefaultValue = 2.1)]
 public double Multiplier { get; set; }

replaces;

   private int getNewVolume(int posVol)
        {
            var newVol = posVol * 2;
            newVol = Math.Min(newVol, MaxRun);
            if (newVol == MaxRun)
                newVol = Volume;
            Print("newVol = {0}", newVol);
            return newVol;

by:

   [Parameter("Multiplier Ordre ", DefaultValue = 2)]
    public int Multiplier { get; set; }

  private int getNewVolume(int posVol)
        {
     private int getNewVolume(int posVol)
        {
            var newVol = posVol * Multiplier;
            newVol = Math.Min(newVol, MaxRun);
            if (newVol == MaxRun)
                newVol = Volume;
            Print("newVol = {0}", newVol);
            return newVol;


@tradermatrix

nirin
08 Oct 2015, 16:38

Hi Paul Hayes, Moneybiz & Tradematrix,

Thanks a lot for your help and advice.

Best regards


@nirin

amantalpur007@gmail.com
09 Jul 2017, 19:30

RE: RE:

HI, i use Sample MArtingale Cbot. in that cbot. i want this cbot to stop doubling my postion after 5 consecutive loses. please tell me the code to do so. i saw your comment and in that comment you've added MAs. i just want to add a setting so that cbot stops doubling after 5 consecutive loses. my email is amantalpur007@gmail.com. i've inserted code of that cbot. please write the whole coding including my need. i shall be really grateful to you.

// -------------------------------------------------------------------------------------------------
//
//    This code is a cAlgo API sample.
//
//    This cBot is intended to be used as a sample and does not guarantee any particular outcome or
//    profit of any kind. Use it at your own risk
//
//    The "Sample Martingale cBot" creates a random Sell or Buy order. If the Stop loss is hit, a new 
//    order of the same type (Buy / Sell) is created with double the Initial Volume amount. The cBot will 
//    continue to double the volume amount for  all orders created until one of them hits the take Profit. 
//    After a Take Profit is hit, a new random Buy or Sell order is created with the Initial Volume amount.
//
// -------------------------------------------------------------------------------------------------

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 SampleMartingalecBot : Robot
    {
        [Parameter("Initial Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double InitialQuantity { 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(InitialQuantity, GetRandomTradeType());
        }

        private void ExecuteOrder(double quantity, TradeType tradeType)
        {
            var volumeInUnits = Symbol.QuantityToVolume(quantity);
            var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "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(InitialQuantity, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder(position.Quantity * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}

 

tradermatrix said:

nirin said:

Hi,

Please help,

With the code below, how can i insert my own signals from indicators without using a random Sell or Buy order,

and stop to double the volume amount after 3 consecutive loss trades (every position from my signals).

 

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 SampleMartingalecBot : Robot
    {
        [Parameter("Initial Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double InitialQuantity { 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(InitialQuantity, GetRandomTradeType());
        }

        private void ExecuteOrder(double quantity, TradeType tradeType)
        {
            var volumeInUnits = Symbol.QuantityToVolume(quantity);
            var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "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(InitialQuantity, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder(position.Quantity * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}

 

Hello
according to this model,
you can add a martingale your robots.
"Max Run" allows you to adjust the number of rounds you want and control your losses.
example
if volume 10000
and loss maxi 40000
set "max run" 41000 .... so stop loss has touched 40000 ....
 martingale stop... complete series ....
back to other trades
there is no doubt of other solutions,
I am using this method.
Best regards.

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


        [Parameter(DefaultValue = " TrenD ")]
        public string cBotLabel { get; set; }

        [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 = 5)]
        public int FastPeriods { get; set; }

        [Parameter(DefaultValue = 3)]
        public int MaxPositions { get; set; }

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

        [Parameter("Stop Loss 1    (pips)", DefaultValue = 120)]
        public int sl1 { get; set; }

        [Parameter("Take Profit 1  (pips)", DefaultValue = 30)]
        public int tp1 { get; set; }

        ////////////////////////////////martingale///////////////////////////////////////

        [Parameter("Start martingale ", DefaultValue = true)]
        public bool Startmartingale { get; set; }

        [Parameter("Stop Loss martingale ", DefaultValue = 120)]
        public double sl2 { get; set; }

        [Parameter("Take Profit martingale ", DefaultValue = 120)]
        public double tp2 { get; set; }

        [Parameter("Multiplier Ordre ", DefaultValue = 2.1)]
        public double Multiplier { get; set; }

        [Parameter(" Max Run ", DefaultValue = 41000)]
        public int MaxRun { get; set; }

        private MovingAverage slowMa;
        private MovingAverage fastMa;


        private const string label2 = " TrenD.X ";



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

        protected override void OnBar()
        {

            var cBotPositions = Positions.FindAll(cBotLabel);

            if (cBotPositions.Length > MaxPositions)
                return;



            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)

                ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, cBotLabel, sl1, tp1);


            else if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa)


                ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, cBotLabel, sl1, tp1);



        }


        private void OnPositionsClosed(PositionClosedEventArgs args)
        {
            if (Startmartingale == true)
            {

                Print("Closed");
                var position = args.Position;
                if (position.Label != cBotLabel || position.SymbolCode != Symbol.Code)
                    if (position.Label != label2 || position.SymbolCode != Symbol.Code)
                        return;
                if (position.GrossProfit < 0)
                {

                    {
                        ExecuteOrder(getNewVolume((int)position.Volume), position.TradeType);
                    }
                }
            }
        }
        private void ExecuteOrder(long volume, TradeType tradeType)
        {
            var result = ExecuteMarketOrder(tradeType, Symbol, volume, label2, sl2, tp2);
            if (result.Error == ErrorCode.NoMoney)
                Stop();
        }

        private int getNewVolume(int posVol)
        {
            var newVol = posVol * 2;
            newVol = Math.Min(newVol, MaxRun);
            if (newVol == MaxRun)
                newVol = Volume;
            Print("newVol = {0}", newVol);
            return newVol;
        }
    }
}

 

 


@amantalpur007@gmail.com

yosifov
13 Jul 2017, 17:50

RE:

the Maringale funnction is not working. ... after a SL is hit the cbot opens new trade in the same direction.


@yosifov

BeardPower
13 Jul 2017, 18:11

Hi,

it's because of the line

ExecuteOrder(getNewVolume((int)position.Volume), position.TradeType);

in

private void OnPositionsClosed(PositionClosedEventArgs args)

It will always open the same trade direction, as the closed position.

To trade in the opposite direction of the closed position, you need to modify it to e.g. like this:

ExecuteOrder(getNewVolume((int)position.Volume), position.TradeType == TradeType.Buy ? TradeType.Sell : TradeType.Buy);

HTH.


@BeardPower

DelFonseca
19 Jun 2018, 02:50

Hi

When he starts the martingale, he doesnt check the strategy. Hitting the stoploss he open a new order without check if strategy = true.

How do I check the strategy again and if there is true, open martingale order?

thank you


@DelFonseca

Alwin123
08 Dec 2022, 17:58

RE: good day, have you already found an answer to your question? I am also looking for the solution for this.

DelFonseca said:

Hi

When he starts the martingale, he doesnt check the strategy. Hitting the stoploss he open a new order without check if strategy = true.

How do I check the strategy again and if there is true, open martingale order?

thank you

 


@Alwin123