Replies

samuelbreezey
02 Sep 2020, 21:30

Thank you Panagiotis 

Can you help me out with the coding please?

Many thanks
Sam


@samuelbreezey

samuelbreezey
24 Aug 2020, 21:14

RE:

PanagiotisCharalampous said:

Hi Sam,

Please explain why do you think it is not loaded properly? What is the indicator supposed to do? What did you expect to see and what do you see instead?

Best Regards,

Panagiotis 

Join us on Telegram

 

Hi Panagiotis 

Reason being no data from before 4th August 2020. I was expecting to see data before this date, however instead it was blank

Thanks
Sam


@samuelbreezey

samuelbreezey
20 Aug 2020, 10:49

RE:

PanagiotisCharalampous said:

Hi Sam,

See an example below

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

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = false, AccessRights = AccessRights.None)]
    public class TickVolumeTheMinimalTrader : Indicator
    {

        [Output("UpVolume", LineColor = "Green", PlotType = PlotType.Histogram, Thickness = 4)]
        public IndicatorDataSeries UpVolume { get; set; }

        [Output("DownVolume", LineColor = "Red", PlotType = PlotType.Histogram, Thickness = 4)]
        public IndicatorDataSeries DownVolume { get; set; }

        [Output("MA", LineColor = "Blue", PlotType = PlotType.Line, Thickness = 4)]
        public IndicatorDataSeries MA { get; set; }

        [Parameter(DefaultValue = 10)]
        public int Periods { get; set; }

        private MovingAverage volumeMA;

        protected override void Initialize()
        {
            // Initialize and create nested indicators    
            volumeMA = Indicators.MovingAverage(Bars.TickVolumes, Periods, MovingAverageType.Simple);
        }

        public override void Calculate(int index)
        {
            UpVolume[index] = Bars.TickVolumes[index];
            if (UpVolume[index] < UpVolume[index - 1])
                DownVolume[index] = UpVolume[index];
            else
                DownVolume[index] = 0;
            MA[index] = volumeMA.Result[index];
        }
    }
}

Best Regards,

Panagiotis 

Join us on Telegram

 

Thank you Panagiotis,

Is there a way to show the indicator on the actual chart?

Sam


@samuelbreezey

samuelbreezey
20 Aug 2020, 00:57

RE:

samuelbreezey said:

Hi guys

I am wanting to add the moving average indicator to my tick volume indicator which calculates the average tick volume price.

Is this possible? My code is below:

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

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = false, AccessRights = AccessRights.None)]
    public class TickVolumeMM : Indicator
    {

        [Output("UpVolume", Color = Colors.Green, PlotType = PlotType.Histogram, Thickness = 1)]
        public IndicatorDataSeries UpVolume { get; set; }

        [Output("DownVolume", Color = Colors.Red, PlotType = PlotType.Histogram, Thickness = 1)]
        public IndicatorDataSeries DownVolume { get; set; }

        protected override void Initialize()
        {
            // Initialize and create nested indicators
        }

        public override void Calculate(int index)
        {
            UpVolume[index] = MarketSeries.TickVolume[index];
            if (UpVolume[index] < UpVolume[index - 1])
                DownVolume[index] = UpVolume[index];
            else
                DownVolume[index] = 0;
        }
    }
}

 

I would love some help on the code or if someone could send me in the right direction.

I look forward to hearing from you guys

Sam

 

Just need the calculation...

 

Have added the MA:

 

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

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = false, AccessRights = AccessRights.None)]
    public class TickVolumeTheMinimalTrader : Indicator
    {

        [Output("UpVolume", LineColor = "Green", PlotType = PlotType.Histogram, Thickness = 4)]
        public IndicatorDataSeries UpVolume { get; set; }

        [Output("DownVolume", LineColor = "Red", PlotType = PlotType.Histogram, Thickness = 4)]
        public IndicatorDataSeries DownVolume { get; set; }

        [Parameter(DefaultValue = 10)]
        public int Periods { get; set; }

        [Output("Moving Average Colour", LineColor = "Turquoise")]
        public IndicatorDataSeries MAColour { get; set; }

        private IndicatorDataSeries MAVol;
        private MovingAverage volumeMA;

        protected override void Initialize()
        {
            // Initialize and create nested indicators
            MAVol = CreateDataSeries();
            volumeMA = Indicators.MovingAverage(MAVol, Periods, MovingAverageType.Simple);
        }

        public override void Calculate(int index)
        {
            UpVolume[index] = Bars.TickVolumes[index];
            if (UpVolume[index] < UpVolume[index - 1])
                DownVolume[index] = UpVolume[index];
            else
                DownVolume[index] = 0;
        }
    }
}

 


@samuelbreezey

samuelbreezey
15 Aug 2020, 11:06

RE:

samuelbreezey said:

Hi All

I have my stop loss automatically set and I wanted to know how to adjust an open position if the initial risk in pips (open price - stop loss) is above 3%. I am having trouble incorporating the pip value from the order into the foreach (var position in Positions) section of code.

I assume slPriceS & slPriceB change each time which is why my bot isn't working how I would like.

If there is a better way to do this, i would love to hear your thoughts :)

Many thanks
Sam

Figured out that I can adjust the order when position is in profit by certain percentage using the following:

 var PositionPnL = Math.Round(100 * Positions.Sum(t => t.NetProfit) / Account.Balance, 1);

Full code:

foreach (var position in Positions.FindAll(InstanceName, SymbolName))
            {
                var shortPosition = Positions.Find(InstanceName, SymbolName, TradeType.Sell);
                var longPosition = Positions.Find(InstanceName, SymbolName, TradeType.Buy);
                var shortPositionsCount = Positions.Count(p => p.TradeType == TradeType.Sell);
                var longPositionsCount = Positions.Count(p => p.TradeType == TradeType.Buy);
                var PositionPnL = Math.Round(100 * Positions.Sum(t => t.NetProfit) / Account.Balance, 1);
                if (position.StopLoss != position.EntryPrice && longPositionsCount > 0)
                {
                    if (PositionPnL >= 0.5 && PositionPnL < 3)
                    {
                        ModifyPosition(position, position.EntryPrice, position.TakeProfit);
                    }
                }
                else if (position.StopLoss != position.EntryPrice && shortPositionsCount > 0)
                {
                    if (PositionPnL >= 0.5 && PositionPnL < 3)
                    {
                        ModifyPosition(position, position.EntryPrice, position.TakeProfit);
                    }
                }

            }

 


@samuelbreezey

samuelbreezey
13 Aug 2020, 13:10

RE: RE: Stop Loss at previous days low or previous days high

firemyst said:

samuelbreezey said:

Hi Guys

I am trying to get my stop loss on a execute at market to be @ the previous days low. My code does'nt seem to work :( may be something simple...

Help needed please.

Try posting some code so people can see what you're doing wrong..

 

Hi,

I have figured this out now using ModifyStopLossPrice right after the order is placed. 

See the following resolved thread:

https://ctrader.com/forum/cbot-support/24493

Many thanks
Sam


@samuelbreezey

samuelbreezey
11 Aug 2020, 16:21

RE:

PanagiotisCharalampous said:

Hi Sam,

Yes you are right, I misread the code. If the difference is slight then this is expected since you are calculating the stop loss distance based on the current price and not based on the position's entry price which might deviate due to slippage. If you need to place the stop loss on an exact price then you need to modify the position after it has been opened.

Best Regards,

Panagiotis 

Join us on Telegram

Thank you Panagiotis 

That is alright :) I thought this may be the case but was doing everything I could to not have to modify the price.

Is it not possible to calculate the stop loss distance from the position entry price? If not, then I will modify the position. Can you send me to where I can find the code.

Thank you for your help as always
Sam


@samuelbreezey

samuelbreezey
11 Aug 2020, 15:34

RE:

PanagiotisCharalampous said:

Hi samuelbreezey,

Shouldn't you use totalPipsB instead of slPriceB here?

ExecuteMarketOrder(TradeType.Buy, SymbolName, exactVolumeB, InstanceName, slPriceB, tpPrice);

Best Regards,

Panagiotis 

Join us on Telegram

 

Hi Panagiotis,

Won't both totalPipsB and slPriceB produce the same results? as they are both the same.

I thought I needed to incorporate the spread within my calculation. It improved the result a little but the stop loss is still a little out from the actual low or high of the previous candle.

Guessing it is to do with the market order not being the exact close price of the previous bar.

Many thanks
Sam


@samuelbreezey

samuelbreezey
21 Jul 2020, 11:03

RE:

PanagiotisCharalampous said:

Hi Sam,

What parameters are you using?

Best Regards,

Panagiotis 

Join us on Telegram

Sorry, it does appear to work. The timeframe was not set to daily in the parameters.

Thank you for your time :)
Samuel


@samuelbreezey

samuelbreezey
20 Jul 2020, 19:27 ( Updated at: 21 Dec 2023, 09:22 )

RE:

PanagiotisCharalampous said:

Hi Sam,

I checked it and seems to work fine for me.

Best Regards,

Panagiotis 

Join us on Telegram

Thank you Panagiotis,

I tried on the EURUSD oair like you did, however it still does not appear to work. See the following:

The order is being places as at the circle candle and I am expecting the stop loss to be where I have drawn the line.


@samuelbreezey

samuelbreezey
18 Jul 2020, 11:03

RE:

PanagiotisCharalampous said:

Hi Sam,

Can you provide the complete cBot code so that we can reproduce this and explain what happens?

Best Regards,

Panagiotis 

Join us on Telegram

 

Hi Panagiotis,

Yes sure, see below:

 

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


/*
 *  INSIDE BAR STRATEGY
 *
 *  07.11.2019 Moving average filter added
 *  09.11.2019 Inside Bar Ratio added
 *  14.11.2019 % risk lot sizing added
 *  22.11.2019 % stop loss and take profit added
 *  prev candle within 25% of its low price for the day
 */


namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NewcBot : Robot
    {
        [Parameter("Instance Name", DefaultValue = "Smash Bar")]
        public string InstanceName { get; set; }
        [Parameter("Another Timeframe", DefaultValue = "Hour")]
        public TimeFrame AnotherTimeFrame { get; set; }
        [Parameter("Risk Percentage", Group = "Money Management", DefaultValue = 1.0, MinValue = 0.1, MaxValue = 10.0)]
        public double RiskPercent { get; set; }
        [Parameter("Buy/Sell Order Level (pips)", DefaultValue = 4)]
        public double bslevel { get; set; }

        /* Moving Average */
        [Parameter("MA Type", Group = "Moving Average")]
        public MovingAverageType MAType { get; set; }
        [Parameter("Source", Group = "Moving Average")]
        public DataSeries Source { get; set; }
        [Parameter("Periods", Group = "Moving Average", DefaultValue = 10)]
        public int Periods { get; set; }
        /* Money Management */


        private MovingAverage ema;
        private double pipsize = 0;
        protected override void OnStart()
        {
            ema = Indicators.MovingAverage(Source, Periods, MAType);

        }

        protected override void OnTick()
        {
            if (Positions.Count == 1)
            {
                foreach (var order in PendingOrders)
                {
                    CancelPendingOrder(order);
                }

            }


        }

        protected override void OnBar()
        {
            var dailySeries = MarketData.GetSeries(AnotherTimeFrame);
            var openTime = dailySeries.OpenTime.Last(1);

            // Calculate bars
            var PrevDayHigh = dailySeries.High.Last(1);
            var PrevDayLow = dailySeries.Low.Last(1);
            var PrevDayOpen = dailySeries.Open.Last(1);
            var PrevDayClose = dailySeries.Close.Last(1);
            // Calculate last price
            var prevClose = dailySeries.Close.Last(1);
            var prevEma = ema.Result.Last(1);

            var SmashBarB = PrevDayClose <= (PrevDayLow + (PrevDayHigh - PrevDayLow) * 0.25);
            var SmashBarS = PrevDayClose >= (PrevDayHigh - (PrevDayHigh - PrevDayLow) * 0.25);

            pipsize = Symbol.PipSize;
            var stoppipsB = ((PrevDayHigh - PrevDayLow) / Symbol.PipSize);
            var stoppipsS = ((PrevDayHigh - PrevDayLow) / Symbol.PipSize);
            var profitpips = 0;

                        /* int Volume = Convert.ToInt32(Lots * 100000); */


            // Our total balance is our account balance plus any reserve funds. We do not always keep all our money in the trading account. 
double totalBalance = Account.Balance;

            // Calculate the total risk allowed per trade.
            double riskPerTrade = (totalBalance * RiskPercent) / 100;

            // Add the stop loss, commission pips and spread to get the total pips used for the volume calculation.
            double totalPips = stoppipsB + Symbol.Spread;

            // Calculate the exact volume to be traded. Then round the volume to the nearest 100,000 and convert to an int so that it can be returned to the caller.
            double exactVolume = Math.Round(riskPerTrade / (Symbol.PipValue * totalPips), 2);

            //Choose your own rounding mode
            exactVolume = (int)Symbol.NormalizeVolumeInUnits(exactVolume, RoundingMode.Down);


            var expiredtime = openTime.AddDays(2);

            if (Positions.Count == 0 && SmashBarB == true && prevClose > prevEma && ema.Result.IsRising())
            {
                PlaceStopOrder(TradeType.Buy, Symbol.Name, exactVolume, PrevDayHigh + bslevel * Symbol.PipSize, InstanceName, stoppipsB, profitpips, expiredtime);
                //  PlaceStopOrder(TradeType.Sell, Symbol.Name, exactVolume, childCandleLow - bslevel * Symbol.PipSize, InstanceName, stoppipsS, profitpips, expiredtime);
            }

            if (Positions.Count == 0 && SmashBarS == true && prevClose < prevEma && ema.Result.IsFalling())
            {
                // PlaceStopOrder(TradeType.Buy, Symbol.Name, exactVolume, childCandleHigh + bslevel * Symbol.PipSize, InstanceName, stoppipsB, profitpips, expiredtime);
                PlaceStopOrder(TradeType.Sell, Symbol.Name, exactVolume, PrevDayLow - bslevel * Symbol.PipSize, InstanceName, stoppipsS, profitpips, expiredtime);
            }

        }
        /*
            foreach (var position in Positions)
            {
                var shortPosition = Positions.Find(InstanceName, SymbolName, TradeType.Sell);
                var longPosition = Positions.Find(InstanceName, SymbolName, TradeType.Buy);
                var shortPositionsCount = Positions.Count(p => p.TradeType == TradeType.Sell);
                var longPositionsCount = Positions.Count(p => p.TradeType == TradeType.Buy);
                if (Positions.Count == 1 && longPositionsCount > 0)
                {
                    Positions[0].ModifyStopLossPrice(ema.Result.Last(1));

                }
                else if (Positions.Count == 1 && shortPositionsCount > 0)
                {
                    Positions[0].ModifyStopLossPrice(ema.Result.Last(1));

                }
            }
*/

        // stop loss at low of prev bar


        // var ma = Indicators.SimpleMovingAverage(Bars.ClosePrices, 14);
        // Positions[0].ModifyStopLossPrice(ma.Result.Last(1));


/*    foreach (var position in Positions)
            {
                var shortPosition = Positions.Find(InstanceName, SymbolName, TradeType.Sell);
                var longPosition = Positions.Find(InstanceName, SymbolName, TradeType.Buy);
                var shortPositionsCount = Positions.Count(p => p.TradeType == TradeType.Sell);
                var longPositionsCount = Positions.Count(p => p.TradeType == TradeType.Buy);
                if (shortPositionsCount > 0)
                {
                          Positions[0].ModifyStopLossPrice(ema.Result.Last(1));
                }
                else if (longPositionsCount > 0)
                       Positions[0].ModifyStopLossPrice(ema.Result.Last(1));
            }

*/


                protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
}

 

Thank you
Sam


@samuelbreezey

samuelbreezey
16 Jul 2020, 22:16 ( Updated at: 21 Dec 2023, 09:22 )

RE:

PanagiotisCharalampous said:

Hi samuelbreezey,

Can you please explain what is not working. What does it do and what would you expect it to do instead?

Best Regards,

Panagiotis 

Join us on Telegram

 

Hi Panagiotis,

See the below, I was expecting the stop loss to be where I have drawn the red line.

Many thanks
Sam


@samuelbreezey

samuelbreezey
13 Jul 2020, 19:53

RE:

Thank you so much :)

 

PanagiotisCharalampous said:

Hi Sam,

Here is an example

            var ma = Indicators.SimpleMovingAverage(Bars.ClosePrices, 14);
            Positions[0].ModifyStopLossPrice(ma.Result.Last(1));

Best Regards,

Panagiotis 

Join us on Telegram

 


@samuelbreezey

samuelbreezey
13 Jul 2020, 09:59

RE:

PanagiotisCharalampous said:

Hi Samuel,

You can use ModifyStopLossPrice to do so.

Best Regards,

Panagiotis 

Join us on Telegram

 

Thank you Panagiotis,

I'm sure that was how, thank you. Is there any sample coding? I am wanting to just set the stop loss to the EMA after each bar.

Many thanks
Sam


@samuelbreezey

samuelbreezey
17 Apr 2020, 22:54

RE:

samuelbreezey said:

Hi all

I am creating a breakout bot which opens a pending order at 7am on the hourly timeframe. I want the submitted price of the buy order to be at the previous candles high and the sell order at previous candles low. 

See code below:

 

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 BreakoutBot : Robot
    {
        [Parameter("Instance Name", DefaultValue = "Breakout")]
        public string InstanceName { get; set; }
        [Parameter("Start Time", DefaultValue = 7, MinValue = 0, MaxValue = 24)]
        public double startTime { get; set; }
        [Parameter("Expiry in hours", DefaultValue = 2, MinValue = 0, MaxValue = 24)]
        public double expHrs { get; set; }


        protected override void OnStart()
        {
            // Put your deinitialization logic here
        }

        protected override void OnTick()
        {


//Last closed bar open price
            var open = MarketSeries.Open.Last(1);

//Last closed bar close price
            var close = MarketSeries.Close.Last(1);

//Last closed bar high price
            var high = MarketSeries.High.Last(1);

//Las closed bar low price
            var low = MarketSeries.Low.Last(1);

            var buyPrice = high;
            var sellPrice = low;

            var expiredtime = Server.Time.AddHours(expHrs);


            if (Positions.Count == 0 && PendingOrders.Count(item => item.OrderType == PendingOrderType.Stop && item.TradeType == TradeType.Buy) == 0)
            {
                if (Server.Time.Hour == startTime)
                {
                    PlaceStopOrder(TradeType.Sell, SymbolName, 1000, sellPrice, InstanceName, 50, 50, expiredtime);
                    PlaceStopOrder(TradeType.Buy, SymbolName, 1000, buyPrice, InstanceName, 50, 50, expiredtime);
                }
            }


            if (Positions.Count == 1)
            {
                foreach (var order in PendingOrders)
                {
                    CancelPendingOrder(order);
                }

            }

        }

    }
}

Any help would be greatly appreciated

Samuel

Sorry it looks like I have figured it out:

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 BreakoutBot : Robot
    {
        [Parameter("Instance Name", DefaultValue = "Breakout")]
        public string InstanceName { get; set; }
        [Parameter("Start Time", DefaultValue = 7, MinValue = 0, MaxValue = 24)]
        public double startTime { get; set; }
        [Parameter("Expiry in hours", DefaultValue = 2, MinValue = 0, MaxValue = 24)]
        public double expHrs { get; set; }
        [Parameter("Look Back Period (bars)", DefaultValue = 1, MinValue = 1, MaxValue = 10)]
        public int lookBack { get; set; }


        protected override void OnStart()
        {
            // Put your deinitialization logic here
        }

        protected override void OnTick()
        {


//Last closed bar open price
            var open = MarketSeries.Open.Last(lookBack);

//Last closed bar close price
            var close = MarketSeries.Close.Last(lookBack);

//Last closed bar high price
            var high = MarketSeries.High.Last(lookBack);

//Las closed bar low price
            var low = MarketSeries.Low.Last(lookBack);

            var buyPrice = high;
            var sellPrice = low;

            var expiredtime = Server.Time.AddHours(expHrs);


            if (Positions.Count == 0 && PendingOrders.Count(item => item.OrderType == PendingOrderType.Stop && item.TradeType == TradeType.Buy) == 0)
            {
                if (Server.Time.Hour == startTime)
                {
                    PlaceStopOrder(TradeType.Sell, SymbolName, 1000, sellPrice, InstanceName, 50, 50, expiredtime);
                    PlaceStopOrder(TradeType.Buy, SymbolName, 1000, buyPrice, InstanceName, 50, 50, expiredtime);
                }
            }


            if (Positions.Count == 1)
            {
                foreach (var order in PendingOrders)
                {
                    CancelPendingOrder(order);
                }

            }

        }
        /*      foreach (var position in Positions)
            {
                if (Positions.Count == 1)
                {
                    ClosePosition(position);

                } */



        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
}

 


@samuelbreezey

samuelbreezey
14 Apr 2020, 23:52

RE:

PanagiotisCharalampous said:

Hi Samuel,

You can use the Server.Time property to check the time and execute the relevant actions. If you need somebody to program a complete cBot for you, you can post a Job or contact a Consultant.

Best Regards,

Panagiotis 

Join us on Telegram

Great stuff, that's all I require as I can code, just need a little help now and again. 

Thanks again

Samuel


@samuelbreezey

samuelbreezey
14 Apr 2020, 08:55

RE:

PanagiotisCharalampous said:

Hi Samuel,

There is no built-in feature in cTrader to do this but you can write a cBot that will place the order at the relevant time.

Best Regards,

Panagiotis 

Join us on Telegram

Thank you Panagiotis,

It's the cBot code that I'm after. Can you give me a sample coding please?

Many thanks

Samuel


@samuelbreezey

samuelbreezey
22 Nov 2019, 15:09

RE:

Panagiotis Charalampous said:

Hi Samuel,

This happens because you are using the actual price as a stop loss. Stop loss should be set in pips instead.

Best Regards,

Panagiotis

Thank you Panagiotis.

 


@samuelbreezey

samuelbreezey
21 Nov 2019, 22:20

RE:

Panagiotis Charalampous said:

Hi Samuel,

Why do you think is wrong. What did you expect to get and what did you get?

Best Regards,

Panagiotis

Hi Panagiotis,

This seems to work, however the actual top loss order does not. The stop loss is meant to be previous days (-2) low for long (buy) orders. 

The previous days low is 1.16840 however the stop loss on the place stop order is 1.17485!

Here's the code:

 

protected override void OnBar()
        {

            // Calculate mother bar
            var motherCandleHigh = MarketSeries.High.Last(2);
            var motherCandleLow = MarketSeries.Low.Last(2);
            var motherCandleOpen = MarketSeries.Open.Last(2);
            var motherCandleClose = MarketSeries.Close.Last(2); 

var slPrice = motherCandleLow;


DateTime expiry = Server.Time.AddHours(ExpTime);
                    PlaceStopOrder(TradeType.Buy, SymbolName, exactVolume, targetPrice, InstanceName, slPrice, tpPrice, expiry);
                }

 


@samuelbreezey

samuelbreezey
19 Aug 2019, 22:27

RE:

FireMyst said:

You need to calculate the difference in pips between the two emas.

Here's a function that will help you:

 private double DifferenceInPips(Symbol s, double firstPrice, double secondPrice, bool returnAbs)
        {
            if (returnAbs)
                return Math.Abs((firstPrice - secondPrice) / s.PipSize);
            else
                return (firstPrice - secondPrice) / s.PipSize;
        }

 

Then change your condition from:

if (_sma1.Result.LastValue > _sma2.Result.LastValue)

to:

if (_sma1.Result.LastValue > _sma2.Result.LastValue && DifferenceInPips(Symbol, _sma1.Result.LastValue, _sma2.Result.LastValue, false) > whatever_amount_you_want)

Thank you,

Here's the code I have now, does this look okay? Do you not have to change the following coding as well?

if (_sma1.Result.LastValue < _sma2.Result.LastValue)

 

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


/*
 *  POPULAR SIMPLE MOVING AVERAGES
 *
 *  The simple moving average (SMA) is the most basic of the moving averages used for trading. 
 *  The simple moving average formula is calculated by taking the average closing price of a stock over the last "x" periods.
 *  
 *  5 - SMA  - For the hyper trader.  This short of an SMA will constantly give you signals.  The best use of a 5-SMA is as a trade trigger in conjunction with a longer SMA period.
 *  10 - SMA - popular with the short-term traders.  Great swing traders and day traders.
 *  20 - SMA - the last stop on the bus for short-term traders.  Beyond 20-SMA you are basically looking at primary trends.
 *  50 - SMA - use the trader to gauge mid-term trends.
 *  200 -SMA - welcome to the world of long-term trend followers.  Most investors will look for a cross above or below this average to represent if the stock is in a bullish or bearish trend.
 */

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class ClickAlgoSchoolSMA : Robot
    {
        #region User defined parameters

        [Parameter("Instance Name", DefaultValue = "001")]
        public string InstanceName { get; set; }

        [Parameter("Lot Size", DefaultValue = 0.1)]
        public double LotSize { get; set; }

        [Parameter("Source SMA #1")]
        public DataSeries SourceSma1 { get; set; }

        [Parameter("Source SMA #2")]
        public DataSeries SourceSma2 { get; set; }

        [Parameter("Period SMA #1", DefaultValue = 5, MinValue = 1, MaxValue = 100)]
        public int PeriodsSma1 { get; set; }

        [Parameter("Period SMA #2", DefaultValue = 20, MinValue = 1, MaxValue = 100)]
        public int PeriodsSma2 { get; set; }

        [Parameter("Calculate OnBar", DefaultValue = false)]
        public bool CalculateOnBar { get; set; }

        #endregion

        #region Indicator declarations

        private SimpleMovingAverage _sma1 { get; set; }
        private SimpleMovingAverage _sma2 { get; set; }

        #endregion

        #region cTrader events

        /// <summary>
        /// This is called when the robot first starts, it is only called once.
        /// </summary>
        protected override void OnStart()
        {
            // construct the indicators
            _sma1 = Indicators.SimpleMovingAverage(SourceSma1, PeriodsSma1);
            _sma2 = Indicators.SimpleMovingAverage(SourceSma2, PeriodsSma2);
        }

        /// <summary>
        /// This method is called every time the price changes for the symbol
        /// </summary>
        protected override void OnTick()
        {
            if (CalculateOnBar)
            {
                return;
            }

            ManagePositions();
        }

        /// <summary>
        /// This method is called at every candle (bar) close, when it has formed
        /// </summary>
        protected override void OnBar()
        {
            if (!CalculateOnBar)
            {
                return;
            }

            ManagePositions();
        }

        /// <summary>
        /// This method is called when your robot stops, can be used to clean-up memory resources.
        /// </summary>
        protected override void OnStop()
        {
            // unused
        }

        #endregion

        #region Position management


        private double DifferenceInPips(Symbol s, double firstPrice, double secondPrice, bool returnAbs)
        {
            if (returnAbs)
                return Math.Abs((firstPrice - secondPrice) / s.PipSize);
            else
                return (firstPrice - secondPrice) / s.PipSize;
        }

        private void ManagePositions()
        {
            if (_sma1.Result.LastValue > _sma2.Result.LastValue && DifferenceInPips(Symbol, _sma1.Result.LastValue, _sma2.Result.LastValue, false) > 20)
            {
                // if there is no buy position open, open one and close any sell position that is open
                if (!IsPositionOpenByType(TradeType.Buy))
                {
                    OpenPosition(TradeType.Buy);
                }

                ClosePosition(TradeType.Sell);
            }

            // if a sell position is already open and signal is buy do nothing
            if (_sma1.Result.LastValue < _sma2.Result.LastValue)
            {
                // if there is no sell position open, open one and close any buy position that is open
                if (!IsPositionOpenByType(TradeType.Sell))
                {
                    OpenPosition(TradeType.Sell);
                }

                ClosePosition(TradeType.Buy);
            }
        }

        /// <summary>
        /// Opens a new long position
        /// </summary>
        /// <param name="type"></param>
        private void OpenPosition(TradeType type)
        {
            // calculate volume from lot size.
            long volume = Symbol.QuantityToVolume(LotSize);

            // open a new position
            ExecuteMarketOrder(type, this.Symbol, volume, InstanceName, null, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        private void ClosePosition(TradeType type)
        {
            var p = Positions.Find(InstanceName, this.Symbol, type);

            if (p != null)
            {
                ClosePosition(p);
            }
        }

        #endregion

        #region Position Information

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool IsPositionOpenByType(TradeType type)
        {
            var p = Positions.FindAll(InstanceName, Symbol, type);

            if (p.Count() >= 1)
            {
                return true;
            }

            return false;
        }

        #endregion
    }
}

Thanks Samuel


@samuelbreezey