Topics
20 Jul 2018, 22:20
 1291
 1
02 Jul 2018, 12:25
 2803
 4
22 Mar 2018, 17:18
 1506
 5
06 Jan 2018, 13:53
 2209
 4
05 Jul 2016, 18:57
 2980
 3
09 Mar 2016, 17:25
 3192
 3
01 Aug 2015, 15:06
 3182
 3
Replies

tradermatrix
19 Jan 2021, 21:30

RE: RE:

yet it works for me. can be replaced;

var cBotPositions = Positions.FindAll(label);
  if (cBotPositions.Length >= 1)
            return;

by:

 var position = Positions.Find(label);
 if (position == null)

 


@tradermatrix

tradermatrix
19 Jan 2021, 14:46

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

        [Parameter(DefaultValue = 1000)]
        public double Volume { get; set; }

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

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

        [Parameter("MA Type", Group = "Moving Average")]
        public MovingAverageType MAType { get; set; }

        [Parameter("Source", Group = "Moving Average")]
        public DataSeries SourceSeries { get; set; }

        [Parameter("Slow Periods", Group = "Moving Average", DefaultValue = 10)]
        public int SlowPeriods { get; set; }

        [Parameter("Fast Periods", Group = "Moving Average", DefaultValue = 5)]
        public int FastPeriods { get; set; }

        [Parameter("Source", Group = "RSI")]
        public DataSeries Source { get; set; }

        [Parameter("Periods", Group = "RSI", DefaultValue = 14)]
        public int Periods { get; set; }

        [Parameter("MACD LongCycle", DefaultValue = 26, MinValue = 1)]
        public int LongCycle { get; set; }

        [Parameter("MACD ShortCycle", DefaultValue = 12, MinValue = 1)]
        public int ShortCycle { get; set; }

        [Parameter("MACD Period", DefaultValue = 9, MinValue = 1)]
        public int MACDPeriod { get; set; }


        private MovingAverage slowMa;
        private MovingAverage fastMa;
        private MacdCrossOver _MACD;
        private RelativeStrengthIndex rsi;
        private const string label = "Follow trend cBot";

        protected override void OnStart()
        {

            fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
            slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
            rsi = Indicators.RelativeStrengthIndex(Source, Periods);
            _MACD = Indicators.MacdCrossOver(LongCycle, ShortCycle, MACDPeriod);
        }

        protected override void OnTick()
        {

            var currentSlowMa = slowMa.Result.Last(0);
            var currentFastMa = fastMa.Result.Last(0);

            var cBotPositions = Positions.FindAll(label);

            if (cBotPositions.Length >= 1)
                return;


            if (rsi.Result.LastValue > 50 && currentFastMa > currentSlowMa && _MACD.MACD.Last(1) > _MACD.Signal.Last(1))
            {
                ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, label, StopLoss, TakeProfit);
            }
            else if (rsi.Result.LastValue < 50 && currentFastMa < currentSlowMa && _MACD.MACD.Last(1) < _MACD.Signal.Last(1))
            {

                ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, label, StopLoss, TakeProfit);

            }
        }


    }
}

          

 


@tradermatrix

tradermatrix
10 Nov 2020, 18:48

RE:

PanagiotisCharalampous said:

Hi tradermatrix,

Here you go

 SL = Math.Round(ATR.Result.LastValue * ATRfactor / Symbol.PipSize, 1);

Best Regards,

Panagiotis 

Join us on Telegram

Thank you for you precious help
It works...
cordially


@tradermatrix

tradermatrix
10 Nov 2020, 14:38

RE:

PanagiotisCharalampous said:

Hi tradermatrix,

You should round the stop loss value to one decimal place before using it.

Best Regards,

Panagiotis 

Join us on Telegram

Thank you for your prompt response.
do you have sample code to help me.
I have already tried several methods to round off but without success.
cordially


@tradermatrix

tradermatrix
20 Jul 2020, 17:43

RE:

Thank you for your precious help, I will experiment your method and look for a solution to adapt it to my needs.
Best Regards,

 


@tradermatrix

tradermatrix
20 Jul 2020, 16:08

RE:

PanagiotisCharalampous said:

Hi tradermatrix,

I do not see why you cannot implement different checks with a single timer event, one for every strategy. It needs some coding but its achievable. 

Best Regards,

Panagiotis 

Join us on Telegram

Thank you for your reply.
so I am making a mistake.
Do you have a sample code to share?


@tradermatrix

tradermatrix
20 Jul 2020, 15:11

RE:

PanagiotisCharalampous said:

Hi tradermatrix,

At the moment you can only have one instance of the Timer. You will need to implement your logic with this limitation in mind.

Best Regards,

Panagiotis 

Join us on Telegram

Hi Panagiotis
Thank you for your reply.
It is a shame because for example I have a robot with 14 different strategies and I am therefore obliged to keep the same deadlines for all instances.
I even think that if the timer is open on a robot, it also intervenes on another robot in operation.
The "OnTimer ()" timer should be associated with the label, this would create several instances of different timers ...

otherwise the method "System.Threading.Thread.Sleep (60000 * _Interval1);" is very easy to use and works on as many desired instances but is still not compatible with backtesting or optimization.
cordially

 


@tradermatrix

tradermatrix
07 Feb 2020, 15:59

yes for me too, no change ..
trust the team that will solve the problem


@tradermatrix

tradermatrix
21 Jul 2019, 15:43

I have this code updated with the new references....
like that i think it's ok
good luck


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

namespace cAlgo.Robots
{
    [Robot()]
    public class TreeBarsTraDerMaTriX : Robot
    {
        [Parameter("3 BARS TraDerMaTriX n°", DefaultValue = "3")]
        public string InstanceName { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public double volume { get; set; }

        [Parameter("SL", DefaultValue = 270)]
        public int SL { get; set; }

        [Parameter("TP", DefaultValue = 280)]
        public int TP { get; set; }

        [Parameter("Use Trail", DefaultValue = true)]
        public bool UseTrail { get; set; }

        [Parameter("Trigger (pips)", DefaultValue = 15)]
        public int TrailingStopTrigger { get; set; }

        [Parameter("Trailing (pips)", DefaultValue = 6)]
        public int TrailingStopStep { get; set; }


        protected override void OnStart()
        {

        }

        protected override void OnTick()
        {
            TRAIL();
        }
        protected override void OnBar()
        {

            play();
        }

        private void play()
        {
            int bars = MarketSeries.Close.Count - 1;
            int[] b_or_m = new int[3];
            Print("{0},{1},{2},{3},{4}", MarketSeries.High[bars - 1], MarketSeries.High[bars - 2], MarketSeries.High[bars - 3], MarketSeries.Close.Count, MarketSeries.High[1]);
            if (MarketSeries.Close[bars - 1] > MarketSeries.Open[bars - 1])
                b_or_m[0] = 1;
            else

                b_or_m[0] = 2;

            if (MarketSeries.Close[bars - 2] > MarketSeries.Open[bars - 2])
                b_or_m[1] = 1;
            else

                b_or_m[1] = 2;

            if (MarketSeries.Close[bars - 3] > MarketSeries.Open[bars - 3])
                b_or_m[2] = 1;
            else

                b_or_m[2] = 2;

            Print("{0},{1},{2}", b_or_m[0], b_or_m[1], b_or_m[2]);

            var cBotPositions = Positions.FindAll(InstanceName);
            if (cBotPositions.Length >= 1)

                return;

            if ((b_or_m[0] == 1) && (b_or_m[1] == 1) && (b_or_m[2] == 1))
            {

                ExecuteMarketOrder(TradeType.Buy, SymbolName, volume, InstanceName, SL, TP);
            }
            else if ((b_or_m[0] == 2) && (b_or_m[1] == 2) && (b_or_m[2] == 2))
            {

                ExecuteMarketOrder(TradeType.Sell, SymbolName, volume, InstanceName, SL, TP);

            }

        }


        protected override void OnError(Error error)
        {
            Print("Errot={0}", error.Code);
        }
        protected override void OnStop()
        {
            Print("Robot 3BARS by TraDerMaTriX  stopped by user");

        }

        private void TRAIL()
        {
            if (UseTrail)
            {

                var sellPositions = Positions.FindAll(InstanceName, SymbolName, TradeType.Sell);

                foreach (Position position in sellPositions)
                {
                    double distance = position.EntryPrice - Symbol.Ask;

                    if (distance < TrailingStopTrigger * Symbol.PipSize)
                        continue;

                    double newStopLossPrice = Symbol.Ask + TrailingStopStep * Symbol.PipSize;

                    if (position.StopLoss == null || newStopLossPrice < position.StopLoss)
                    {
                        ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                    }
                }

                var buyPositions = Positions.FindAll(InstanceName, SymbolName, TradeType.Buy);

                foreach (Position position in buyPositions)
                {
                    double distance = Symbol.Bid - position.EntryPrice;

                    if (distance < TrailingStopTrigger * Symbol.PipSize)
                        continue;

                    double newStopLossPrice = Symbol.Bid - TrailingStopStep * Symbol.PipSize;
                    if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                    {
                        ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                    }
                }
            }

        }
    }
}



 


@tradermatrix

tradermatrix
02 Apr 2019, 12:20

yes it's a bug ..
I hulled all your bot piece by piece but finally I did not find any error ..
so i figured that the optimization flaw came up when the cBot gets data in the form of deadlines other than the one on which it runs.
I modified your code a little and I realized to the optimization that when my setting "Time Frame" is identical to the one on which it is executed there is no more problem ...
that's why it worked previously because I optimized on 5m ....
thanks to you I just noticed that some of my robots do not have the right settings ... because I trusted optimization.
hope that this problem will be settled soon
cordially

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.RussianStandardTime, AccessRights = AccessRights.FullAccess)]
    public class VolatilityBreakout4 : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("Time Frame", DefaultValue = "Minute5")]
        public TimeFrame timeframe { get; set; }

        [Parameter("Risk", MaxValue = 10, MinValue = 0.5, DefaultValue = 1)]
        public double Risk { get; set; }

        [Parameter("Squeeze bars number", MaxValue = 180, MinValue = 5, Step = 1, DefaultValue = 20)]
        public int SqueezeBarsNumber { get; set; }

        [Parameter("Squeeze in pips", MaxValue = 300, MinValue = 1, Step = 1, DefaultValue = 20)]
        public int Squeeze { get; set; }

        [Parameter("TP multiple", MaxValue = 8, MinValue = 1, Step = 0.1, DefaultValue = 2)]
        public double TpMultiple { get; set; }

        [Parameter("Close on Profit %", Step = 0.1, DefaultValue = 4.0)]
        public double CloseOnProfit { get; set; }

        [Parameter("Close Trade Hour", DefaultValue = 23)]
        public int CloseTradesHour { get; set; }

        [Parameter("Close Trade Minute", DefaultValue = 30)]
        public int CloseTradesMinute { get; set; }

        [Parameter("Open Trade Hour", DefaultValue = 2)]
        public int OpenTradesHour { get; set; }

        private string instance;
        private MarketSeries series;
        private double range, high, low, volume, barsRange, SL, TP, minVolume, risk, longPrice;
        private double shortPrice, closeOnProfit;
        private int pipDigits, n;
        private DateTime squeezeFirstBarTime, squeezeLastBarTime;

        protected override void OnStart()
        {
            instance = ToString() + ", " + Symbol.Code + ", " + TimeFrame + ", " + Account.BrokerName + ", " + Account.Number;
            range = Squeeze * Symbol.PipSize;

            series = MarketData.GetSeries(timeframe);
            minVolume = Symbol.VolumeInUnitsMin;
            risk = Risk * 0.01;
            closeOnProfit = CloseOnProfit * 0.01;
            pipDigits = Symbol.Digits - (int)Math.Log10(1 / Symbol.PipSize);
            Positions.Opened += Positions_Opened;
            Positions.Closed += PositionsOnClosed;
            squeezeFirstBarTime = CandleOpenTime(2 + SqueezeBarsNumber);
            squeezeLastBarTime = CandleOpenTime(2);
        }

        protected override void OnBar()
        {
            var position = Positions.Find(instance);
            var spread = Symbol.Spread / Symbol.PipSize;
            if (position == null)
            {
                if (spread > 2)
                {
                    return;
                }
                if ((CandleOpenTime(0).Hour >= CloseTradesHour && CandleOpenTime(0).Minute >= CloseTradesMinute) || CandleOpenTime(0).Hour < OpenTradesHour)
                {
                    return;
                }
                squeezeFirstBarTime = CandleOpenTime(1 + SqueezeBarsNumber);
                squeezeLastBarTime = CandleOpenTime(1);
                high = CandleHigh(1);
                low = CandleLow(1);
                barsRange = CandleClose(1) > (1) ? MarketSeries.Close.Last(1) - MarketSeries.Open.Last(1) : MarketSeries.Open.Last(1) - MarketSeries.Close.Last(1);
                for (int i = 0; i < SqueezeBarsNumber; i++)
                {
                    high = CandleHigh(i + 1) > high ? CandleHigh(i + 1) : high;
                    low = CandleLow(i + 1) < low ? CandleLow(i + 1) : low;
                    barsRange = high - low;
                }
                //Chart.RemoveAllObjects();
                //Chart.DrawTrendLine("sHigh", squeezeFirstBarTime, high, squeezeLastBarTime, high, Color.Aqua, 1, LineStyle.Solid);
                //Chart.DrawTrendLine("sLow", squeezeFirstBarTime, low, squeezeLastBarTime, low, Color.Red, 1, LineStyle.Solid);
                //double barRangePips = Math.Round(barsRange / Symbol.PipSize, 1);
                //string text = "Squeeze = " + Squeeze + " , barRange = " + barRangePips;
                //Chart.DrawStaticText("Current range", text, VerticalAlignment.Bottom, HorizontalAlignment.Right, Color.Aquamarine);


                n = 0;
                foreach (var order in PendingOrders)
                {
                    if (order.Label == instance)
                    {
                        n = n + 1;
                    }
                }
                if (n == 0)
                {
                    if (high - low < range)
                    {
                        {
                            longPrice = high;
                            shortPrice = low;
                            SL = (high - low) / Symbol.PipSize + 1;
                            volume = Math.Floor(((Account.Equity * risk) / SL) / Symbol.PipValue / minVolume) * minVolume;
                            SL = Math.Round(SL, pipDigits, MidpointRounding.AwayFromZero);
                            TP = SL * TpMultiple;
                            PlaceStopOrder(TradeType.Buy, Symbol, volume, longPrice, instance, null, TP);
                            PlaceStopOrder(TradeType.Sell, Symbol, volume, shortPrice, instance, null, TP);
                            //Chart.DrawHorizontalLine(longPrice.ToString(), longPrice - SL * Symbol.PipSize, Color.Crimson, 1, LineStyle.DotsRare);
                            //Chart.DrawHorizontalLine(shortPrice.ToString(), shortPrice + SL * Symbol.PipSize, Color.Crimson, 1, LineStyle.DotsRare);
                        }
                    }
                }
            }
            if (position != null)
            {
                if (spread > 2)
                {
                    return;
                }
                if (position.TradeType == TradeType.Buy)
                {
                    if (CandleClose(1) < position.EntryPrice - SL * Symbol.PipSize)
                    {
                        ClosePosition(position);
                        //Chart.RemoveAllObjects();
                    }
                }
                if (position.TradeType == TradeType.Sell)
                {
                    if (CandleClose(1) > position.EntryPrice + SL * Symbol.PipSize)
                    {

                        ClosePosition(position);
                        //Chart.RemoveAllObjects();
                    }
                }
            }
        }
        protected override void OnTick()
        {
            if (Account.UnrealizedNetProfit > Account.Balance * closeOnProfit)
                foreach (var position in Positions)
                {
                    ClosePositionAsync(position);
                }
        }
        private void Positions_Opened(PositionOpenedEventArgs args)
        {
            var position = args.Position;
            if (position.Label == instance)
            {
                foreach (var order in PendingOrders)
                {
                    if (order.Label == instance)
                        CancelPendingOrder(order);
                }
                if (position.TradeType == TradeType.Buy)
                {
                    //Chart.RemoveObject(shortPrice.ToString());
                }
                if (position.TradeType == TradeType.Sell)
                {
                    //Chart.RemoveObject(longPrice.ToString());
                }
            }

        }
        private void PositionsOnClosed(PositionClosedEventArgs args)
        {
            var position = args.Position;

            if (args.Reason == PositionCloseReason.TakeProfit)
            {
                //
            }
        }
        #region Candles Processing
        #region Candle Type
        private bool CandleTypeBullish(int k)
        {
            if (series.Open.Last(k) > series.Close.Last(k))
            {
                return false;
            }
            return true;
        }
        #endregion

        #region Candle Range(int k)
        private double CandleRange(int k)
        {
            return series.High.Last(k) - series.Low.Last(k);
        }
        #endregion

        #region Candle body bottom
        private double CandleBodyBottom(int k)
        {
            return (series.Open.Last(k) < series.Close.Last(k)) ? series.Open.Last(k) : series.Close.Last(k);
        }
        #endregion

        #region Candle body Top
        private double CandleBodyTop(int k)
        {
            return (series.Open.Last(k) > series.Close.Last(k)) ? series.Open.Last(k) : series.Close.Last(k);
        }
        #endregion

        #region Candle high
        private double CandleHigh(int k)
        {
            return series.High.Last(k);
        }
        #endregion

        #region Candle low
        private double CandleLow(int k)
        {
            return series.Low.Last(k);
        }
        #endregion

        #region Candle body
        private double CandleBody(int k)
        {
            return Math.Abs((series.Open.Last(k) - series.Close.Last(k)));
        }
        #endregion

        #region Candle Close
        private double CandleClose(int k)
        {
            if (CandleTypeBullish(k))
            {
                return CandleBodyTop(k);
            }
            return CandleBodyBottom(k);
        }
        #endregion

        #region Candle Open
        private double CandleOpen(int k)
        {
            if (CandleTypeBullish(k))
            {
                return CandleBodyBottom(k);
            }
            return CandleBodyTop(k);
        }

        #endregion

        #region Candle Sinus
        private double CandleSinus(int k)
        {
            return Math.Abs((series.Open.Last(k) - series.Close.Last(k))) / CandleRange(k) * (series.Close.Last(k) > series.Open.Last(k) ? 1 : -1);
        }
        #endregion

        #region Trend Angle
        private double TrendAngle(int CandlesInTrend)
        {
            double absBody = 0;
            double bodiesRange = 0;
            for (int i = 0; i <= CandlesInTrend; i++)
            {
                if (CandleTypeBullish(i))
                {
                    bodiesRange = bodiesRange + CandleBody(i);
                }
                if (!CandleTypeBullish(i))
                {
                    bodiesRange = bodiesRange - CandleBody(i);
                }
                absBody = absBody + CandleBody(i);
            }
            var trendSinus = bodiesRange / absBody;
            return Math.Asin(trendSinus) * 180 / Math.PI;
        }
        #endregion

        #region Candle OpenTime
        private DateTime CandleOpenTime(int k)
        {
            return series.OpenTime.Last(k);
        }
        #endregion

        #region No k Candles on the left High
        private bool NoLeftCandlesHigh(int k)
        {
            for (int i = 1; i < k; i++)
            {
                if (CandleHigh(1) > CandleLow(1 + i) && CandleHigh(1) < CandleHigh(1 + i))
                {
                    return false;
                }
                if (CandleHigh(1) < CandleLow(1 + i) || CandleHigh(1) > CandleHigh(1 + i))
                {
                    continue;
                }
            }
            return true;
        }
        #endregion
        #region No k Candles on the left Low
        private bool NoLeftCandlesLow(int k)
        {
            for (int i = 1; i < k; i++)
            {
                if (CandleLow(1) < CandleHigh(1 + i) && CandleLow(1) > CandleLow(1 + i))
                {
                    return false;
                }
                if (CandleLow(1) < CandleHigh(1 + i) || CandleLow(1) > CandleLow(1 + i))
                {
                    continue;
                }
            }
            return true;
        }
        #endregion
        #endregion
    }
}

 


@tradermatrix

tradermatrix
31 Mar 2019, 11:57

Hello

I downloaded the last code you tested ... and at home it works in bar mode and tick mode .. no difference between backesting and optimization

I think the cause is an update ..

I downloaded last upgrade to a newer version of .Net framework.

can be a try ...

https://dotnet.microsoft.com/download/dotnet-framework/net472


@tradermatrix

tradermatrix
30 Mar 2019, 15:52

Hi
I think the problem is here;
SL = Math.Round(SL, pipDigits, MidpointRounding.AwayFromZero);
I just replaced ("MidpointRounding.AwayFromZero") with 0 and it works
 SL = Math.Round(SL, pipDigits, 0);
  TP = SL * TpMultiple;
                        PlaceStopOrder(TradeType.Buy, Symbol, volume, longPrice, instance, SL, TP);
                        PlaceStopOrder(TradeType.Sell, Symbol, volume, shortPrice, instance, SL, TP);

cordially


@tradermatrix

tradermatrix
06 Mar 2019, 12:30

thank you Mr. Panagiotis
thanks to you everything works fine.

 


@tradermatrix

tradermatrix
18 Nov 2018, 18:15

salut
il devrait mieux fonctionner ainsi...
attention il faut tenir compte de utc heure d hivers / heures d ete ...
par exemple en france si tu regles stoptime a 18 H le robot coupera ta commande a 19 H ...regarde le backtesting
@+

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

        private DateTime _startTime;
        private DateTime _stopTime;

        [Parameter("Start Hour", DefaultValue = 10.0)]
        public double StartTime { get; set; }
        [Parameter("Stop Hour", DefaultValue = 18.0)]
        public double StopTime { get; set; }

        [Parameter()]
        public DataSeries Prix { get; set; }
        [Parameter(DefaultValue = 32)]
        public int Period { get; set; }
        private ExponentialMovingAverage Ema;
        [Parameter(DefaultValue = 39)]
        public int Period2 { get; set; }
        private ExponentialMovingAverage Ema2;
        [Parameter(DefaultValue = 50)]
        public int Period3 { get; set; }
        private ExponentialMovingAverage Ema3;
        [Parameter(DefaultValue = 75)]
        public int Period4 { get; set; }
        private ExponentialMovingAverage Ema4;
        [Parameter(DefaultValue = 100)]
        public int Period5 { get; set; }
        private ExponentialMovingAverage Ema5;

        [Parameter("Stop Loss (pips)", DefaultValue = 20, MinValue = 1)]
        public int StopLossInPips { get; set; }
        [Parameter("Take Profit (pips)", DefaultValue = 60, MinValue = 1)]
        public int TakeProfitInPips { get; set; }
        public double Quantity;
        private const string Label = "";
        private MacdCrossOver MyMacd;
//====================== Pivot ==================================//
        private int GetStartDayIndex(int index)
        {
            var startDayIndex = index;
            while (startDayIndex > 0 && MarketSeries.OpenTime[startDayIndex].Date == MarketSeries.OpenTime[index].Date)
                startDayIndex--;
            return ++startDayIndex;
        }
        private double GetHigh(int fromIndex, int toIndex)
        {
            var result = MarketSeries.High[fromIndex];
            for (var i = fromIndex; i <= toIndex; i++)
                result = Math.Max(result, MarketSeries.High[i]);
            return result;
        }
        private double GetLow(int fromIndex, int toIndex)
        {
            var result = MarketSeries.Low[fromIndex];
            for (var i = fromIndex; i <= toIndex; i++)
                result = Math.Min(result, MarketSeries.Low[i]);
            return result;
        }
//====================== Calculs des paramètres =================//
        protected override void OnStart()
        {

            _startTime = Server.Time.Date.AddHours(StartTime);
            _stopTime = Server.Time.Date.AddHours(StopTime);

            if (Account.Equity <= 1500)
                Quantity = 10000;
            if ((Account.Equity > 1500) && (Account.Equity <= 3000))
                Quantity = 20000;
            if ((Account.Equity > 3000) && (Account.Equity <= 4500))
                Quantity = 30000;
            if ((Account.Equity > 4500) && (Account.Equity <= 6000))
                Quantity = 40000;
            if ((Account.Equity > 6000) && (Account.Equity <= 7500))
                Quantity = 50000;
            if ((Account.Equity > 7500) && (Account.Equity <= 9000))
                Quantity = 60000;
            if ((Account.Equity > 9000) && (Account.Equity <= 10500))
                Quantity = 70000;
            if ((Account.Equity > 10500) && (Account.Equity <= 12000))
                Quantity = 80000;
            if ((Account.Equity > 12000) && (Account.Equity <= 13500))
                Quantity = 90000;
            if ((Account.Equity > 13500) && (Account.Equity <= 15000))
                Quantity = 100000;
            if ((Account.Equity > 15000) && (Account.Equity <= 16500))
                Quantity = 110000;
            if ((Account.Equity > 16500) && (Account.Equity <= 18000))
                Quantity = 120000;
            if ((Account.Equity > 18000) && (Account.Equity <= 19500))
                Quantity = 130000;
            if ((Account.Equity > 19500) && (Account.Equity <= 21000))
                Quantity = 140000;
            if ((Account.Equity > 21000) && (Account.Equity <= 22500))
                Quantity = 150000;
            if ((Account.Equity > 22500) && (Account.Equity <= 24000))
                Quantity = 160000;
            if ((Account.Equity > 24000) && (Account.Equity <= 25500))
                Quantity = 170000;
            if ((Account.Equity > 25500) && (Account.Equity <= 27000))
                Quantity = 180000;
            if ((Account.Equity > 27000) && (Account.Equity <= 30000))
                Quantity = 190000;
            if (Account.Equity > 30000)
                Quantity = 200000;

            Ema = Indicators.ExponentialMovingAverage(MarketSeries.Close, Period);
            Ema2 = Indicators.ExponentialMovingAverage(MarketSeries.Close, Period2);
            Ema3 = Indicators.ExponentialMovingAverage(MarketSeries.Close, Period3);
            Ema4 = Indicators.ExponentialMovingAverage(MarketSeries.Close, Period4);
            Ema5 = Indicators.ExponentialMovingAverage(MarketSeries.Close, Period5);
            MyMacd = Indicators.MacdCrossOver(5, 11, 3);
        }

        protected override void OnTick()
        {
            var currentHours = Server.Time.TimeOfDay.TotalHours;
            bool tradeTime = StartTime < StopTime ? currentHours > StartTime && currentHours < StopTime : currentHours < StopTime || currentHours > StartTime;
            if (currentHours >= StopTime)
            {
                Close(TradeType.Sell);
                Close(TradeType.Buy);
            }
        }

        protected override void OnBar()
        {



//========================= Horaire de trading =========================//


            var currentHours = Server.Time.TimeOfDay.TotalHours;
            bool tradeTime = StartTime < StopTime ? currentHours > StartTime && currentHours < StopTime : currentHours < StopTime || currentHours > StartTime;
            if (!tradeTime)
                return;

            if (Positions.Count != 0)
                return;

//========================= Moyennes mobiles =========================//
            var currentprix = MarketSeries.Close.Last(0);
            var currentema = Ema.Result.Last(0);
            var currentema2 = Ema2.Result.Last(0);
            var currentema3 = Ema3.Result.Last(0);
            var currentema4 = Ema4.Result.Last(0);
            var currentema5 = Ema5.Result.Last(0);
//========================= Macd =========================//            
            var signal = MyMacd.Signal[0];
            var macd = MyMacd.MACD[0];
//===================== pivot =====================================//
            if (TimeFrame == TimeFrame.Daily)
                return;
            var todayStartIndex = GetStartDayIndex(0);
            if (todayStartIndex == 0)
                return;
            var yesterdayStartIndex = GetStartDayIndex(todayStartIndex - 1);
            var yHigh = GetHigh(yesterdayStartIndex, todayStartIndex - 1);
            var yLow = GetLow(yesterdayStartIndex, todayStartIndex - 1);
            var yClose = MarketSeries.Close[todayStartIndex - 1];
            var yHigh2 = GetHigh(yesterdayStartIndex - 1, todayStartIndex - 2);
            var yLow2 = GetLow(yesterdayStartIndex - 1, todayStartIndex - 2);
            var yClose2 = MarketSeries.Close[todayStartIndex - 2];
            var pivot = (yHigh + yLow + yClose) / 3;
            var pivot2 = (yHigh2 + yLow2 + yClose2) / 3;
            var s1 = (pivot * 2) - yHigh;
            var ms1 = ((s1 - pivot) / 2 + pivot);
            var r1 = (pivot * 2) - yLow;
            var mr1 = ((r1 - pivot) / 2 + pivot);
//====================== Trade Type =================================//   
            var longPosition = Positions.Find(Label, Symbol, TradeType.Buy);
            var shortPosition = Positions.Find(Label, Symbol, TradeType.Sell);


//======================= Condition d'achat ===========================================//
            if ((currentprix < currentema) && (currentprix > currentema2) && (currentema2 > currentema3) && (currentema3 > currentema4) && (currentema4 > currentema5) && (longPosition == null) && (shortPosition == null) && (MyMacd.Signal.HasCrossedAbove(MyMacd.MACD, 0)))
            {
                ExecuteMarketOrder(TradeType.Buy, Symbol, Quantity, Label, StopLossInPips, TakeProfitInPips);
            }
//======================= Condition de vente ===========================================//
            if ((currentprix > currentema) && (currentprix < currentema2) && (currentema2 < currentema3) && (currentema3 < currentema4) && (currentema4 < currentema5) && (shortPosition == null) && (longPosition == null) && (MyMacd.Signal.HasCrossedBelow(MyMacd.MACD, 0)))
            {
                ExecuteMarketOrder(TradeType.Sell, Symbol, Quantity, Label, StopLossInPips, TakeProfitInPips);

            }
        }

        private void Close(TradeType tradeType)
        {
            foreach (var position in Positions.FindAll(Label, Symbol, tradeType))
                ClosePosition(position);
        }

    }
}

 


@tradermatrix

tradermatrix
16 Nov 2018, 20:08

effectively...the robot is built for a first random order ... then it stays in the same direction ... and it leads to disaster if you are in the wrong direction for a long time.
test this one ... it is completely random.
Warning ... you will never do the same backtesting
cordially

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

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

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class SampleMartingalecBot : Robot
    {
        [Parameter("Initial Volume", DefaultValue = 10000, MinValue = 0)]
        public int InitialVolume { get; set; }

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

        [Parameter("Take Profit", DefaultValue = 20)]
        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, GetRandomTradeType());
                //
            }
        }

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

 


@tradermatrix

tradermatrix
12 Jul 2018, 22:00

RE:

ceakuk said:

I have created an amazing cbot and I would like to share it here without  showing the  source codes.

How can I do it?

can the source code of cbot.algo be read?

 

I want others to use my bot without giving the source code.

Thanks in advance

 

Hello
there are probably several solutions.
you can distribute the algo file ...
left on the dashboard select "show in folder"
you can copy and paste the file and send it to the mailbox of the person who asks you.
he can use your cBot without seeing the code.
you can send it to me without any problem
cordially
 

 


@tradermatrix

tradermatrix
04 Jul 2018, 12:06

Thank you for your answers
I specify that [Parameter ("Break time (hour)" does not stop the robot. The cbot continues to work until he hits SL and TP or net earnings ... etc .... Then he will not be able to place new orders until the opening of the markets the following week.
UTC = User Time Offset
that I change bottom right of the platform ... UTC + 2 in summer ... UTC + 1 in winter (France)

http://help.spotware.com/user-time-offset

my code works very well but I have to manually adjust to my time zone "UTC" (left on my cBot) so that "StopTime" is adapted to the place where I work.
it is not a problem except for the backtesting over several years because I have to choose between summer time UTC + 2 and UTC + 1 winters
that's why I'm looking for a code that automatically adapts to the time zone.
I miss something or it's not possible.

thank you for everything

example with UTC Friday 8 June

[Parameter("Current Time UTC", DefaultValue = 2)]

public double UTC { get; set; }

[Parameter("Break time (hour)", DefaultValue = 16, MinValue = 0, MaxValue = 23)]

public int StopTime { get; set; }

var currentHours = Server.Time.TimeOfDay.Hours + UTC;

 

08/06/2018 08:27	EURUSD	€ 1k	Vendre	1,17766	1,17608	08/06/2018 10:22	1,27	1028,97
08/06/2018 08:37	EURUSD	€ 1k	Acheter	1,17843	1,17603	08/06/2018 10:22	-2,13	1026,84
08/06/2018 09:39	EURUSD	€ 3k	Vendre	1,17691	1,17608	08/06/2018 10:22	1,85	1028,69
08/06/2018 10:21	EURUSD	€ 4k	Vendre	1,17619	1,17608	08/06/2018 10:22	0,02	1028,71
08/06/2018 10:22	EURUSD	€ 1k	Acheter	1,17608	1,17694	08/06/2018 11:20	0,66	1029,37
08/06/2018 10:43	EURUSD	€ 2k	Acheter	1,17679	1,17694	08/06/2018 11:20	0,08	1029,45
08/06/2018 11:20	EURUSD	€ 1k	Vendre	1,17694	1,17609	08/06/2018 12:02	0,65	1030,1
08/06/2018 12:02	EURUSD	€ 1k	Acheter	1,17609	1,1728	08/06/2018 13:13	-2,9	1027,2
08/06/2018 12:05	EURUSD	€ 1k	Vendre	1,1748	1,17285	08/06/2018 13:13	1,59	1028,79
08/06/2018 12:58	EURUSD	€ 3k	Vendre	1,1738	1,17285	08/06/2018 13:13	2,16	1030,95
08/06/2018 13:11	EURUSD	€ 4k	Vendre	1,17309	1,17285	08/06/2018 13:13	0,46	1031,41
08/06/2018 13:13	EURUSD	€ 1k	Vendre	1,1728	1,17534	08/06/2018 14:03	-2,25	1029,16
08/06/2018 13:20	EURUSD	€ 1k	Acheter	1,17366	1,17529	08/06/2018 14:03	1,31	1030,47
08/06/2018 13:42	EURUSD	€ 3k	Acheter	1,17439	1,17529	08/06/2018 14:03	2,03	1032,5
08/06/2018 13:51	EURUSD	€ 4k	Acheter	1,17512	1,17529	08/06/2018 14:03	0,22	1032,72
10/06/2018 23:05	EURUSD	€ 1k	Acheter	1,17742	1,17816	11/06/2018 01:41	0,55	1033,27

example code without UTC
the bot continues to place orders after 2 pm until 4 pm
2 hours of +

421	08/06/2018 12:59	EURUSD	€ 1k	Vendre	1,1735	1,17568	08/06/2018 14:27	-1,95	1163,87
421	08/06/2018 13:11	EURUSD	€ 2k	Vendre	1,17309	1,17568	08/06/2018 14:27	-4,61	1159,26
421	08/06/2018 13:26	EURUSD	€ 1k	Acheter	1,174	1,17563	08/06/2018 14:27	1,31	1160,57
421	08/06/2018 13:42	EURUSD	€ 4k	Acheter	1,17439	1,17563	08/06/2018 14:27	3,88	1164,45
421	08/06/2018 13:44	EURUSD	€ 5k	Acheter	1,17484	1,17563	08/06/2018 14:27	2,94	1167,39
421	08/06/2018 14:03	EURUSD	€ 6k	Acheter	1,17534	1,17563	08/06/2018 14:27	0,95	1168,34
421	08/06/2018 14:27	EURUSD	€ 1k	Acheter	1,17568	1,17379	08/06/2018 14:43	-1,7	1166,64
421	08/06/2018 14:32	EURUSD	€ 1k	Vendre	1,17521	1,17384	08/06/2018 14:43	1,09	1167,73
421	08/06/2018 14:35	EURUSD	€ 3k	Vendre	1,17474	1,17384	08/06/2018 14:43	2,03	1169,76
421	08/06/2018 14:40	EURUSD	€ 4k	Vendre	1,17431	1,17384	08/06/2018 14:43	1,25	1171,01
421	08/06/2018 14:43	EURUSD	€ 1k	Acheter	1,17384	1,17479	08/06/2018 15:00	0,73	1171,74
421	08/06/2018 14:45	EURUSD	€ 2k	Acheter	1,17429	1,17479	08/06/2018 15:00	0,68	1172,42
421	08/06/2018 14:57	EURUSD	€ 3k	Acheter	1,17461	1,17479	08/06/2018 15:00	0,18	1172,6
421	08/06/2018 15:00	EURUSD	€ 1k	Acheter	1,17484	1,17605	08/06/2018 15:14	0,96	1173,56
421	08/06/2018 15:02	EURUSD	€ 1k	Vendre	1,17443	1,1761	08/06/2018 15:14	-1,51	1172,05
421	08/06/2018 15:11	EURUSD	€ 3k	Acheter	1,17516	1,17605	08/06/2018 15:14	2	1174,05
421	08/06/2018 15:12	EURUSD	€ 4k	Acheter	1,17549	1,17605	08/06/2018 15:14	1,56	1175,61
421	08/06/2018 15:14	EURUSD	€ 1k	Acheter	1,1761	1,17731	08/06/2018 16:34	0,96	1176,57
421	08/06/2018 15:18	EURUSD	€ 1k	Vendre	1,17574	1,17736	08/06/2018 16:34	-1,47	1175,1
421	08/06/2018 15:21	EURUSD	€ 3k	Acheter	1,17648	1,17731	08/06/2018 16:34	1,85	1176,95
421	08/06/2018 15:30	EURUSD	€ 4k	Acheter	1,17688	1,17731	08/06/2018 16:34	1,11	1178,06
421	11/06/2018 01:41	EURUSD	€ 3k	Acheter	1,17821	1,17896	11/06/2018 02:43	1,65	1179,21

 


@tradermatrix

tradermatrix
22 Apr 2018, 01:10

you have to program one command at a time
can be like that;
 

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

        [Parameter("Slow Periods", DefaultValue = 30)]
        public int SlowPeriods { get; set; }

        [Parameter("Fast Periods", DefaultValue = 14)]
        public int FastPeriods { get; set; }

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

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

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

        private ExponentialMovingAverage slowMa;
        private ExponentialMovingAverage fastMa;

        private const string label = "EMA";

        private Position longPosition;
        private Position shortPosition;

        protected override void OnStart()
        {
            fastMa = Indicators.ExponentialMovingAverage(SourceSeries, FastPeriods);
            slowMa = Indicators.ExponentialMovingAverage(SourceSeries, SlowPeriods);
        }

        protected override void OnBar()
        {
            var cBotPositions = Positions.FindAll(label);

            longPosition = Positions.Find(label, Symbol, TradeType.Buy);
            shortPosition = Positions.Find(label, Symbol, TradeType.Sell);

            if (cBotPositions.Length >= 1)
                return;

            if (slowMa.Result.Last(1) < fastMa.Result.Last(1) && longPosition == null)
            {
                ExecuteMarketOrder(TradeType.Buy, Symbol, VolumeInUnits, label, StopLossInPips, TakeProfitInPips);

            }
            else if (slowMa.Result.Last(1) > fastMa.Result.Last(1) && shortPosition == null)
            {
                ExecuteMarketOrder(TradeType.Sell, Symbol, VolumeInUnits, label, StopLossInPips, TakeProfitInPips);

            }


        }

        private long VolumeInUnits
        {
            get { return Symbol.QuantityToVolume(Quantity); }
        }
    }
}

 


@tradermatrix

tradermatrix
09 Apr 2018, 16:33

RE:

ceakuk said:

ExecuteMarketOrder(TradeType.Buy, Symbol, 5000, "myLabel", 10, 10, XXXX, "this is a comment");

Hi,

Im interested in adding label and comment without this Markert range pips which I have no idea what it is and how to set it.

How can I avoid using Markert range pips or what should I set it to if I dont need it?

Thanks

Kevin

Bonjour

j utilise cette methode

ExecuteMarketOrder(TradeType.Buy, Symbol, 5000, "myLabel", 10, 10, null, "this is a comment");

 


@tradermatrix

tradermatrix
23 Mar 2018, 14:42

thanks Panagiotis
actually it causes a failure.
So, bypassing the problem, I moved Indicator.MovingAverage from "OnStart" to "OnTick ()".
I found that the orders are exactly the same as the previous method (at the millisecond)
I do not find breakdowns on several years of backtesting
cordially

  protected override void OnTick()
        {
            play();
        }

        private void play()
        {
            var cBotPositions = Positions.FindAll("MoVinG");

            if (cBotPositions.Length >= 1)
                return;



            if (_movingAverage.Result.IsRising())
            {
                ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, "MoVinG", SL, TP);
            }
            else if (_movingAverage.Result.IsFalling())
            {
                ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, "MoVinG", SL, TP);

            }
        }
22/09/2017 16:41:03.248 | Executing Market Order to Sell 1000 EURUSD (SL: 10, TP: 12)
22/09/2017 16:41:03.248 | → Executing Market Order to Sell 1000 EURUSD (SL: 10, TP: 12) SUCCEEDED, Position PID507
22/09/2017 20:59:56.251 | Closed
22/09/2017 20:59:56.251 | Crashed in Positions.Closed with NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet.



22/09/2017 20:59:56.251 | closed
22/09/2017 20:59:56.251 | Losing Trade
22/09/2017 20:59:56.456 | Executing Market Order to Buy 2000 EURUSD (SL: 10, TP: 12)
22/09/2017 20:59:56.456 | → Executing Market Order to Buy 2000 EURUSD (SL: 10, TP: 12) 

 


@tradermatrix