Replies

rwieden
23 Apr 2018, 16:56 ( Updated at: 21 Dec 2023, 09:20 )

RE:

Panagiotis Charalampous said:

Dear rwieden,

Thanks but I am seeing different parameters. See below

Am I using the correct robot?

Best Regards,

Panagiotis

Sorry for confusion, below should be the correct cbot, I would highly appreciate if you could check what might cause the issue

//+------------------------------------------------------------------+
//+                           Code generated using FxPro Quant 2.1.4 |
//+------------------------------------------------------------------+

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


namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC)]
    public class Prototype : Robot
    {

        [Parameter("weekday_1", DefaultValue = 0)]
        public double _weekday_1 { get; set; }
        [Parameter("weekday_3", DefaultValue = 0)]
        public double _weekday_3 { get; set; }
        [Parameter("CRV", DefaultValue = 0)]
        public double _CRV { get; set; }
        [Parameter("weekday_2", DefaultValue = 0)]
        public double _weekday_2 { get; set; }
        [Parameter("Start_Hour", DefaultValue = 0)]
        public double _Start_Hour { get; set; }
        [Parameter("max_Range", DefaultValue = 0)]
        public double _max_Range { get; set; }
        [Parameter("min_Range", DefaultValue = 0)]
        public double _min_Range { get; set; }
        [Parameter("Risk_Percent", DefaultValue = 0)]
        public double _Risk_Percent { get; set; }
        [Parameter("Point_Value", DefaultValue = 0)]
        public double _Point_Value { get; set; }

        //Global declaration
        double _Prev_Low;
        double _M1_Open_Candle;
        double _Prev_High;
        double _Arithmetic;
        double _Calculate_Range;
        double _Round_SL;

        DateTime LastTradeExecution = new DateTime(0);

        protected override void OnStart()
        {

        }

        protected override void OnTick()
        {
            if (Trade.IsExecuting)
                return;

            //Local declaration
            TriState _Close_Short_Position = new TriState();
            TriState _Send_Pending_Short = new TriState();

            //Step 1
            _Prev_Low = MarketSeries.Low.Last(1);
            _M1_Open_Candle = MarketData.GetSeries(TimeFrame.Minute).Open.Last(0);
            _Prev_High = MarketSeries.High.Last(1);

            //Step 2
            _Arithmetic = (_Prev_High - (_Prev_Low));

            //Step 3

            //Step 4
            if ((((int)Server.Time.DayOfWeek == 5) && IsTime(20, 21, 0, 0)))
                _Close_Short_Position = _ClosePosition(2, Symbol.Code, 0);
            _Calculate_Range = ((_Arithmetic / (_M1_Open_Candle)) * (100));
            _Round_SL = Math.Round(Transform(_Arithmetic, 0) * Math.Pow(10, 0)) / Math.Pow(10, 0);

            //Step 5

            //Step 6

            //Step 7

            //Step 8

            //Step 9
            if ((IsTime(_Start_Hour, (_Start_Hour + (0)), 2, 2) && (_M1_Open_Candle < _Prev_High) && (_M1_Open_Candle > _Prev_Low) && (_Calculate_Range > _min_Range) && (_Calculate_Range < _max_Range) && (((int)Server.Time.DayOfWeek == _weekday_1) || ((int)Server.Time.DayOfWeek == _weekday_2) || (_weekday_3 == (int)Server.Time.DayOfWeek)) && NoOrders(Symbol.Code, new double[] 
            {
                2
            }) && !Trade_Exists(2)))
                _Send_Pending_Short = _SendPending(2, true, Symbol.Code, PendingOrderType.Stop, TradeType.Sell, Math.Round(((Account.Equity * ((_Risk_Percent / (100)))) / (((_Round_SL * (_Point_Value)) * ((1 / (MarketSeries.Open.Last(0))))))) * Math.Pow(10, 2)) / Math.Pow(10, 2), 0, _Prev_Low, _Round_SL, Math.Round((_Round_SL * (_CRV)) * Math.Pow(10, 0)) / Math.Pow(10, 0),
                Server.Time.AddHours(4), "Range Breakout");

        }

        bool NoOrders(string symbolCode, double[] magicIndecies)
        {
            if (symbolCode == "")
                symbolCode = Symbol.Code;
            string[] labels = new string[magicIndecies.Length];
            for (int i = 0; i < magicIndecies.Length; i++)
            {
                labels[i] = "FxProQuant_" + magicIndecies[i].ToString("F0");
            }
            foreach (Position pos in Positions)
            {
                if (pos.SymbolCode != symbolCode)
                    continue;
                if (labels.Length == 0)
                    return false;
                foreach (var label in labels)
                {
                    if (pos.Label == label)
                        return false;
                }
            }
            foreach (PendingOrder po in PendingOrders)
            {
                if (po.SymbolCode != symbolCode)
                    continue;
                if (labels.Length == 0)
                    return false;
                foreach (var label in labels)
                {
                    if (po.Label == label)
                        return false;
                }
            }
            return true;
        }

        TriState _OpenPosition(double magicIndex, bool noOrders, string symbolCode, TradeType tradeType, double lots, double slippage, double? stopLoss, double? takeProfit, string comment)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            if (noOrders && Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)
                return new TriState();
            if (stopLoss < 1)
                stopLoss = null;
            if (takeProfit < 1)
                takeProfit = null;
            if (symbol.Digits == 5 || symbol.Digits == 3)
            {
                if (stopLoss != null)
                    stopLoss /= 10;
                if (takeProfit != null)
                    takeProfit /= 10;
                slippage /= 10;
            }
            int volume = Convert.ToInt32(lots * 100000);
            if (!ExecuteMarketOrder(tradeType, symbol, volume, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, slippage, comment).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _SendPending(double magicIndex, bool noOrders, string symbolCode, PendingOrderType poType, TradeType tradeType, double lots, int priceAction, double priceValue, double? stopLoss, double? takeProfit,
        DateTime? expiration, string comment)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            if (noOrders && PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)
                return new TriState();
            if (stopLoss < 1)
                stopLoss = null;
            if (takeProfit < 1)
                takeProfit = null;
            if (symbol.Digits == 5 || symbol.Digits == 3)
            {
                if (stopLoss != null)
                    stopLoss /= 10;
                if (takeProfit != null)
                    takeProfit /= 10;
            }
            int volume = Convert.ToInt32(lots * 100000);
            double targetPrice;
            switch (priceAction)
            {
                case 0:
                    targetPrice = priceValue;
                    break;
                case 1:
                    targetPrice = symbol.Bid - priceValue * symbol.TickSize;
                    break;
                case 2:
                    targetPrice = symbol.Bid + priceValue * symbol.TickSize;
                    break;
                case 3:
                    targetPrice = symbol.Ask - priceValue * symbol.TickSize;
                    break;
                case 4:
                    targetPrice = symbol.Ask + priceValue * symbol.TickSize;
                    break;
                default:
                    targetPrice = priceValue;
                    break;
            }
            if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))
                expiration = null;
            if (poType == PendingOrderType.Limit)
            {
                if (!PlaceLimitOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful)
                {
                    Thread.Sleep(400);
                    return false;
                }
                return true;
            }
            else if (poType == PendingOrderType.Stop)
            {
                if (!PlaceStopOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful)
                {
                    Thread.Sleep(400);
                    return false;
                }
                return true;
            }
            return new TriState();
        }

        TriState _ModifyPosition(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (pos == null)
                return new TriState();
            double? sl, tp;
            if (slValue == 0)
                sl = null;
            else
            {
                switch (slAction)
                {
                    case 0:
                        sl = pos.StopLoss;
                        break;
                    case 1:
                        if (pos.TradeType == TradeType.Buy)
                            sl = pos.EntryPrice - slValue * symbol.TickSize;
                        else
                            sl = pos.EntryPrice + slValue * symbol.TickSize;
                        break;
                    case 2:
                        sl = slValue;
                        break;
                    default:
                        sl = pos.StopLoss;
                        break;
                }
            }
            if (tpValue == 0)
                tp = null;
            else
            {
                switch (tpAction)
                {
                    case 0:
                        tp = pos.TakeProfit;
                        break;
                    case 1:
                        if (pos.TradeType == TradeType.Buy)
                            tp = pos.EntryPrice + tpValue * symbol.TickSize;
                        else
                            tp = pos.EntryPrice - tpValue * symbol.TickSize;
                        break;
                    case 2:
                        tp = tpValue;
                        break;
                    default:
                        tp = pos.TakeProfit;
                        break;
                }
            }
            if (!ModifyPosition(pos, sl, tp).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _ModifyPending(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue, int priceAction, double priceValue, int expirationAction, DateTime? expiration)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (po == null)
                return new TriState();
            double targetPrice;
            double? sl, tp;
            if (slValue == 0)
                sl = null;
            else
            {
                switch (slAction)
                {
                    case 0:
                        sl = po.StopLoss;
                        break;
                    case 1:
                        if (po.TradeType == TradeType.Buy)
                            sl = po.TargetPrice - slValue * symbol.TickSize;
                        else
                            sl = po.TargetPrice + slValue * symbol.TickSize;
                        break;
                    case 2:
                        sl = slValue;
                        break;
                    default:
                        sl = po.StopLoss;
                        break;
                }
            }
            if (tpValue == 0)
                tp = null;
            else
            {
                switch (tpAction)
                {
                    case 0:
                        tp = po.TakeProfit;
                        break;
                    case 1:
                        if (po.TradeType == TradeType.Buy)
                            tp = po.TargetPrice + tpValue * symbol.TickSize;
                        else
                            tp = po.TargetPrice - tpValue * symbol.TickSize;
                        break;
                    case 2:
                        tp = tpValue;
                        break;
                    default:
                        tp = po.TakeProfit;
                        break;
                }
            }
            switch (priceAction)
            {
                case 0:
                    targetPrice = po.TargetPrice;
                    break;
                case 1:
                    targetPrice = priceValue;
                    break;
                case 2:
                    targetPrice = po.TargetPrice + priceValue * symbol.TickSize;
                    break;
                case 3:
                    targetPrice = po.TargetPrice - priceValue * symbol.TickSize;
                    break;
                case 4:
                    targetPrice = symbol.Bid - priceValue * symbol.TickSize;
                    break;
                case 5:
                    targetPrice = symbol.Bid + priceValue * symbol.TickSize;
                    break;
                case 6:
                    targetPrice = symbol.Ask - priceValue * symbol.TickSize;
                    break;
                case 7:
                    targetPrice = symbol.Ask + priceValue * symbol.TickSize;
                    break;
                default:
                    targetPrice = po.TargetPrice;
                    break;
            }
            if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))
                expiration = null;
            if (expirationAction == 0)
                expiration = po.ExpirationTime;
            if (!ModifyPendingOrder(po, targetPrice, sl, tp, expiration).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _ClosePosition(double magicIndex, string symbolCode, double lots)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (pos == null)
                return new TriState();
            TradeResult result;
            if (lots == 0)
            {
                result = ClosePosition(pos);
            }
            else
            {
                int volume = Convert.ToInt32(lots * 100000);
                result = ClosePosition(pos, volume);
            }
            if (!result.IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _DeletePending(double magicIndex, string symbolCode)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (po == null)
                return new TriState();
            if (!CancelPendingOrder(po).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        bool _OrderStatus(double magicIndex, string symbolCode, int test)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (pos != null)
            {
                if (test == 0)
                    return true;
                if (test == 1)
                    return true;
                if (test == 3)
                    return pos.TradeType == TradeType.Buy;
                if (test == 4)
                    return pos.TradeType == TradeType.Sell;
            }
            var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (po != null)
            {
                if (test == 0)
                    return true;
                if (test == 2)
                    return true;
                if (test == 3)
                    return po.TradeType == TradeType.Buy;
                if (test == 4)
                    return po.TradeType == TradeType.Sell;
                if (test == 5)
                    return po.OrderType == PendingOrderType.Limit;
                if (test == 6)
                    return po.OrderType == PendingOrderType.Stop;
            }
            return false;
        }

        int TimeframeToInt(TimeFrame tf)
        {
            if (tf == TimeFrame.Minute)
                return 1;
            else if (tf == TimeFrame.Minute2)
                return 2;
            else if (tf == TimeFrame.Minute3)
                return 3;
            else if (tf == TimeFrame.Minute4)
                return 4;
            else if (tf == TimeFrame.Minute5)
                return 5;
            else if (tf == TimeFrame.Minute10)
                return 10;
            else if (tf == TimeFrame.Minute15)
                return 15;
            else if (tf == TimeFrame.Minute30)
                return 30;
            else if (tf == TimeFrame.Hour)
                return 60;
            else if (tf == TimeFrame.Hour4)
                return 240;
            else if (tf == TimeFrame.Daily)
                return 1440;
            else if (tf == TimeFrame.Weekly)
                return 10080;
            else if (tf == TimeFrame.Monthly)
                return 43200;
            return 1;
        }


        DateTime __currentBarTime = DateTime.MinValue;
        bool __isNewBar(bool triggerAtStart)
        {
            DateTime newTime = MarketSeries.OpenTime.LastValue;
            if (__currentBarTime != newTime)
            {
                if (!triggerAtStart && __currentBarTime == DateTime.MinValue)
                {
                    __currentBarTime = newTime;
                    return false;
                }
                __currentBarTime = newTime;
                return true;
            }
            return false;
        }


        bool Trade_Exists(double magicIndex)
        {
            return Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), Symbol) != null;
        }


        bool IsTime(double startHourParam, double endHourParam, double startMinuteParam, double endMinuteParam)
        {
            int startHour = Convert.ToInt32(startHourParam);
            int endHour = Convert.ToInt32(endHourParam);
            int startMinute = Convert.ToInt32(startMinuteParam);
            int endMinute = Convert.ToInt32(endMinuteParam);

            if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 || startMinute < 0 || startMinute > 59 || endMinute < 0 || endMinute > 59)
                return false;

            int startTime = startHour * 60 + startMinute;
            int endTime = endHour * 60 + endMinute;
            int time = Server.Time.Hour * 60 + Server.Time.Minute;

            if (startTime < endTime)
                return (time >= startTime && time <= endTime);
            else if (startTime > endTime)
                return (time >= startTime || time <= endTime);
            else
                return (time == startTime);
        }


        double Transform(double Value, int Transformation)
        {
            switch (Transformation)
            {
                case 0:
                    return (Value / Symbol.TickSize);
                case 1:
                    return (Value / Symbol.PipSize);
                case 2:
                    return (Value * Symbol.TickSize);
                case 3:
                    return (Value * Symbol.PipSize);
                default:
                    return (0);
            }
        }

    }
}

public struct TriState
{
    public static readonly TriState NonExecution = new TriState(0);
    public static readonly TriState False = new TriState(-1);
    public static readonly TriState True = new TriState(1);
    sbyte value;
    TriState(int value)
    {
        this.value = (sbyte)value;
    }
    public bool IsNonExecution
    {
        get { return value == 0; }
    }
    public static implicit operator TriState(bool x)
    {
        return x ? True : False;
    }
    public static TriState operator ==(TriState x, TriState y)
    {
        if (x.value == 0 || y.value == 0)
            return NonExecution;
        return x.value == y.value ? True : False;
    }
    public static TriState operator !=(TriState x, TriState y)
    {
        if (x.value == 0 || y.value == 0)
            return NonExecution;
        return x.value != y.value ? True : False;
    }
    public static TriState operator !(TriState x)
    {
        return new TriState(-x.value);
    }
    public static TriState operator &(TriState x, TriState y)
    {
        return new TriState(x.value < y.value ? x.value : y.value);
    }
    public static TriState operator |(TriState x, TriState y)
    {
        return new TriState(x.value > y.value ? x.value : y.value);
    }
    public static bool operator true(TriState x)
    {
        return x.value > 0;
    }
    public static bool operator false(TriState x)
    {
        return x.value < 0;
    }
    public static implicit operator bool(TriState x)
    {
        return x.value > 0;
    }
    public override bool Equals(object obj)
    {
        if (!(obj is TriState))
            return false;
        return value == ((TriState)obj).value;
    }
    public override int GetHashCode()
    {
        return value;
    }
    public override string ToString()
    {
        if (value > 0)
            return "True";
        if (value < 0)
            return "False";
        return "NonExecution";
    }
}

public static class PendingEx
{
    public static PendingOrder __Find(this cAlgo.API.PendingOrders pendingOrders, string label, Symbol symbol)
    {
        foreach (PendingOrder po in pendingOrders)
        {
            if (po.SymbolCode == symbol.Code && po.Label == label)
                return po;
        }
        return null;
    }
}

 


@rwieden

rwieden
23 Apr 2018, 13:18

RE:

Panagiotis Charalampous said:

Hi rwieden,

Thanks for the additional information. Could you please provide me the cBot parameters you are using? I will run the cBot on my side as well and check if I can reproduce the problem.

Best Regards,

Panagiotis

ChartParameters]

Symbol = EURUSD
Timeframe = h4

[cBotParameters]
_weekday_1 = 3
_CRV = 2.2
_weekday_3 = 5
_weekday_2 = 5
_Point_Value = 1
_max_Range = 2
_min_Range = 0.1
_Start_Hour = 8
_Risk_Percent = 2

@rwieden

rwieden
23 Apr 2018, 11:42

RE:

Panagiotis Charalampous said:

Hi rwieden,

It would be easier to get an answer if you contacted the broker directly, provide them with the position ID and explain them the issue. They should come back to you with the exact reason why the position was closed. The cBot's code is fairly extensive for someone to go through and guess what could go wrong. If the broker cannot provide an explanation, then we can investigate further.

Best Regards,

Panagiotis

Dear Panagiotis,

I forgot one important thing. Since this problem happened already before with other cbots, I decided to run for testing purpuse this cbot simultaniously on 2 different broker accounts on my VPS. In both cases the same error occured at the ecactly same time, so I dont think its a broker related issue.

regards

Reiner


@rwieden

rwieden
16 Sep 2017, 22:53 ( Updated at: 21 Dec 2023, 09:20 )

RE:

tradermatrix said:

hi

c is because of this sentence:
you automatically close a  _End_hour
this sentence should be deleted

  protected override void OnTick()
        {
            if (Trade.IsExecuting)
                return;

            //Local declaration
            TriState _Close_Position = new TriState();
            TriState _Open_Long_Position = new TriState();

            //Step 1
            _Signal = i_Signal.Result.Last(0);
            _EMA2 = i_EMA2.Result.Last(0);
            _Daily_EMA50 = i_Daily_EMA50.Result.Last(0);

            //Step 2
            if (!IsTime(_Start_hour, _End_hour, 0, 0))
                _Close_Position = _ClosePosition(1, Symbol.Code, 0);

look you always close at 20h

SymbolOpening DirectionClosing Time (UTC+2)Entry PriceClosing PriceClosing QuantityDID209784513GBPUSDBuy14.09.17 20:231,340151,34005DID209784545GBPUSDBuy14.09.17 20:231,340131,34009DID209784578GBPUSDBuy14.09.17 20:231,340161,34009DID209784589GBPUSDBuy14.09.17 20:231,340161,34009DID209784599GBPUSDBuy14.09.17 20:231,340161,34011DID209784604GBPUSDBuy14.09.17 20:231,340111,34004DID209784612GBPUSDBuy14.09.17 20:231,34011,34004DID209784693GBPUSDBuy14.09.17 20:231,34011,34009DID209784700GBPUSDBuy14.09.17 20:231,340151,34008DID209784718GBPUSDBuy14.09.17 20:231,340151,34008DID209784727GBPUSDBuy14.09.17 20:231,340151,34008DID209784733GBPUSDBuy14.09.17 20:231,340151,34008DID209784764GBPUSDBuy14.09.17 20:231,340161,34009DID209784781GBPUSDBuy14.09.17 20:231,340111,34006DID209784803GBPUSDBuy14.09.17 20:231,34011,34005DID209784838GBPUSDBuy14.09.17 20:231,340111,34005DID209784848GBPUSDBuy14.09.17 20:231,34011,34006DID209784858GBPUSDBuy14.09.17 20:231,340121,34006DID209784869GBPUSDBuy14.09.17 20:231,340111,34004DID209784885GBPUSDBuy14.09.17 20:231,340111,34005DID209784889GBPUSDBuy14.09.17 20:231,34011,34004

Thanks Tradermatrix,

but the current setup should also not allow to create buy order at the same time which system nevertheless did, see below how I disgned this. Do I need to create a separate node for closing the position ?

 

regards

 

Reiner

 


@rwieden

rwieden
15 Sep 2017, 17:41

RE:

Spotware said:

Dear Reiner,

Thanks for your post. Could you please share the code that results in this behavior so that we can advise further?

Best Regards,

cTrader Team

Dear cTrade Team,

please find below the code

//+------------------------------------------------------------------+
//+                           Code generated using FxPro Quant 2.1.4 |
//+------------------------------------------------------------------+

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


namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC)]
    public class Prototype : Robot
    {

        [Parameter("EMA2_Period", DefaultValue = 50)]
        public double _EMA2_Period { get; set; }
        [Parameter("Lot_Size", DefaultValue = 0)]
        public double _Lot_Size { get; set; }
        [Parameter("Max_Spread", DefaultValue = 2)]
        public int _Max_Spread { get; set; }
        [Parameter("Signal_Period", DefaultValue = 50)]
        public double _Signal_Period { get; set; }
        [Parameter("Take_Profit", DefaultValue = 0)]
        public double _Take_Profit { get; set; }
        [Parameter("EMA3_Period", DefaultValue = 200)]
        public double _EMA3_Period { get; set; }
        [Parameter("Stop_Loss", DefaultValue = 0)]
        public double _Stop_Loss { get; set; }
        [Parameter("EMA1_Period", DefaultValue = 20)]
        public double _EMA1_Period { get; set; }
        [Parameter("Start_hour", DefaultValue = 5)]
        public double _Start_hour { get; set; }
        [Parameter("End_hour", DefaultValue = 18)]
        public double _End_hour { get; set; }
        [Parameter("hourly_EMA_fast", DefaultValue = 20)]
        public double _hourly_EMA_fast { get; set; }
        [Parameter("hourly_EMA_slow", DefaultValue = 200)]
        public double _hourly_EMA_slow { get; set; }
        [Parameter("hourly_EMA_middle", DefaultValue = 50)]
        public double _hourly_EMA_middle { get; set; }

        //Global declaration
        private ExponentialMovingAverage i_Signal;
        private ExponentialMovingAverage i_EMA3;
        private ExponentialMovingAverage i_EMA1;
        private ExponentialMovingAverage i_EMA2;
        private ExponentialMovingAverage i_Daily_EMA200;
        private ExponentialMovingAverage i_Daily_EMA50;
        private ExponentialMovingAverage i_Daily_EMA20;
        double _Signal;
        double _EMA2;
        double _Daily_EMA50;

        DateTime LastTradeExecution = new DateTime(0);

        protected override void OnStart()
        {
            i_Signal = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_Signal_Period);
            i_EMA3 = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_EMA3_Period);
            i_EMA1 = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_EMA1_Period);
            i_EMA2 = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_EMA2_Period);
            i_Daily_EMA200 = Indicators.ExponentialMovingAverage(MarketData.GetSeries(TimeFrame.Hour).Close, (int)_hourly_EMA_slow);
            i_Daily_EMA50 = Indicators.ExponentialMovingAverage(MarketData.GetSeries(TimeFrame.Hour).Close, (int)_hourly_EMA_middle);
            i_Daily_EMA20 = Indicators.ExponentialMovingAverage(MarketData.GetSeries(TimeFrame.Hour).Close, (int)_hourly_EMA_fast);

        }

        protected override void OnTick()
        {
            if (Trade.IsExecuting)
                return;

            //Local declaration
            TriState _Close_Position = new TriState();
            TriState _Open_Long_Position = new TriState();

            //Step 1
            _Signal = i_Signal.Result.Last(0);
            _EMA2 = i_EMA2.Result.Last(0);
            _Daily_EMA50 = i_Daily_EMA50.Result.Last(0);

            //Step 2
            if (!IsTime(_Start_hour, _End_hour, 0, 0))
                _Close_Position = _ClosePosition(1, Symbol.Code, 0);

            //Step 3

            //Step 4

            //Step 5
            if (((MarketSeries.High.Last(1) < _Signal) && (MarketSeries.High.Last(0) >= _Signal) && (i_EMA1.Result.Last(0) > _EMA2) && (_EMA2 > i_EMA3.Result.Last(0)) && ((Symbol.Bid - (Symbol.Ask)) <= _Max_Spread) && IsTime(_Start_hour, _End_hour, 0, 0) && (i_Daily_EMA20.Result.Last(0) > _Daily_EMA50) && (_Daily_EMA50 > i_Daily_EMA200.Result.Last(0))))
                _Open_Long_Position = _OpenPosition(1, true, Symbol.Code, TradeType.Buy, _Lot_Size, 0, _Stop_Loss, _Take_Profit, "");

        }

        bool NoOrders(string symbolCode, double[] magicIndecies)
        {
            if (symbolCode == "")
                symbolCode = Symbol.Code;
            string[] labels = new string[magicIndecies.Length];
            for (int i = 0; i < magicIndecies.Length; i++)
            {
                labels[i] = "FxProQuant_" + magicIndecies[i].ToString("F0");
            }
            foreach (Position pos in Positions)
            {
                if (pos.SymbolCode != symbolCode)
                    continue;
                if (labels.Length == 0)
                    return false;
                foreach (var label in labels)
                {
                    if (pos.Label == label)
                        return false;
                }
            }
            foreach (PendingOrder po in PendingOrders)
            {
                if (po.SymbolCode != symbolCode)
                    continue;
                if (labels.Length == 0)
                    return false;
                foreach (var label in labels)
                {
                    if (po.Label == label)
                        return false;
                }
            }
            return true;
        }

        TriState _OpenPosition(double magicIndex, bool noOrders, string symbolCode, TradeType tradeType, double lots, double slippage, double? stopLoss, double? takeProfit, string comment)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            if (noOrders && Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)
                return new TriState();
            if (stopLoss < 1)
                stopLoss = null;
            if (takeProfit < 1)
                takeProfit = null;
            if (symbol.Digits == 5 || symbol.Digits == 3)
            {
                if (stopLoss != null)
                    stopLoss /= 10;
                if (takeProfit != null)
                    takeProfit /= 10;
                slippage /= 10;
            }
            int volume = Convert.ToInt32(lots * 100000);
            if (!ExecuteMarketOrder(tradeType, symbol, volume, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, slippage, comment).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _SendPending(double magicIndex, bool noOrders, string symbolCode, PendingOrderType poType, TradeType tradeType, double lots, int priceAction, double priceValue, double? stopLoss, double? takeProfit,
        DateTime? expiration, string comment)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            if (noOrders && PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)
                return new TriState();
            if (stopLoss < 1)
                stopLoss = null;
            if (takeProfit < 1)
                takeProfit = null;
            if (symbol.Digits == 5 || symbol.Digits == 3)
            {
                if (stopLoss != null)
                    stopLoss /= 10;
                if (takeProfit != null)
                    takeProfit /= 10;
            }
            int volume = Convert.ToInt32(lots * 100000);
            double targetPrice;
            switch (priceAction)
            {
                case 0:
                    targetPrice = priceValue;
                    break;
                case 1:
                    targetPrice = symbol.Bid - priceValue * symbol.TickSize;
                    break;
                case 2:
                    targetPrice = symbol.Bid + priceValue * symbol.TickSize;
                    break;
                case 3:
                    targetPrice = symbol.Ask - priceValue * symbol.TickSize;
                    break;
                case 4:
                    targetPrice = symbol.Ask + priceValue * symbol.TickSize;
                    break;
                default:
                    targetPrice = priceValue;
                    break;
            }
            if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))
                expiration = null;
            if (poType == PendingOrderType.Limit)
            {
                if (!PlaceLimitOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful)
                {
                    Thread.Sleep(400);
                    return false;
                }
                return true;
            }
            else if (poType == PendingOrderType.Stop)
            {
                if (!PlaceStopOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful)
                {
                    Thread.Sleep(400);
                    return false;
                }
                return true;
            }
            return new TriState();
        }

        TriState _ModifyPosition(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (pos == null)
                return new TriState();
            double? sl, tp;
            if (slValue == 0)
                sl = null;
            else
            {
                switch (slAction)
                {
                    case 0:
                        sl = pos.StopLoss;
                        break;
                    case 1:
                        if (pos.TradeType == TradeType.Buy)
                            sl = pos.EntryPrice - slValue * symbol.TickSize;
                        else
                            sl = pos.EntryPrice + slValue * symbol.TickSize;
                        break;
                    case 2:
                        sl = slValue;
                        break;
                    default:
                        sl = pos.StopLoss;
                        break;
                }
            }
            if (tpValue == 0)
                tp = null;
            else
            {
                switch (tpAction)
                {
                    case 0:
                        tp = pos.TakeProfit;
                        break;
                    case 1:
                        if (pos.TradeType == TradeType.Buy)
                            tp = pos.EntryPrice + tpValue * symbol.TickSize;
                        else
                            tp = pos.EntryPrice - tpValue * symbol.TickSize;
                        break;
                    case 2:
                        tp = tpValue;
                        break;
                    default:
                        tp = pos.TakeProfit;
                        break;
                }
            }
            if (!ModifyPosition(pos, sl, tp).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _ModifyPending(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue, int priceAction, double priceValue, int expirationAction, DateTime? expiration)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (po == null)
                return new TriState();
            double targetPrice;
            double? sl, tp;
            if (slValue == 0)
                sl = null;
            else
            {
                switch (slAction)
                {
                    case 0:
                        sl = po.StopLoss;
                        break;
                    case 1:
                        if (po.TradeType == TradeType.Buy)
                            sl = po.TargetPrice - slValue * symbol.TickSize;
                        else
                            sl = po.TargetPrice + slValue * symbol.TickSize;
                        break;
                    case 2:
                        sl = slValue;
                        break;
                    default:
                        sl = po.StopLoss;
                        break;
                }
            }
            if (tpValue == 0)
                tp = null;
            else
            {
                switch (tpAction)
                {
                    case 0:
                        tp = po.TakeProfit;
                        break;
                    case 1:
                        if (po.TradeType == TradeType.Buy)
                            tp = po.TargetPrice + tpValue * symbol.TickSize;
                        else
                            tp = po.TargetPrice - tpValue * symbol.TickSize;
                        break;
                    case 2:
                        tp = tpValue;
                        break;
                    default:
                        tp = po.TakeProfit;
                        break;
                }
            }
            switch (priceAction)
            {
                case 0:
                    targetPrice = po.TargetPrice;
                    break;
                case 1:
                    targetPrice = priceValue;
                    break;
                case 2:
                    targetPrice = po.TargetPrice + priceValue * symbol.TickSize;
                    break;
                case 3:
                    targetPrice = po.TargetPrice - priceValue * symbol.TickSize;
                    break;
                case 4:
                    targetPrice = symbol.Bid - priceValue * symbol.TickSize;
                    break;
                case 5:
                    targetPrice = symbol.Bid + priceValue * symbol.TickSize;
                    break;
                case 6:
                    targetPrice = symbol.Ask - priceValue * symbol.TickSize;
                    break;
                case 7:
                    targetPrice = symbol.Ask + priceValue * symbol.TickSize;
                    break;
                default:
                    targetPrice = po.TargetPrice;
                    break;
            }
            if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))
                expiration = null;
            if (expirationAction == 0)
                expiration = po.ExpirationTime;
            if (!ModifyPendingOrder(po, targetPrice, sl, tp, expiration).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _ClosePosition(double magicIndex, string symbolCode, double lots)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (pos == null)
                return new TriState();
            TradeResult result;
            if (lots == 0)
            {
                result = ClosePosition(pos);
            }
            else
            {
                int volume = Convert.ToInt32(lots * 100000);
                result = ClosePosition(pos, volume);
            }
            if (!result.IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        TriState _DeletePending(double magicIndex, string symbolCode)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (po == null)
                return new TriState();
            if (!CancelPendingOrder(po).IsSuccessful)
            {
                Thread.Sleep(400);
                return false;
            }
            return true;
        }

        bool _OrderStatus(double magicIndex, string symbolCode, int test)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (pos != null)
            {
                if (test == 0)
                    return true;
                if (test == 1)
                    return true;
                if (test == 3)
                    return pos.TradeType == TradeType.Buy;
                if (test == 4)
                    return pos.TradeType == TradeType.Sell;
            }
            var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);
            if (po != null)
            {
                if (test == 0)
                    return true;
                if (test == 2)
                    return true;
                if (test == 3)
                    return po.TradeType == TradeType.Buy;
                if (test == 4)
                    return po.TradeType == TradeType.Sell;
                if (test == 5)
                    return po.OrderType == PendingOrderType.Limit;
                if (test == 6)
                    return po.OrderType == PendingOrderType.Stop;
            }
            return false;
        }

        int TimeframeToInt(TimeFrame tf)
        {
            if (tf == TimeFrame.Minute)
                return 1;
            else if (tf == TimeFrame.Minute2)
                return 2;
            else if (tf == TimeFrame.Minute3)
                return 3;
            else if (tf == TimeFrame.Minute4)
                return 4;
            else if (tf == TimeFrame.Minute5)
                return 5;
            else if (tf == TimeFrame.Minute10)
                return 10;
            else if (tf == TimeFrame.Minute15)
                return 15;
            else if (tf == TimeFrame.Minute30)
                return 30;
            else if (tf == TimeFrame.Hour)
                return 60;
            else if (tf == TimeFrame.Hour4)
                return 240;
            else if (tf == TimeFrame.Daily)
                return 1440;
            else if (tf == TimeFrame.Weekly)
                return 10080;
            else if (tf == TimeFrame.Monthly)
                return 43200;
            return 1;
        }


        DateTime __currentBarTime = DateTime.MinValue;
        bool __isNewBar(bool triggerAtStart)
        {
            DateTime newTime = MarketSeries.OpenTime.LastValue;
            if (__currentBarTime != newTime)
            {
                if (!triggerAtStart && __currentBarTime == DateTime.MinValue)
                {
                    __currentBarTime = newTime;
                    return false;
                }
                __currentBarTime = newTime;
                return true;
            }
            return false;
        }


        bool IsTime(double startHourParam, double endHourParam, double startMinuteParam, double endMinuteParam)
        {
            int startHour = Convert.ToInt32(startHourParam);
            int endHour = Convert.ToInt32(endHourParam);
            int startMinute = Convert.ToInt32(startMinuteParam);
            int endMinute = Convert.ToInt32(endMinuteParam);

            if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 || startMinute < 0 || startMinute > 59 || endMinute < 0 || endMinute > 59)
                return false;

            int startTime = startHour * 60 + startMinute;
            int endTime = endHour * 60 + endMinute;
            int time = Server.Time.Hour * 60 + Server.Time.Minute;

            if (startTime < endTime)
                return (time >= startTime && time <= endTime);
            else if (startTime > endTime)
                return (time >= startTime || time <= endTime);
            else
                return (time == startTime);
        }

    }
}

public struct TriState
{
    public static readonly TriState NonExecution = new TriState(0);
    public static readonly TriState False = new TriState(-1);
    public static readonly TriState True = new TriState(1);
    sbyte value;
    TriState(int value)
    {
        this.value = (sbyte)value;
    }
    public bool IsNonExecution
    {
        get { return value == 0; }
    }
    public static implicit operator TriState(bool x)
    {
        return x ? True : False;
    }
    public static TriState operator ==(TriState x, TriState y)
    {
        if (x.value == 0 || y.value == 0)
            return NonExecution;
        return x.value == y.value ? True : False;
    }
    public static TriState operator !=(TriState x, TriState y)
    {
        if (x.value == 0 || y.value == 0)
            return NonExecution;
        return x.value != y.value ? True : False;
    }
    public static TriState operator !(TriState x)
    {
        return new TriState(-x.value);
    }
    public static TriState operator &(TriState x, TriState y)
    {
        return new TriState(x.value < y.value ? x.value : y.value);
    }
    public static TriState operator |(TriState x, TriState y)
    {
        return new TriState(x.value > y.value ? x.value : y.value);
    }
    public static bool operator true(TriState x)
    {
        return x.value > 0;
    }
    public static bool operator false(TriState x)
    {
        return x.value < 0;
    }
    public static implicit operator bool(TriState x)
    {
        return x.value > 0;
    }
    public override bool Equals(object obj)
    {
        if (!(obj is TriState))
            return false;
        return value == ((TriState)obj).value;
    }
    public override int GetHashCode()
    {
        return value;
    }
    public override string ToString()
    {
        if (value > 0)
            return "True";
        if (value < 0)
            return "False";
        return "NonExecution";
    }
}

public static class PendingEx
{
    public static PendingOrder __Find(this cAlgo.API.PendingOrders pendingOrders, string label, Symbol symbol)
    {
        foreach (PendingOrder po in pendingOrders)
        {
            if (po.SymbolCode == symbol.Code && po.Label == label)
                return po;
        }
        return null;
    }
}


@rwieden