Martingale edit

Created at 17 Feb 2017, 07:34
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!
DE

derekszyszka

Joined 15.10.2016

Martingale edit
17 Feb 2017, 07:34


Can someone show me how to change the code from opening a random position, to being able to open specifically a long or short position while still employing the martingale strategy?

// -------------------------------------------------------------------------------------------------
//
//    This code is a cAlgo API sample.
//
//    This robot 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
//
//    All changes to this file will be lost on next application start.
//    If you are going to modify this file please make a copy using the "Duplicate" command.
//
//    The "Sample Martingale Robot" 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 robot 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.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;
        }
    }
}

 


@derekszyszka
Replies

tradermatrix
17 Feb 2017, 15:15

Hello

I have cut a piece of my bot code

/algos/cbots/show/192

You can choose the direction that wish you to buy or sell.

and even reverse the direction of the losing trades

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

        ///////////////////////////////////////////////////////

        [Parameter("SETTING BUY", DefaultValue = "___BUY___")]
        public string Separator1 { get; set; }

        //////////////////////////////////////////////////////

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

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

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

        [Parameter("Take Profit", DefaultValue = 80)]
        public double TakeProfit { get; set; }

        [Parameter("Start Martingale Buy", DefaultValue = true)]
        public bool StartMartingaleBuy { get; set; }

        [Parameter("Change the direction Martingale", DefaultValue = false)]
        public bool change1 { get; set; }

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

        [Parameter("Max Volume Martingale Buy", DefaultValue = 1.2, MinValue = 0.01, Step = 0.01)]
        public double Quantity1Max { get; set; }

        [Parameter("Start Automate Buy", DefaultValue = false)]
        public bool StartAutomate1 { get; set; }


        ///////////////////////////////////////////////////////

        [Parameter("SETTING SELL", DefaultValue = "___SELL___")]
        public string Separator2 { get; set; }

        //////////////////////////////////////////////////////

        [Parameter("Start Sell", DefaultValue = false)]
        public bool Sell { get; set; }

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

        [Parameter("Stop Loss", DefaultValue = 60)]
        public double StopLoss2 { get; set; }

        [Parameter("Take Profit", DefaultValue = 80)]
        public double TakeProfit2 { get; set; }

        [Parameter("Start Martingale Sell", DefaultValue = true)]
        public bool StartMartingaleSell { get; set; }

        [Parameter("change the direction Martingale", DefaultValue = false)]
        public bool change2 { get; set; }

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

        [Parameter("Max Volume  Martingale Sell", DefaultValue = 1.2, MinValue = 0.01, Step = 0.01)]
        public double Quantity2Max { get; set; }

        [Parameter("Start Automate Sell", DefaultValue = false)]
        public bool StartAutomate2 { get; set; }




        ///////////////////////////////////////////////////////////////////////////

        public long volumeMax1;
        public long volumeMax2;


        public double earn1;
        public double earn2;



        protected override void OnStart()
        {

            string text = "PayBacK  By TraderMatriX";

            base.ChartObjects.DrawText("PayBacK  By TraderMatriX", text, StaticPosition.TopCenter, new Colors?(Colors.Lime));


            buy();
            Positions.Closed += OnPositionsClosed1;
            Positions.Closed += OnPositionsClosed2;
            Positions.Closed += OnPositionsClosedReturnBuy;


            sell();
            Positions.Closed += OnPositionsClosed3;
            Positions.Closed += OnPositionsClosed4;
            Positions.Closed += OnPositionsClosedReturnSell;



            var volumeInUnits1Max = Symbol.QuantityToVolume(Quantity1Max);

            volumeMax1 = volumeInUnits1Max;

            var volumeInUnits2Max = Symbol.QuantityToVolume(Quantity2Max);

            volumeMax2 = volumeInUnits2Max;



            DisplayEarn();

        }


        protected override void OnTick()
        {


            var netProfit = 0.0;


            foreach (var openedPosition in Positions)
            {

                netProfit += openedPosition.NetProfit + openedPosition.Commissions;


            }

            ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime));

            DisplayEarn();

            NetProfit1();
            NetProfit2();



        }

        private string GenerateText()
        {

            var e1 = "";
            var e2 = "";


            var earnText = "";

            e1 = "\nBuy  =       " + earn1;
            e2 = "\nSell =       " + earn2;



            earnText = e1 + e2;
            return (earnText);
        }

        private void DisplayEarn()
        {

            ChartObjects.DrawText("text", GenerateText(), StaticPosition.TopRight, Colors.Aqua);
        }

        private void NetProfit1()
        {

            earn1 = 0;



            foreach (var pos in Positions)
            {
                if (pos.Label.StartsWith("buy PayBack"))
                {
                    earn1 += pos.NetProfit + pos.Commissions;
                }

            }
        }



        private void NetProfit2()
        {


            earn2 = 0;

            foreach (var pos2 in Positions)
            {
                if (pos2.Label.StartsWith("sell PayBack"))
                {
                    earn2 += pos2.NetProfit + pos2.Commissions;
                }
            }
        }


        private void buy()
        {


            if (Buy == true)
            {

                var cBotPositions = Positions.FindAll("buy PayBack");

                if (cBotPositions.Length >= 1)
                    return;


                var volumeInUnits1 = Symbol.QuantityToVolume(Quantity1);


                ExecuteMarketOrder(TradeType.Buy, Symbol, volumeInUnits1, "buy PayBack", StopLoss, TakeProfit);
                Print("ExecuteMarketOrder,Quantity initial Buy");
            }
        }

        private void sell()
        {
            if (Sell == true)
            {

                var cBotPositions = Positions.FindAll("sell PayBack");

                if (cBotPositions.Length >= 1)
                    return;


                var volumeInUnits2 = Symbol.QuantityToVolume(Quantity2);

                ExecuteMarketOrder(TradeType.Sell, Symbol, volumeInUnits2, "sell PayBack", StopLoss2, TakeProfit2);
                Print("ExecuteMarketOrder,Quantity initial Sell");

            }
        }



        private void OnPositionsClosed1(PositionClosedEventArgs args)
        {
            if (Buy == true)

                if (StartMartingaleBuy == true)

                    if (StartAutomate1 == true)
                    {

                        Print("martingale active + Automate Active...buy PayBack");

                        var position = args.Position;

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


                        if (position.Pips > 0)
                            buy();
                        {




                            if (position.GrossProfit < 0)
                            {


                                if (change1 == true)
                                {

                                    TradeType AA = TradeType.Sell;

                                    if (position.TradeType == TradeType.Sell)

                                        AA = TradeType.Buy;



                                    if (position.Volume * Multiplier <= volumeMax1)

                                        ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit);
                                    Print("loss;inverse direction buy PayBack");
                                }

                                else if (change1 == false)
                                {
                                    TradeType BB = TradeType.Sell;



                                    BB = TradeType.Buy;


                                    if (position.Volume * Multiplier <= volumeMax1)

                                        ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit);
                                    Print("loss; NO inverse direction buy PayBack");

                                }

                            }

                        }

                    }
        }




        private void OnPositionsClosed2(PositionClosedEventArgs args)
        {

            if (Buy == true)

                if (StartMartingaleBuy == true)

                    if (StartAutomate1 == false)
                    {

                        Print("martingale active + Automate inactive...buy PayBack");

                        var position = args.Position;

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


                        if (position.Pips > 0)
                            return;
                        {

                            if (position.GrossProfit < 0)
                            {

                                if (change1 == true)
                                {
                                    TradeType AA = TradeType.Sell;

                                    if (position.TradeType == TradeType.Sell)

                                        AA = TradeType.Buy;

                                    if (position.Volume * Multiplier <= volumeMax1)


                                        ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit);
                                    Print("loss; inverse direction buy PayBack");
                                }


                                else if (change1 == false)
                                {
                                    TradeType BB = TradeType.Sell;


                                    BB = TradeType.Buy;

                                    if (position.Volume * Multiplier <= volumeMax1)


                                        ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit);
                                    Print("loss; NO inverse direction buy PayBack");



                                }

                            }

                        }

                    }

        }


        private void OnPositionsClosedReturnBuy(PositionClosedEventArgs args)
        {
            if (Buy == true)
                if (StartMartingaleBuy == true)

                    if (StartAutomate1 == true)
                    {

                        var volumeInUnits1Max = Symbol.QuantityToVolume(Quantity1Max);


                        var position = args.Position;

                        if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code)
                            return;
                        if (position.Volume * Multiplier >= volumeInUnits1Max)

                            buy();

                    }
        }


        private void OnPositionsClosed3(PositionClosedEventArgs args)
        {

            if (Sell == true)

                if (StartMartingaleSell == true)

                    if (StartAutomate2 == true)
                    {


                        Print("martingale active + Automate Active...sell PayBack");

                        var position = args.Position;

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


                        if (position.Pips > 0)
                            sell();
                        {


                            if (position.GrossProfit < 0)
                            {

                                if (change2 == true)
                                {
                                    TradeType AA = TradeType.Sell;

                                    if (position.TradeType == TradeType.Sell)

                                        AA = TradeType.Buy;

                                    if (position.Volume * Multiplier2 <= volumeMax2)


                                        ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2);
                                    Print("loss; inverse direction sell PayBack");
                                }

                                else if (change2 == false)
                                {
                                    TradeType BB = TradeType.Buy;



                                    BB = TradeType.Sell;

                                    if (position.Volume * Multiplier2 <= volumeMax2)


                                        ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2);
                                    Print("loss; NO inverse direction sell PayBack");



                                }

                            }

                        }

                    }

        }


        private void OnPositionsClosed4(PositionClosedEventArgs args)
        {

            if (Sell == true)

                if (StartMartingaleSell == true)

                    if (StartAutomate2 == false)
                    {


                        Print("martingale active + Automate inactive...sell PayBack");

                        var position = args.Position;

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


                        if (position.Pips > 0)
                            return;
                        {

                            if (position.GrossProfit < 0)
                            {

                                if (change2 == true)
                                {
                                    TradeType AA = TradeType.Sell;

                                    if (position.TradeType == TradeType.Sell)

                                        AA = TradeType.Buy;

                                    if (position.Volume * Multiplier2 <= volumeMax2)


                                        ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2);
                                    Print("loss; inverse direction sell PayBack");
                                }


                                else if (change2 == false)
                                {
                                    TradeType BB = TradeType.Buy;



                                    BB = TradeType.Sell;


                                    if (position.Volume * Multiplier2 <= volumeMax2)

                                        ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2);
                                    Print("loss; NO inverse direction sell PayBack");



                                }

                            }

                        }

                    }

        }

        private void OnPositionsClosedReturnSell(PositionClosedEventArgs args)
        {
            if (Sell == true)
                if (StartMartingaleSell == true)

                    if (StartAutomate2 == true)
                    {

                        var volumeInUnits2Max = Symbol.QuantityToVolume(Quantity2Max);


                        var position = args.Position;

                        if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code)
                            return;
                        if (position.Volume * Multiplier2 >= volumeInUnits2Max)

                            if (position.GrossProfit < 0)

                                sell();

                    }
        }

    }

}
























 


@tradermatrix

derekszyszka
17 Feb 2017, 16:03

RE:

tradermatrix said:

Hello

I have cut a piece of my bot code

/algos/cbots/show/192

You can choose the direction that wish you to buy or sell.

and even reverse the direction of the losing trades


 

Thank you very much. Any addition tips or instruction when using this bot? What is your strategy with this algo?

THanks again


@derekszyszka

derekszyszka
17 Feb 2017, 16:03

RE:

tradermatrix said:

Hello

I have cut a piece of my bot code

/algos/cbots/show/192

You can choose the direction that wish you to buy or sell.

and even reverse the direction of the losing trades


 

Thank you very much. Any addition tips or instruction when using this bot? What is your strategy with this algo?

THanks again


@derekszyszka