Replies

maxxx2532@gmail.com
10 Mar 2020, 17:19

RE: Thank you.

PanagiotisCharalampous said:

Hi there,

See below

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

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class MacdBot : Robot
    {
        private MacdHistogram _macd;
        private Position _position;

        [Parameter(DefaultValue = 10000, MinValue = 0)]
        public int Volume { get; set; }

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

        [Parameter("Long Cycle", DefaultValue = 26)]
        public int LongCycle { get; set; }

        [Parameter("Short Cycle", DefaultValue = 12)]
        public int ShortCycle { get; set; }

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

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

        protected override void OnStart()
        {
            _macd = Indicators.MacdHistogram(LongCycle, ShortCycle, Period);
            Positions.Opened += OnPositionsOpened;
        }

        void OnPositionsOpened(PositionOpenedEventArgs obj)
        {
            _position = obj.Position;
        }

        protected override void OnBar()
        {

            bool isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
            bool isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;

            if (_macd.Histogram.LastValue > 0.0 && _macd.Signal.IsRising() && !isLongPositionOpen)
            {
                ClosePosition();
                Buy();
            }

            if (_macd.Histogram.LastValue < 0.0 && _macd.Signal.IsFalling() && !isShortPositionOpen)
            {
                ClosePosition();
                Sell();
            }
        }
        private void ClosePosition()
        {
            if (_position != null)
            {
                _position.Close();
                _position = null;
            }
        }

        private void Buy()
        {
            ExecuteMarketOrder(TradeType.Buy, Symbol.Name, Volume, "", StopLoss, TakeProfit);
        }

        private void Sell()
        {
            ExecuteMarketOrder(TradeType.Sell, Symbol.Name, Volume, "", StopLoss, TakeProfit);
        }

    }
}

 

Best Regards,

Panagiotis 

Join us on Telegram

 

 


@maxxx2532@gmail.com