Only one trade

Created at 28 Mar 2013, 18:13
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

Only one trade
28 Mar 2013, 18:13


Hi!

 

I'm very new in this kind of programming robots. I'm working on some existing robots an I would like what i have to add to a script to make only one trade at a time, and no more trades till the one opened is closed by taking profit or stop loss.

 

Thanks a lot,

Mandril


@MANDRIL
Replies

MANDRIL
28 Mar 2013, 18:59

Here it is the robot...it is the one of the samples....it just keep making orders...and i would like just to open a trade and closed it. 

 

// -------------------------------------------------------------------------------------------------
//
//    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 Breakout Robot" will check the difference in pips between the Upper Bollinger Band and the Lower Bollinger Band 
//    and compare it against the "Band Height" parameter specified by the user.  If the height  is lower than the number of pips 
//    specified, the market is considered to be consolidating, and the first candlestick to cross the upper or lower band will 
//    generate a buy or sell signal. The user can specify the number of periods that the market should be consolidating in the 
//    "Consolidation Periods" parameter. The position is closed by a Stop Loss or Take Profit.  
//
// -------------------------------------------------------------------------------------------------

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

namespace cAlgo.Robots
{
    [Robot]
    public class SampleBreakoutRobot : Robot
    {
        [Parameter]
        public DataSeries Source { get; set; }

        [Parameter("Stop Loss", DefaultValue = 10, MinValue = 1)]
        public int StopLossInPips { get; set; }

        [Parameter("Take Profit", DefaultValue = 10, MinValue = 1)]
        public int TakeProfitInPips { get; set; }

        [Parameter("Volume", DefaultValue = 10000, MinValue = 1000)]
        public int Volume { get; set; }

        [Parameter("Bollinger Bands Deviations", DefaultValue = 2)]
        public int Deviations { get; set; } // BB

        [Parameter("Bollinger Bands Periods", DefaultValue = 20)]
        public int Periods { get; set; } // BB
        
        [Parameter("Bollinger Bands MA Type")]
        public MovingAverageType MAType { get; set; } // BB

        private BollingerBands bollingerBands;

        protected override void OnStart()    
                
        {
            bollingerBands = Indicators.BollingerBands(Source, Periods, Deviations, MAType);
        }

        
        protected override void OnTick()
        {
            double top = bollingerBands.Top.LastValue;
            double bottom = bollingerBands.Bottom.LastValue;

                if (Symbol.Ask > top)
                {
                    var request = new MarketOrderRequest(TradeType.Sell, Volume)
                    {
                        Label = "SampleBreakoutRobot",
                        StopLossPips = StopLossInPips,
                        TakeProfitPips = TakeProfitInPips
                    };

                    Trade.Send(request);

                }
                else if (Symbol.Bid < bottom)
                {
                    var request = new MarketOrderRequest(TradeType.Buy, Volume)
                    {
                        Label = "SampleBreakoutRobot",
                        StopLossPips = StopLossInPips,
                        TakeProfitPips = TakeProfitInPips
                    };

                    Trade.Send(request); 
                    
                }
            }
        }


    }


@MANDRIL

cAlgo_Fanatic
29 Mar 2013, 09:24

Hello,

You can declare a field for position that will be set when the position opens and set to null when it closes. Prior to the code that executes the trade requests check that this field is null. Therefore, you will not start a new trade if there is an open position by this robot.

private Position position;

[Parameter]
public DataSeries Source { get; set; }
// ...

 protected override void OnBar()
 {
     if (Trade.IsExecuting || position != null)
         return;
    // ...
}
protected override void OnPositionOpened(Position openedPosition)
{
      position = openedPosition; 
}
protected override void OnPositionClosed(Position closedPosition)
{
      position = null;
}





@cAlgo_Fanatic

MANDRIL
08 Apr 2013, 20:21

Thanks a lot!!!!!!!!!!!!


@MANDRIL

ABC1
16 Mar 2018, 20:37

Full code

Please post the full code here for us non-programmers.


@ABC1

PanagiotisCharalampous
19 Mar 2018, 10:14

Hi Pipdays,

Thanks for posting in our forum.What is the full code you are looking for? The code sample posted above by Spotware can be incorporated in any cBot however it does not do anything as a standalone code sample. It is just an example on how to add this logic in your own cBot.

Best Regards,

Panagiotis


@PanagiotisCharalampous

NyanHtet
25 Sep 2019, 20:56

Should i Add this code at the bottom or at the top?

 

for example.

this is the break out Cbot code.

where should i add it?

 

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 SampleBreakoutcBot : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("Band Height (pips)", DefaultValue = 40.0, MinValue = 0)]
        public double BandHeightPips { get; set; }

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

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

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

        [Parameter("Bollinger Bands Deviations", DefaultValue = 2)]
        public double Deviations { get; set; }

        [Parameter("Bollinger Bands Periods", DefaultValue = 20)]
        public int Periods { get; set; }

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

        [Parameter("Consolidation Periods", DefaultValue = 2)]
        public int ConsolidationPeriods { get; set; }

        BollingerBands bollingerBands;
        string label = "Sample Breakout cBot";
        int consolidation;

        protected override void OnStart()
        {
            bollingerBands = Indicators.BollingerBands(Source, Periods, Deviations, MAType);
        }

        protected override void OnBar()
        {

            var top = bollingerBands.Top.Last(1);
            var bottom = bollingerBands.Bottom.Last(1);

            if (top - bottom <= BandHeightPips * Symbol.PipSize)
            {
                consolidation = consolidation + 1;
            }
            else
            {
                consolidation = 0;
            }

            if (consolidation >= ConsolidationPeriods)
            {
                var volumeInUnits = Symbol.QuantityToVolume(Quantity);
                if (Symbol.Ask > top)
                {
                    ExecuteMarketOrder(TradeType.Buy, Symbol, volumeInUnits, label, StopLossInPips, TakeProfitInPips);

                    consolidation = 0;
                }
                else if (Symbol.Bid < bottom)
                {
                    ExecuteMarketOrder(TradeType.Sell, Symbol, volumeInUnits, label, StopLossInPips, TakeProfitInPips);

                    consolidation = 0;
                }
            }
        }
    }
}


@NyanHtet

PanagiotisCharalampous
26 Sep 2019, 08:22

Hi NyanHtet,

Thanks for posting in our forum. See the modified code below

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 SampleBreakoutcBot : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("Band Height (pips)", DefaultValue = 40.0, MinValue = 0)]
        public double BandHeightPips { get; set; }

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

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

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

        [Parameter("Bollinger Bands Deviations", DefaultValue = 2)]
        public double Deviations { get; set; }

        [Parameter("Bollinger Bands Periods", DefaultValue = 20)]
        public int Periods { get; set; }

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

        [Parameter("Consolidation Periods", DefaultValue = 2)]
        public int ConsolidationPeriods { get; set; }

        BollingerBands bollingerBands;
        string label = "Sample Breakout cBot";
        int consolidation;
        private Position position;
        protected override void OnStart()
        {
            bollingerBands = Indicators.BollingerBands(Source, Periods, Deviations, MAType);
            Positions.Opened += OnPositionsOpened;
            Positions.Closed += OnPositionsClosed;
        }

        void OnPositionsClosed(PositionClosedEventArgs obj)
        {
            position = null;
        }

        void OnPositionsOpened(PositionOpenedEventArgs obj)
        {
            position = obj.Position;
        }

        protected override void OnBar()
        {
            if (position != null)
                return;
            var top = bollingerBands.Top.Last(1);
            var bottom = bollingerBands.Bottom.Last(1);

            if (top - bottom <= BandHeightPips * Symbol.PipSize)
            {
                consolidation = consolidation + 1;
            }
            else
            {
                consolidation = 0;
            }

            if (consolidation >= ConsolidationPeriods)
            {
                var volumeInUnits = Symbol.QuantityToVolume(Quantity);
                if (Symbol.Ask > top)
                {
                    ExecuteMarketOrder(TradeType.Buy, Symbol, volumeInUnits, label, StopLossInPips, TakeProfitInPips);

                    consolidation = 0;
                }
                else if (Symbol.Bid < bottom)
                {
                    ExecuteMarketOrder(TradeType.Sell, Symbol, volumeInUnits, label, StopLossInPips, TakeProfitInPips);

                    consolidation = 0;
                }
            }
        }
    }
}

Best Regards,

Panagiotis


@PanagiotisCharalampous