wmclennan77
wmclennan77's avatar

Info

Username:wmclennan77
Name:wmclennan77
Member since: 29 Jun 2021

About

None

Signature

None

Last Forum Posts

@Refresh bar just before new bar start:  19 Jan 2023, 16:41


Hi,

I am looking for a solution to a problem I am having with an indicator, it needs to reload the chart basically 2 or 3 seconds before the new bar forms.

Is this in any way possible?

Thanks.

@cTrader API Pivot function:  23 Apr 2022, 12:20


Hi,

I am currently porting an indicator from TradingView to cTrader and I have a question:

Does cTrader have a pivot function in its API? It's possible to use Bars.Maximum, but the TV pivothigh function has left and right period parameters.

Thanks.

@Multi-timeframe trading and one buy/one sell per period:  11 Mar 2022, 11:42


amusleh said:

Hi,

Try this:

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.FullAccess)]
    public class AFFS : Robot
    {
        [Parameter("Name", DefaultValue = "AFFS")]
        public string _name { get; set; }

        [Parameter("Start Hour", DefaultValue = 6.0)]
        public double _starttime { get; set; }

        [Parameter("Stop Hour", DefaultValue = 18.0)]
        public double _stoptime { get; set; }

        [Parameter("Max Lots", DefaultValue = 100.0, MinValue = 0.01, MaxValue = 1000.0)]
        public double _maxlots { get; set; }

        [Parameter("Starting Risk (%)", DefaultValue = 1.0, MinValue = 0.01, MaxValue = 100.0)]
        public double _startingrisk { get; set; }

        [Parameter("Risk Step (%)", DefaultValue = 1.0, MinValue = 0.01, MaxValue = 100.0)]
        public double _riskstep { get; set; }

        [Parameter("Take Profit", DefaultValue = 5.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _takeprofit { get; set; }

        [Parameter("Stop Loss", DefaultValue = 10.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _stoploss { get; set; }

        [Parameter("Safety (Pips)", DefaultValue = 3.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _safety { get; set; }

        [Parameter("High/Low Timeframe", DefaultValue = "Daily")]
        public TimeFrame _hltf { get; set; }

        private Bars _hlbars;
        private double _bullprice, _bearprice, _previoushigh, _previouslow, _maxunits, _activerisk;
        private bool _todaybuy, _todaysell;

        protected override void OnStart()
        {
            _hlbars = MarketData.GetBars(_hltf);

            _safety *= Symbol.PipSize;
        }

        protected override void OnBar()
        {
            var _currenthours = Server.Time.TimeOfDay.TotalHours;
            bool _tradetime = _starttime < _stoptime ? _currenthours > _starttime && _currenthours < _stoptime : _currenthours < _stoptime || _currenthours > _starttime;

            _activerisk = GetRisk();
            var _volume = GetVolume();
            _maxunits = Symbol.QuantityToVolumeInUnits(_maxlots);
            if (_volume > _maxunits)
            {
                _volume = _maxunits;
            }
            _previoushigh = _hlbars.HighPrices.Last(1);
            _previouslow = _hlbars.LowPrices.Last(1);
            _bullprice = Symbol.Ask + _safety;
            _bearprice = Symbol.Bid - _safety;

            if (_tradetime && !_todaybuy)
            {
                if (_bullprice > _previoushigh)
                {
                    ExecuteMarketOrder(TradeType.Buy, Symbol.Name, _volume, _name, _stoploss, _takeprofit);
                    _todaybuy = true;
                }
            }
            if (!_tradetime && _todaybuy)
            {
                _todaybuy = false;
            }

            if (_tradetime && !_todaysell)
            {
                if (_bearprice < _previouslow)
                {
                    ExecuteMarketOrder(TradeType.Sell, Symbol.Name, _volume, _name, _stoploss, _takeprofit);
                    _todaysell = true;
                }
            }
            if (!_tradetime && _todaysell)
            {
                _todaysell = false;
            }
        }

        private double GetRisk()
        {
            double _result = 0.0;
            double _maxrisk = 10.0;
            var _lastposition = History.FindLast(_name);
            bool _win = _lastposition != null && _lastposition.NetProfit > 0.0 ? true : false;
            if (_win && _activerisk < _maxrisk)
            {
                _result = _activerisk + _riskstep;
            }
            else if (!_win)
            {
                _result = _startingrisk;
            }
            return _result;
        }

        private double GetVolume()
        {
            double costPerPip = (double)((int)(Symbol.PipValue * 10000000)) / 100;

            double baseNumber = Account.Balance;

            double sizeInLots = Math.Round((baseNumber * _activerisk / 100) / (_stoploss * costPerPip), 2);

            var result = Symbol.QuantityToVolumeInUnits(sizeInLots);

            if (result > Symbol.VolumeInUnitsMax)
            {
                result = Symbol.VolumeInUnitsMax;
            }
            else if (result < Symbol.VolumeInUnitsMin)
            {
                result = Symbol.VolumeInUnitsMin;
            }
            else if (result % Symbol.VolumeInUnitsStep != 0)
            {
                result = result - (result % Symbol.VolumeInUnitsStep);
            }

            return result;
        }
    }
}

Hi amusleh,

I have one more issue if you can help me.

In the bot above, is there any way to check in the OnStart if:
In the _hlbars period,  the one entry for the day has already happened? If so, the bot cannot trade until the next period.

For example, if HL is set to daily and I start the bot at 2 PM and today's entry happened at 1 PM, I don't want the bot to trade until the next day.

What is happening now is when I initialize the bot, the logic sees that the current price is higher than the previous high, and makes a buy immediately. This is wrong since the ideal entry has passed.

Any help would be greatly appreciated, thanks.

@Multi-timeframe trading and one buy/one sell per period:  10 Mar 2022, 13:25


amusleh said:

Hi,

Try this:

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.FullAccess)]
    public class AFFS : Robot
    {
        [Parameter("Name", DefaultValue = "AFFS")]
        public string _name { get; set; }

        [Parameter("Start Hour", DefaultValue = 6.0)]
        public double _starttime { get; set; }

        [Parameter("Stop Hour", DefaultValue = 18.0)]
        public double _stoptime { get; set; }

        [Parameter("Max Lots", DefaultValue = 100.0, MinValue = 0.01, MaxValue = 1000.0)]
        public double _maxlots { get; set; }

        [Parameter("Starting Risk (%)", DefaultValue = 1.0, MinValue = 0.01, MaxValue = 100.0)]
        public double _startingrisk { get; set; }

        [Parameter("Risk Step (%)", DefaultValue = 1.0, MinValue = 0.01, MaxValue = 100.0)]
        public double _riskstep { get; set; }

        [Parameter("Take Profit", DefaultValue = 5.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _takeprofit { get; set; }

        [Parameter("Stop Loss", DefaultValue = 10.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _stoploss { get; set; }

        [Parameter("Safety (Pips)", DefaultValue = 3.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _safety { get; set; }

        [Parameter("High/Low Timeframe", DefaultValue = "Daily")]
        public TimeFrame _hltf { get; set; }

        private Bars _hlbars;
        private double _bullprice, _bearprice, _previoushigh, _previouslow, _maxunits, _activerisk;
        private bool _todaybuy, _todaysell;

        protected override void OnStart()
        {
            _hlbars = MarketData.GetBars(_hltf);

            _safety *= Symbol.PipSize;
        }

        protected override void OnBar()
        {
            var _currenthours = Server.Time.TimeOfDay.TotalHours;
            bool _tradetime = _starttime < _stoptime ? _currenthours > _starttime && _currenthours < _stoptime : _currenthours < _stoptime || _currenthours > _starttime;

            _activerisk = GetRisk();
            var _volume = GetVolume();
            _maxunits = Symbol.QuantityToVolumeInUnits(_maxlots);
            if (_volume > _maxunits)
            {
                _volume = _maxunits;
            }
            _previoushigh = _hlbars.HighPrices.Last(1);
            _previouslow = _hlbars.LowPrices.Last(1);
            _bullprice = Symbol.Ask + _safety;
            _bearprice = Symbol.Bid - _safety;

            if (_tradetime && !_todaybuy)
            {
                if (_bullprice > _previoushigh)
                {
                    ExecuteMarketOrder(TradeType.Buy, Symbol.Name, _volume, _name, _stoploss, _takeprofit);
                    _todaybuy = true;
                }
            }
            if (!_tradetime && _todaybuy)
            {
                _todaybuy = false;
            }

            if (_tradetime && !_todaysell)
            {
                if (_bearprice < _previouslow)
                {
                    ExecuteMarketOrder(TradeType.Sell, Symbol.Name, _volume, _name, _stoploss, _takeprofit);
                    _todaysell = true;
                }
            }
            if (!_tradetime && _todaysell)
            {
                _todaysell = false;
            }
        }

        private double GetRisk()
        {
            double _result = 0.0;
            double _maxrisk = 10.0;
            var _lastposition = History.FindLast(_name);
            bool _win = _lastposition != null && _lastposition.NetProfit > 0.0 ? true : false;
            if (_win && _activerisk < _maxrisk)
            {
                _result = _activerisk + _riskstep;
            }
            else if (!_win)
            {
                _result = _startingrisk;
            }
            return _result;
        }

        private double GetVolume()
        {
            double costPerPip = (double)((int)(Symbol.PipValue * 10000000)) / 100;

            double baseNumber = Account.Balance;

            double sizeInLots = Math.Round((baseNumber * _activerisk / 100) / (_stoploss * costPerPip), 2);

            var result = Symbol.QuantityToVolumeInUnits(sizeInLots);

            if (result > Symbol.VolumeInUnitsMax)
            {
                result = Symbol.VolumeInUnitsMax;
            }
            else if (result < Symbol.VolumeInUnitsMin)
            {
                result = Symbol.VolumeInUnitsMin;
            }
            else if (result % Symbol.VolumeInUnitsStep != 0)
            {
                result = result - (result % Symbol.VolumeInUnitsStep);
            }

            return result;
        }
    }
}

Hi amusleh,

Thanks, works perfectly!

@Multi-timeframe trading and one buy/one sell per period:  09 Mar 2022, 13:15


Hi, I am building a basic EA to test multi-timeframe trading, and I am having some trouble in that bot does not create any trades.

The bot needs to buy when Bull Price > Previous Period High (Bull Price = Price + Safety in Pips)
And sell when Bear Price < Previous Period Low open sell (Bear Price = Price - Safety in Pips)

Additionally, one of each (buy or sell) is allowed per trading day.

Here I have attached the code I am having problems with:

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.FullAccess)]
    public class AFFS : Robot
    {
        [Parameter("Name", DefaultValue = "AFFS")]
        public string _name { get; set; }

        [Parameter("Start Hour", DefaultValue = 6.0)]
        public double _starttime { get; set; }

        [Parameter("Stop Hour", DefaultValue = 18.0)]
        public double _stoptime { get; set; }

        [Parameter("Max Lots", DefaultValue = 100.0, MinValue = 0.01, MaxValue = 1000.0)]
        public double _maxlots { get; set; }

        [Parameter("Starting Risk (%)", DefaultValue = 1.0, MinValue = 0.01, MaxValue = 100.0)]
        public double _startingrisk { get; set; }

        [Parameter("Risk Step (%)", DefaultValue = 1.0, MinValue = 0.01, MaxValue = 100.0)]
        public double _riskstep { get; set; }

        [Parameter("Take Profit", DefaultValue = 5.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _takeprofit { get; set; }

        [Parameter("Stop Loss", DefaultValue = 10.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _stoploss { get; set; }

        [Parameter("Safety (Pips)", DefaultValue = 3.0, MinValue = 0.1, MaxValue = 100.0)]
        public double _safety { get; set; }

        [Parameter("High/Low Timeframe", DefaultValue = "Daily")]
        public TimeFrame _hltf { get; set; }

        private Bars _hlbars;
        private double _bullprice, _bearprice, _previoushigh, _previouslow, _maxunits, _activerisk;
        private bool _todaybuy, _todaysell;

        protected override void OnStart()
        {
            _hlbars = MarketData.GetBars(_hltf);
        }

        protected override void OnBar()
        {
            var _currenthours = Server.Time.TimeOfDay.TotalHours;
            bool _tradetime = _starttime < _stoptime ? _currenthours > _starttime && _currenthours < _stoptime : _currenthours < _stoptime || _currenthours > _starttime;

            _activerisk = GetRisk();
            var _volume = GetVolume();
            _maxunits = Symbol.QuantityToVolumeInUnits(_maxlots);
            if (_volume > _maxunits)
            {
                _volume = _maxunits;
            }
            _previoushigh = _hlbars.HighPrices.Last(1);
            _previouslow = _hlbars.LowPrices.Last(1);
            _bullprice = Symbol.Ask + (_safety / Symbol.PipValue);
            _bearprice = Symbol.Bid - (_safety / Symbol.PipValue);

            if (_tradetime && !_todaybuy)
            {
                if (_bullprice > _previoushigh)
                {
                    ExecuteMarketOrder(TradeType.Buy, Symbol.Name, _volume, _name, _stoploss, _takeprofit);
                    _todaybuy = true;
                }
            }
            if (!_tradetime && _todaybuy)
            {
                _todaybuy = false;
            }

            if (_tradetime && !_todaysell)
            {
                if (_bearprice < _previouslow)
                {
                    ExecuteMarketOrder(TradeType.Sell, Symbol.Name, _volume, _name, _stoploss, _takeprofit);
                    _todaysell = true;
                }
            }
            if (!_tradetime && _todaysell)
            {
                _todaysell = false;
            }
        }

        private double GetRisk()
        {
            double _result = 0.0;
            double _maxrisk = 10.0;
            var _lastposition = History.FindLast(_name);
            bool _win = _lastposition.NetProfit > 0.0 ? true : false;
            if (_win && _activerisk < _maxrisk)
            {
                _result = _activerisk + _riskstep;
            }
            else if (!_win)
            {
                _result = _startingrisk;
            }
            return _result;
        }

        private double GetVolume()
        {
            double costPerPip = (double)((int)(Symbol.PipValue * 10000000)) / 100;

            double baseNumber = Account.Balance;

            double sizeInLots = Math.Round((baseNumber * _activerisk / 100) / (_stoploss * costPerPip), 2);

            var result = Symbol.QuantityToVolumeInUnits(sizeInLots);

            if (result > Symbol.VolumeInUnitsMax)
            {
                result = Symbol.VolumeInUnitsMax;
            }
            else if (result < Symbol.VolumeInUnitsMin)
            {
                result = Symbol.VolumeInUnitsMin;
            }
            else if (result % Symbol.VolumeInUnitsStep != 0)
            {
                result = result - (result % Symbol.VolumeInUnitsStep);
            }

            return result;
        }
    }
}

@cAlgo.Lib Error:  12 Aug 2021, 13:05


Hi all,

I have a custom indicator that I got from the forums that I would like to test out.

On compiling, I receive the following error:

Error CS0234: The type or namespace name 'Lib' does not exist in the namespace 'cAlgo' (are you missing an assembly reference?)

Source for clarification:

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


namespace cAlgo.Indicators
{
    [Indicator(TimeZone = TimeZones.UTC, IsOverlay = false, AccessRights = AccessRights.None)]
    [Levels(-5, -3, -2, -1, -0.75, -0.5, -0.25, 0, 0.25, 0.5,
    0.75, 1, 2, 3, 5)]
    public class VelocityIndicator : Indicator
    {
        #region cIndicators Parameters

        [Parameter("Number Of Candle", DefaultValue = 5, MinValue = 1)]
        public int NumberOfCandle { get; set; }

        [Parameter("Moving Average", DefaultValue = MovingAverageType.Exponential)]
        public MovingAverageType MovingAverageType { get; set; }

        [Parameter("MA Period", DefaultValue = 14, MinValue = 2)]
        public int Period { get; set; }

        [Output("High Acceleration", Color = Colors.Green, Thickness = 1)]
        public IndicatorDataSeries HighAccelerationSeries { get; set; }

        [Output("Low Acceleration", Color = Colors.Red, Thickness = 1)]
        public IndicatorDataSeries LowAccelerationSeries { get; set; }

        [Output("Moving Average", Color = Colors.Blue, Thickness = 2)]
        public IndicatorDataSeries MovingAverageSeries { get; set; }

        #endregion

        MovingAverage _movingAverage;
        double _elapsedTime;

        protected override void Initialize()
        {
            _movingAverage = Indicators.MovingAverage(HighAccelerationSeries, Period, MovingAverageType);

            long elapsedTicks = (long)Math.Ceiling((NumberOfCandle + 0.5) * MarketSeries.TimeFrame.ToTimeSpan().Ticks);
            TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);
            _elapsedTime = elapsedSpan.TotalSeconds;
        }

        /// <summary>
        /// S = S0 + V0t +(at^2)/2   a = (2*(S-S0))/t^2.
        /// v = v0 +at
        /// </summary>
        /// <param name="index"></param>
        public override void Calculate(int index)
        {
            double high = MarketSeries.High[index];
            double previewHigh = MarketSeries.High[index - NumberOfCandle];
            double actualPriceOrHigh = (MarketSeries.Bars() - 1) == index ? Symbol.Mid() : high;

            double low = MarketSeries.Low[index];
            double previewLow = MarketSeries.Low[index - NumberOfCandle];
            double actualPriceOrLow = (MarketSeries.Bars() - 1) == index ? Symbol.Mid() : low;

            double highAcceleration = (2 * (high - previewHigh) / Math.Pow(_elapsedTime, 2)) * Math.Pow(10, 2 * Symbol.Digits);
            double lowAcceleration = (2 * (low - previewLow) / Math.Pow(_elapsedTime, 2)) * Math.Pow(10, 2 * Symbol.Digits);

            HighAccelerationSeries[index] = highAcceleration;
            LowAccelerationSeries[index] = lowAcceleration;
            MovingAverageSeries[index] = _movingAverage.Result[index];


            // Print("{0} {1} {2} {3} {4}",highAcceleration, lowAcceleration, elapsedTime, MarketSeries.Bars()-1, index);

        }
    }
}

Any  help would be appreciated, thanks.

@Risk based on SL algorithm:  29 Jul 2021, 13:27


amusleh said:

Hi,

Try this:

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.FullAccess)]
    public class RiskonSL : Robot
    {
        [Parameter("Label", DefaultValue = "")]
        public string _Label { get; set; }

        [Parameter("Risk %", DefaultValue = 1.0, MaxValue = 100.0, MinValue = 0.01, Step = 0.1)]
        public double _RiskPercent { get; set; }

        [Parameter("Max Allowed Lots", DefaultValue = 10.0, MaxValue = 100.0, MinValue = 0.01, Step = 0.01)]
        public double _MaxLots { get; set; }

        [Parameter("Stop Loss", DefaultValue = 10.0, MaxValue = 50.0, MinValue = 0.1, Step = 0.1)]
        public double _SL { get; set; }

        [Parameter("Take Profit", DefaultValue = 15.0, MaxValue = 50.0, MinValue = 0.1, Step = 0.1)]
        public double _TP { get; set; }

        private ExponentialMovingAverage _ema_12;
        private ExponentialMovingAverage _ema_26;
        private bool _ema_buy, _ema_sell;

        protected override void OnStart()
        {
            _ema_12 = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 12);
            _ema_26 = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 26);
        }

        protected override void OnBar()
        {
            var ActiveBuy = Positions.Find(_Label, SymbolName, TradeType.Buy);
            var ActiveSell = Positions.Find(_Label, SymbolName, TradeType.Sell);

            var volume = GetVolume();

            if (_ema_12.Result.HasCrossedAbove(_ema_26.Result.Last(1), 1))
            {
                _ema_buy = true;
                _ema_sell = false;
            }
            else if (_ema_12.Result.HasCrossedBelow(_ema_26.Result.Last(1), 1))
            {
                _ema_sell = true;
                _ema_buy = false;
            }

            if (ActiveBuy == null && _ema_buy)
            {
                if (ActiveSell != null)
                {
                    ClosePosition(ActiveSell);
                }
                ExecuteMarketOrder(TradeType.Buy, SymbolName, volume, _Label, _SL, _TP);
            }

            if (ActiveSell == null && _ema_sell)
            {
                if (ActiveBuy != null)
                {
                    ClosePosition(ActiveBuy);
                }
                ExecuteMarketOrder(TradeType.Sell, SymbolName, volume, _Label, _SL, _SL);
            }
        }

        private double GetVolume()
        {
            double costPerPip = (double)((int)(Symbol.PipValue * 10000000)) / 100;

            double baseNumber = Account.Equity;

            double sizeInLots = Math.Round((baseNumber * _RiskPercent / 100) / (_SL * costPerPip), 2);

            var result = Symbol.QuantityToVolumeInUnits(sizeInLots);

            if (result > Symbol.VolumeInUnitsMax)
            {
                result = Symbol.VolumeInUnitsMax;
            }
            else if (result < Symbol.VolumeInUnitsMin)
            {
                result = Symbol.VolumeInUnitsMin;
            }
            else if (result % Symbol.VolumeInUnitsStep != 0)
            {
                result = result - (result % Symbol.VolumeInUnitsStep);
            }

            return result;
        }
    }
}

Hi, 

Works perfect, thanks!

@Risk based on SL algorithm:  29 Jul 2021, 10:44


amusleh said:

Hi,

Please post a full cBot sample that uses your calculation code and then we will be able to help you.

Hi,

Here is an example of the calculation code implemented in an example basic MA cross strategy.

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.FullAccess)]
    public class RiskonSL : Robot
    {
        private double _volume;
        private double _AdjRisk;
        private double _AdjStop;
        private double _MaxUnits;

        [Parameter("Label", DefaultValue = "")]
        public string _Label { get; set; }

        [Parameter("Risk %", DefaultValue = 1.0, MaxValue = 100.0, MinValue = 0.01, Step = 0.1)]
        public double _RiskPercent { get; set; }

        [Parameter("Max Allowed Lots", DefaultValue = 10.0, MaxValue = 100.0, MinValue = 0.01, Step = 0.01)]
        public double _MaxLots { get; set; }

        [Parameter("Stop Loss", DefaultValue = 10.0, MaxValue = 50.0, MinValue = 0.1, Step = 0.1)]
        public double _SL { get; set; }

        [Parameter("Take Profit", DefaultValue = 15.0, MaxValue = 50.0, MinValue = 0.1, Step = 0.1)]
        public double _TP { get; set; }

        private ExponentialMovingAverage _ema_12;
        private ExponentialMovingAverage _ema_26;
        private bool _ema_buy, _ema_sell;

        protected override void OnStart()
        {
            _ema_12 = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 12);
            _ema_26 = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 26);
        }

        protected override void OnBar()
        {
            var ActiveBuy = Positions.Find(_Label, SymbolName, TradeType.Buy);
            var ActiveSell = Positions.Find(_Label, SymbolName, TradeType.Sell);

            _MaxUnits = Symbol.QuantityToVolumeInUnits(_MaxLots);
            _AdjRisk = _RiskPercent / 100;
            _AdjStop = _SL / Symbol.PipValue;
            _volume = (long)Math.Ceiling((Account.Balance * _AdjRisk) / _AdjStop) * 1000;
            if (_volume > _MaxUnits)
            {
                _volume = _MaxUnits;
            }

            if (_ema_12.Result.HasCrossedAbove(_ema_26.Result.Last(1), 1))
            {
                _ema_buy = true;
                _ema_sell = false;
            }
            else if (_ema_12.Result.HasCrossedBelow(_ema_26.Result.Last(1), 1))
            {
                _ema_sell = true;
                _ema_buy = false;
            }

            if (ActiveBuy == null && _ema_buy)
            {
                if (ActiveSell != null)
                {
                    ClosePosition(ActiveSell);
                }
                ExecuteMarketOrder(TradeType.Buy, SymbolName, _volume, _Label, _SL, _TP);
            }

            if (ActiveSell == null && _ema_sell)
            {
                if (ActiveBuy != null)
                {
                    ClosePosition(ActiveBuy);
                }
                ExecuteMarketOrder(TradeType.Sell, SymbolName, _volume, _Label, _SL, _SL);
            }
        }
    }
}

@Risk based on SL algorithm:  29 Jul 2021, 09:13


Hi all,

I have created a risk management algorithm that sets the volume in accordance with account balance and stop-loss distance.

The algo gets the SL amount as well as the specified risk percentage from the user via parameters.

Examples of the desired result:

Pair - EURUSD
Account Balance - $10 000
Risk % - 1
SL - 10
Amount At Risk - $100
Volume - 100000 (1 lot)

Pair - USDCAD
Account Balance - $14 566
Risk % - 2.5
SL - 27
Amount At Risk - $364.15
Volume - 169788 (1.69 lots)

The code I have for this calculation so far:
 

_AdjRisk = _RiskPercent / 100;
_AdjStop = _SL / Symbol.PipValue;
_volume = (long)Math.Ceiling((Account.Balance * _AdjRisk) / _AdjStop) * 1000;



Although when backtesting, the lot size stays at 0.01 for the entire backtest.

Any advice as to what is wrong with the logic?
 

@Add reloaded functionality to working bot:  20 Jul 2021, 09:30


Hi all,

I have written a bot that works well enough and have a question about making the bot more complete.

What kind of code should I write in case of cTrader disconnection? The bot might eventually go on a VPS where disconnection has a low probability, but as of right now I'm running the cBot from my home internet which drops on occasion. I'm aware of Bars.Reloaded, but have no idea where to start implementation.

I would just like to know how to not make the bot crash in the event of internet disconnection.

Kind regards,

Notification Publishing copyrighted material is strictly prohibited. If you believe there is copyrighted material in this section you may use the Copyright Infringement Notification form to submit a claim.

No uploaded.

Warning! Executing cBots downloaded from this section may result in loss of funds. Use them at your own risk.

No uploaded.