Category Trend  Published on 12/06/2024

cTrader Supertrend & EMA cBot

Description

This starter kit for algorithmic developers includes an open-source Supertrend indicator, a technical analysis tool designed for trading to identify the direction of the prevailing market trend and generate buy or sell signals. The Supertrend indicator is particularly effective in trending markets but can generate false signals in choppy or sideways markets. Therefore, it is often used in conjunction with other indicators. The Full Source Code is included for educational purposes.

 

HOW DOES THIS STRATEGY WORK?

If you need further details on how this strategy works, visit the user guide.

 

SOURCE CODE INCLUDED

The full source code is included in the cBot for you to add new features and make any changes, it is also perfect for learning how to code your cBots.

 

 

HOW WAS THE STRATEGY CREATED?

This strategy (cBot) was created by the Algo Strategy Building Tool with no coding, you can use a simple interface to select your indicators, trades rules and risk management. 

 

NEED MODIFICATIONS?

You can contact our development team if you need to add additional indicators or features to this cBot.

If you also would like us to convert your ideas or manual strategy into an automated system, we can help

 

ClickAlgo is a leading supplier of cTrader cBots & indicators.

 

DISCLAIMER

This product is for educational use only and should not be considered financial advice. Trading and Investing Activities are Inherently Risky, and Users of Our Material Should Be Prepared to Incur Losses in Connection with Such Activities.


using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

/*
   This code was created using the Algo Strategy Building Tool by ClickAlgo Limited
   https://clickalgo.com/strategy-builder
 
   This cBot does not guarantee any particular outcome or
   profit of any kind. Use it at your own risk.

   Created: 12/06/2024
   Name: Supertrend & EMA

   The EMA and SuperTrend Combined Trend Following Strategy ingeniously combines the EMA indicator and the SuperTrend indicator to identify market trends and provide clear entry and exit signals.
*/

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class AlgoBuilderBot : Robot
    {
        // user parameter settings

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

        [Parameter("Stop loss", Group = "Protection", DefaultValue = 42)]
        public int StopLoss { get; set; }

        [Parameter("Take profit", Group = "Protection", DefaultValue = 9)]
        public int TakeProfit { get; set; }

        // Indicator settings for bullish signals

        [Parameter("Supertrend Periods", DefaultValue =  16, Group = "Supertrend Buy #1")]
        public int SupertrendPeriodsBuy1 { get; set; }
        
        [Parameter("Supertrend Multiplier", DefaultValue =  3, Group = "Supertrend Buy #1")]
        public int SupertrendMultiBuy1 { get; set; }

        [Parameter("Timeframe", DefaultValue = "h1", Group = "Bullish EMA Buy #2")]
        public TimeFrame EmaTimeFrameBuy2 { get; set; }
        
        [Parameter("EMA Periods", DefaultValue =  200, Group = "Bullish EMA Buy #2")]
        public int EmaPeriodsBuy2 { get; set; }

        // Indicator settings for bearish signals

        [Parameter("Supertrend Periods", DefaultValue =  16, Group = "Supertrend Sell #1")]
        public int SupertrendPeriodsSell1 { get; set; }
        
        [Parameter("Supertrend Multiplier", DefaultValue =  3, Group = "Supertrend Sell #1")]
        public int SupertrendMultiSell1 { get; set; }

        [Parameter("Timeframe", DefaultValue = "h1", Group = "Bearish EMA Sell #2")]
        public TimeFrame EmaTimeFrameSell2 { get; set; }
        
        [Parameter("EMA Periods", DefaultValue =  200, Group = "Bearish EMA Sell #2")]
        public int EmaPeriodsSell2 { get; set; }

        // declaring the standard bullish indicators

        private Supertrend _supertrend_Buy1;
        private ExponentialMovingAverage _ema_Buy2;

        // declaring the standard bearish indicators

        private Supertrend _supertrend_Sell1;
        private ExponentialMovingAverage _ema_Sell2;

        // declaring the market data variables for bullish signals.

        private Bars _emaBars_Buy2;

        // declaring the market data variables for bearish signals.

        private Bars _emaBars_Sell2;

        // Private fields.

        private string StrategyName { get; set; }

        // makes sure only 1 trade opens per signal
        bool IsBullish { get; set; }
        bool IsBearish { get; set; }    

        // Initialise variables when the cBot starts.

        protected override void OnStart()
        {
            StrategyName = "Supertrend & EMA";

            // constructing the market data for the bullish indicators
            _emaBars_Buy2 = MarketData.GetBars(EmaTimeFrameBuy2);

            // constructing the market data for the bearish indicators
            _emaBars_Sell2 = MarketData.GetBars(EmaTimeFrameSell2);

            // constructing the BULLISH indicators
            _supertrend_Buy1 = Indicators.Supertrend(SupertrendPeriodsBuy1, SupertrendMultiBuy1);
            _ema_Buy2 = Indicators.ExponentialMovingAverage(_emaBars_Buy2.ClosePrices, EmaPeriodsBuy2);

            // constructing the BEARISH indicators
            _supertrend_Sell1 = Indicators.Supertrend(SupertrendPeriodsSell1, SupertrendMultiSell1);
            _ema_Sell2 = Indicators.ExponentialMovingAverage(_emaBars_Sell2.ClosePrices, EmaPeriodsSell2);
        }

        // The onTick method is called on each price change.
        protected override void OnTick()
        {
          
        }

         // this method is called when the candle closes and is used to check the trade signals, execute trades and send alerts.
        protected override void OnBarClosed()
        {
            TradeRulesBullish();            
            TradeRulesBearish();
        }

        // parent method to check rules and open bullish trade or send signal.
        private void TradeRulesBullish()
        {
            // flag to open a trade if all rules true.
            bool OpenBuyTrade = false;

            if (IsBullishSignal())
            {
                OpenBuyTrade = true;
            }
 
            if (OpenBuyTrade)
            {
                if (!IsBullish)
                {
                    if (!IsTradeOpen(TradeType.Buy))
                    {
                        OpenTrade(TradeType.Buy);
                    }
                }

                IsBullish = true;
            }
            else
            {
                IsBullish = false;
            }
        }


        // parent method to check rules and open bearish trade or send signal.
        private void TradeRulesBearish()
        {
            // flag to open a trade if all rules true.
            bool OpenSellTrade = false;

           if (IsBearishSignal())
            {
                OpenSellTrade = true;
            }

            if (OpenSellTrade)
            {
                if (!IsBearish)
                {
                    if (!IsTradeOpen(TradeType.Sell))
                    {
                        OpenTrade(TradeType.Sell);
                    }
                }

                IsBearish = true;
            }
            else
            {
                IsBearish = false;
            }
        }

        // returns true if all signals are bullish
        private bool IsBullishSignal() 
        {
            if (_supertrend_Buy1.UpTrend.Last(1) !< Bars.LowPrices.Last(1) && _supertrend_Buy1.DownTrend.Last(2) !> Bars.HighPrices.Last(2))
            {
                return false;
            }

            if (Symbol.Bid < _ema_Buy2.Result.LastValue)
            {
                return false;
            }

            return true;
        }

        // returns true if all signals are bearish
        private bool IsBearishSignal() 
        {
            if (_supertrend_Sell1.DownTrend.Last(1) !> Bars.HighPrices.Last(1) && _supertrend_Sell1.UpTrend.Last(2) !< Bars.LowPrices.Last(2))
            {
                return false;
            }

            if (Symbol.Ask > _ema_Sell2.Result.LastValue)
            {
                return false;
            }

            return true;
        }

        private void OpenTrade(TradeType type)
        {
            // calculate volume from lots
            var volume = Symbol.QuantityToVolumeInUnits(Quantity);
            volume = Symbol.NormalizeVolumeInUnits(volume, RoundingMode.Down);

            ExecuteMarketOrder(type, SymbolName, volume, StrategyName, StopLoss, TakeProfit);
        }

        // returns true if buy trade is open.
        private bool IsTradeOpen(TradeType type)
        {
            var positions = Positions.FindAll(StrategyName, SymbolName, type);
            if (positions.Count() > 0)
            {
                return true;
            }
            else return false;
        }
    }
}

ClickAlgo's avatar
ClickAlgo

Joined on 05.02.2015

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: Supertrend & EMA.algo
  • Rating: 0
  • Installs: 417
  • Modified: 12/06/2024 14:30
Comments
Log in to add a comment.
No comments found.