Topics
20 May 2021, 06:16
 1
 857
 1
14 May 2021, 23:32
 2163
 10
13 May 2021, 07:35
 2
 921
 1
17 Mar 2021, 18:36
 0
 1014
 1
Replies

freyrthegreat
05 Jul 2021, 12:18

RE:

Hi,

finally managed to test the revised code. everything finally working as expected.

thanks for the help. appreciate it

 


@freyrthegreat

freyrthegreat
02 Jul 2021, 12:57

RE:

Hi,

i revised the code based on your suggestion and it worked. Thanks for that. However after i added a few more criteria, the SL to entry trigger does not work again.

i wanted to add tradetype criteria for the distance calculation whereby the "distancebuy"  calculation and the resulting modification would only apply to long position and vice versa. But it doesnt work. would you mind having a look?

using System;
using System.Linq;
using System.Text;
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 NewsRobotwithBE : Robot
    {

        [Parameter("News Hour", DefaultValue = 14, MinValue = 0, MaxValue = 23)]
        public int NewsHour { get; set; }

        [Parameter("News Minute", DefaultValue = 30, MinValue = 0, MaxValue = 59)]
        public int NewsMinute { get; set; }

        [Parameter("Pips away", DefaultValue = 10)]
        public int PipsAway { get; set; }

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

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

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

        [Parameter("Seconds Before", DefaultValue = 10, MinValue = 1)]
        public int SecondsBefore { get; set; }

        [Parameter("Seconds Timeout", DefaultValue = 10, MinValue = 1)]
        public int SecondsTimeout { get; set; }

        [Parameter("One Cancels Other")]
        public bool Oco { get; set; }

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

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

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

        private bool _ordersCreated;

        private DateTime _triggerTimeInServerTimeZone;

        private const string Label = "News Robot";

        protected override void OnStart()
        {
            Positions.Opened += OnPositionOpened;
            Timer.Start(1);

            var triggerTimeInLocalTimeZone = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, NewsHour, NewsMinute, 0);
            if (triggerTimeInLocalTimeZone < DateTime.Now)
                triggerTimeInLocalTimeZone = triggerTimeInLocalTimeZone.AddDays(1);
            _triggerTimeInServerTimeZone = TimeZoneInfo.ConvertTime(triggerTimeInLocalTimeZone, TimeZoneInfo.Local, TimeZone);
        }

        protected override void OnTimer()
        {
            var remainingTime = _triggerTimeInServerTimeZone - Server.Time;
            DrawRemainingTime(remainingTime);

            if (!_ordersCreated)
            {
                var sellOrderTargetPrice = Symbol.Bid - PipsAway * Symbol.PipSize;
                ChartObjects.DrawHorizontalLine("sell target", sellOrderTargetPrice, Colors.Red, 1, LineStyle.DotsVeryRare);
                var buyOrderTargetPrice = Symbol.Ask + PipsAway * Symbol.PipSize;
                ChartObjects.DrawHorizontalLine("buy target", buyOrderTargetPrice, Colors.Blue, 1, LineStyle.DotsVeryRare);

                if (Server.Time <= _triggerTimeInServerTimeZone && (_triggerTimeInServerTimeZone - Server.Time).TotalSeconds <= SecondsBefore)
                {
                    _ordersCreated = true;
                    var expirationTime = _triggerTimeInServerTimeZone.AddSeconds(SecondsTimeout);

                    PlaceStopOrder(TradeType.Sell, Symbol, Volume, sellOrderTargetPrice, Label, StopLoss, TakeProfit, expirationTime);
                    PlaceStopOrder(TradeType.Buy, Symbol, Volume, buyOrderTargetPrice, Label, StopLoss, TakeProfit, expirationTime);

                    ChartObjects.RemoveObject("sell target");
                    ChartObjects.RemoveObject("buy target");
                }
            }

            if (_ordersCreated && !PendingOrders.Any(o => o.Label == Label))
            {
                Print("Orders expired");
            }
        }

        private void DrawRemainingTime(TimeSpan remainingTimeToNews)
        {
            if (ShowTimeLeftToNews)
            {
                if (remainingTimeToNews > TimeSpan.Zero)
                {
                    ChartObjects.DrawText("countdown1", "Time left to news: " + FormatTime(remainingTimeToNews), StaticPosition.TopLeft);
                }
                else
                {
                    ChartObjects.RemoveObject("countdown1");
                }
            }
            if (ShowTimeLeftToPlaceOrders)
            {
                var remainingTimeToOrders = remainingTimeToNews - TimeSpan.FromSeconds(SecondsBefore);
                if (remainingTimeToOrders > TimeSpan.Zero)
                {
                    ChartObjects.DrawText("countdown2", "Time left to place orders: " + FormatTime(remainingTimeToOrders), StaticPosition.TopRight);
                }
                else
                {
                    ChartObjects.RemoveObject("countdown2");
                }
            }
        }

        private static StringBuilder FormatTime(TimeSpan remainingTime)
        {
            var remainingTimeStr = new StringBuilder();
            if (remainingTime.TotalHours >= 1)
                remainingTimeStr.Append((int)remainingTime.TotalHours + "h ");
            if (remainingTime.TotalMinutes >= 1)
                remainingTimeStr.Append(remainingTime.Minutes + "m ");
            if (remainingTime.TotalSeconds > 0)
                remainingTimeStr.Append(remainingTime.Seconds + "s");
            return remainingTimeStr;
        }

        private void OnPositionOpened(PositionOpenedEventArgs args)
        {
            var position = args.Position;
            if (position.Label == Label && position.SymbolCode == Symbol.Code)
            {
                if (Oco)
                {
                    foreach (var order in PendingOrders)
                    {
                        if (order.Label == Label && order.SymbolCode == Symbol.Code)
                        {
                            CancelPendingOrderAsync(order);
                        }
                    }
                }
            }
        }

        protected override void OnTick()
        {
            var position = Positions.Find(Label, SymbolName);

            if (position == null)
                return;

            var entryPrice = position.EntryPrice;
            var distanceBuy = Symbol.Bid - entryPrice;
            var distanceSell = entryPrice - Symbol.Ask;

            if (position.TradeType == TradeType.Buy)
            {
                if (distanceBuy >= Trigger * Symbol.PipSize)
                {
                    ModifyPosition(position, entryPrice, position.TakeProfit);
                    Print("Stop Loss to Break Even set for position {0}", position.Id);
                }
            }
            else
            {
                if (position.TradeType == TradeType.Sell)
                {
                    if (distanceSell >= Trigger * Symbol.PipSize)
                    {
                        ModifyPosition(position, entryPrice, position.TakeProfit);
                        Print("Stop Loss to Break Even set for position {0}", position.Id);
                    }
                }
            }
        }
    }
}


@freyrthegreat

freyrthegreat
25 May 2021, 04:44

RE:

firemyst said:

Currently, there's known issues with the built in cTrader SuperTrend indicator which might be causing you problems as well.

See this thread:

You might be trying to set a SL on an ST value which doesn't exist.

 

that might explain some of the results i got while backtesting where my trade closed at seemingly random position. thanks for the heads up.


@freyrthegreat

freyrthegreat
18 May 2021, 09:22

RE:

PanagiotisCharalampous said:

Hi freyrthegreat,

You can try something like this

               var position = ExecuteMarketOrder(TradeType.Buy, SymbolName, _volumeInUnits, Label, null, null).Position;
                position.ModifyStopLossPrice(Math.Round(_supertrend.DownTrend.LastValue, Symbol.Digits));
                position.ModifyTakeProfitPrice(Math.Round(_supertrend.UpTrend.LastValue, Symbol.Digits));

Best Regards,

Panagiotis 

Join us on Telegram

Hi panagiotis,

i recompiled i and tested the bot on my demo account. seems like the trade is succesfully opened based on criteria. but it did not open with SL.

and looking at the log there was an error modifying position as well stating "invalidstoplosstakeprofit" and "invalidrequest".

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
    // This sample cBot shows how to use the Supertrend indicator
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class Supertrendvar : Robot
    {
        private double _volumeInUnits;
        private Supertrend _supertrend;
        [Parameter("Volume (Lots)", DefaultValue = 0.01)]
        public double VolumeInLots { get; set; }
        [Parameter("Label", DefaultValue = "Sample")]
        public string Label { get; set; }
        public Position[] BotPositions
        {
            get { return Positions.FindAll(Label); }
        }
        protected override void OnStart()
        {
            _volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots);
            _supertrend = Indicators.Supertrend(10, 3);
        }
        protected override void OnBar()
        {
xa
            if (_supertrend.UpTrend.Last(1) < Bars.LowPrices.Last(1) && _supertrend.DownTrend.Last(2) > Bars.HighPrices.Last(2))
            {
                var position = ExecuteMarketOrder(TradeType.Buy, SymbolName, _volumeInUnits, Label, null, null).Position;
                position.ModifyStopLossPrice(Math.Round(_supertrend.DownTrend.LastValue, Symbol.Digits));
                position.ModifyTakeProfitPrice(Math.Round(_supertrend.UpTrend.LastValue, Symbol.Digits));
            }
            if (_supertrend.DownTrend.Last(1) > Bars.HighPrices.Last(1) && _supertrend.UpTrend.Last(2) < Bars.LowPrices.Last(2))
            {
                var position = ExecuteMarketOrder(TradeType.Sell, SymbolName, _volumeInUnits, Label, null, null).Position;
                position.ModifyStopLossPrice(Math.Round(_supertrend.UpTrend.LastValue, Symbol.Digits));
                position.ModifyTakeProfitPrice(Math.Round(_supertrend.DownTrend.LastValue, Symbol.Digits));
            }
        }
        private void ClosePositions(TradeType tradeType)
        {
            foreach (var position in BotPositions)
            {
                if (position.TradeType != tradeType)
                    continue;
                ClosePosition(position);
            }
        }
    }
}


@freyrthegreat

freyrthegreat
17 May 2021, 08:48

RE:

PanagiotisCharalampous said:

Hi freyrthegreat,

SL and TP should be set in pips. You are using absolute prices instead. You should convert in pips first.

Best Regards,

Panagiotis 

Join us on Telegram

Hi,

 

Apologies. I forgot to remove the SL and TP parameter before posting.

But im looking to use the supertrend value to set SL and trail it. 

 


@freyrthegreat