Category Trend  Published on 19/01/2023

moving average

Description

from datetime import datetime
import backtrader as bt

# Create a subclass of Strategy to define the indicators and logic

class SmaCross(bt.Strategy):
    # list of parameters which are configurable for the strategy
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30   # period for the slow moving average
    )

    def init(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

    def next(self):
        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.buy()  # enter long

        elif self.crossover < 0:  # in the market & cross to the downside
            self.close()  # close long position


cerebro = bt.Cerebro()  # create a "Cerebro" engine instance

# Create a data feed
data = bt.feeds.YahooFinanceData(dataname='MSFT',
                                 fromdate=datetime(2011, 1, 1),
                                 todate=datetime(2012, 12, 31))

cerebro.adddata(data)  # Add the data feed

cerebro.addstrategy(SmaCross)  # Add the trading strategy
cerebro.run()  # run it all
cerebro.plot()  # and plot it with a single command


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

namespace cAlgo
{
    [Cloud("ZoneUp1", "ZoneDn1", FirstColor = "Green", SecondColor = "Red", Opacity = 0.1)]
    [Cloud("ZoneUp2", "ZoneDn2", FirstColor = "Green", SecondColor = "Red", Opacity = 0.2)]
    [Cloud("ZoneUp3", "ZoneDn3", FirstColor = "Green", SecondColor = "Red", Opacity = 0.3)]
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class mSwingArmATRtrend : Indicator
    {
        [Parameter("Trial Type (modified)", DefaultValue = enumTrialType.Modified)]
        public enumTrialType inpTrailType { get; set; }
        [Parameter("ATR Period (26)", DefaultValue = 28)]
        public int inpPeriodATR { get; set; }
        [Parameter("ATR Factor (5)", DefaultValue = 5)]
        public int inpFactorATR { get; set; }
        [Parameter("Show Fib (true)", DefaultValue = true)]
        public bool inpShowFib { get; set; }
        [Parameter("Fib Level 1 (61.8)", DefaultValue = 61.8)]
        public double inpFibLevel1 { get; set; }
        [Parameter("Fib Level 2 (78.6)", DefaultValue = 78.6)]
        public double inpFibLevel2 { get; set; }
        [Parameter("Fib Level 3 (88.6)", DefaultValue = 88.6)]
        public double inpFibLevel3 { get; set; }        

        [Output("Extremum", LineColor = "Green", PlotType = PlotType.DiscontinuousLine, LineStyle = LineStyle.Lines, Thickness = 1)]
        public IndicatorDataSeries outExtremum { get; set; }
        [Output("TrailingStop", LineColor = "Red", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outTrail { get; set; }
        [Output("Level 1", LineColor = "Silver", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outLevel1 { get; set; }
        [Output("Level 2", LineColor = "Silver", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outLevel2 { get; set; }
        [Output("Level 3", LineColor = "Silver", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outLevel3 { get; set; }
        [Output("ZoneUp1", LineColor = "Transparent", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outZoneUp1 { get; set; }
        [Output("ZoneDn1", LineColor = "Transparent", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outZoneDn1 { get; set; }
        [Output("ZoneUp2", LineColor = "Transparent", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outZoneUp2 { get; set; }
        [Output("ZoneDn2", LineColor = "Transparent", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outZoneDn2 { get; set; }
        [Output("ZoneUp3", LineColor = "Transparent", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outZoneUp3 { get; set; }
        [Output("ZoneDn3", LineColor = "Transparent", LineStyle = LineStyle.Solid, Thickness = 1)]
        public IndicatorDataSeries outZoneDn3 { get; set; }
        [Output("OpenLong trigger", LineColor = "Black", PlotType = PlotType.Points, Thickness = 3)]
        public IndicatorDataSeries outLongOpen { get; set; }
        [Output("OpenShort trigger", LineColor = "Black", PlotType = PlotType.Points, Thickness = 3)]
        public IndicatorDataSeries outShortOpen { get; set; }
        
        private MovingAverage _no, _nh, _nl, _nc;
        private IndicatorDataSeries _href, _lref, _hilo, _range, _trueRange, _wild, _loss, _rawup, _rawdn, _trendup, _trenddn, _trend, _trail, _extremum, _level1, _level2, _level3;
        private MovingAverage _smoothrange;


        protected override void Initialize()
        {
            _no = Indicators.MovingAverage(Bars.OpenPrices, 1, MovingAverageType.Simple);
            _nh = Indicators.MovingAverage(Bars.HighPrices, 1, MovingAverageType.Simple);
            _nl = Indicators.MovingAverage(Bars.LowPrices, 1, MovingAverageType.Simple);
            _nc = Indicators.MovingAverage(Bars.ClosePrices, 1, MovingAverageType.Simple);
            _href = CreateDataSeries();
            _lref = CreateDataSeries();
            _range = CreateDataSeries();
            _smoothrange = Indicators.MovingAverage(_range, inpPeriodATR, MovingAverageType.Simple);
            _hilo = CreateDataSeries();
            _trueRange = CreateDataSeries();
            _wild = CreateDataSeries();
            _loss = CreateDataSeries();
            _rawup = CreateDataSeries();
            _rawdn = CreateDataSeries();
            _trendup = CreateDataSeries();
            _trenddn = CreateDataSeries();
            _trend = CreateDataSeries();
            _trail = CreateDataSeries();
            _extremum = CreateDataSeries();
            _level1 = CreateDataSeries();
            _level2 = CreateDataSeries();
            _level3 = CreateDataSeries();
        }

        public override void Calculate(int i)
        {
            _href[i] = _nl.Result[i] <= _nh.Result[i-1] ? _nh.Result[i] - _nc.Result[i-1] : (_nh.Result[i] - _nc.Result[i-1]) - 0.5 * (_nl.Result[i] - _nh.Result[i-1]);
            _lref[i] = _nh.Result[i] >= _nl.Result[i-1] ? _nc.Result[i-1] - _nl.Result[i] : (_nc.Result[i] - _nl.Result[i-1]) - 0.5 * (_nl.Result[i-1] - _nh.Result[i]);
            _range[i] = _nh.Result[i] - _nl.Result[i];
            _hilo[i] = Math.Min(_nh.Result[i] - _nl.Result[i], 1.5 * (i>inpPeriodATR ? _smoothrange.Result[i] : _range[i]));
            _trueRange[i] = inpTrailType == enumTrialType.Modified ? Math.Max(_hilo[i], Math.Max(_href[i], _lref[i])) :
                            Math.Max(_nh.Result[i] - _nl.Result[i], Math.Max(Math.Abs(_nh.Result[i] - _nc.Result[i-1]), Math.Abs(_nl.Result[i] - _nc.Result[i-1])));
            _wild[i] = i>1 ? (_wild[i-1] + (_trueRange[i] - _wild[i-1]) / inpPeriodATR) : 0;
            _loss[i] = inpFactorATR * _wild[i];
            _rawup[i] = _nc.Result[i] - _loss[i];
            _rawdn[i] = _nc.Result[i] + _loss[i];
            
            _trendup[i] = i>1 && _nc.Result[i-1] > _trendup[i-1] ? Math.Max(_rawup[i], _trendup[i-1]) : _rawup[i];
            _trenddn[i] = i>1 && _nc.Result[i-1] < _trenddn[i-1] ? Math.Min(_rawdn[i], _trenddn[i-1]) : _rawdn[i];
            
            _trend[i] = _nc.Result[i] > _trenddn[i-1] ? +1 : _nc.Result[i] < _trendup[i-1]? -1 : (i>1 ? _trend[i-1] : +1);
            _trail[i] = _trend[i] == +1 ? _trendup[i] : _trenddn[i];

            _extremum[i] = i>1 && _trend[i-1] != +1 && _trend[i] == +1 ? _nh.Result[i]
                         : i>1 && _trend[i-1] != -1 && _trend[i] == -1 ? _nl.Result[i]
                         : i>1 && _trend[i] == +1 ? Math.Max(_extremum[i-1], _nh.Result[i])
                         : i>1 && _trend[i] == -1 ? Math.Min(_extremum[i-1], _nl.Result[i])
                         : _extremum[i-1];
            
 
            _level1[i] = _extremum[i] + (_trail[i] - _extremum[i]) * inpFibLevel1 / 100;
            _level2[i] = _extremum[i] + (_trail[i] - _extremum[i]) * inpFibLevel2 / 100;
            _level3[i] = _extremum[i] + (_trail[i] - _extremum[i]) * inpFibLevel3 / 100;
 
             outTrail[i] = _trail[i];
            outExtremum[i] = _extremum[i];
            outLevel1[i] = _level1[i];
            outLevel2[i] = _level2[i];
            outLevel3[i] = _level3[i];
            outZoneUp1[i] = _level1[i];
            outZoneDn1[i] = _level2[i];
            outZoneUp2[i] = _level2[i];
            outZoneDn2[i] = _level3[i];
            outZoneUp3[i] = _trail[i];
            outZoneDn3[i] = _level3[i];
            outLongOpen[i] = _trend[i]==+1 && Bars.ClosePrices[i] < _level1[i] ? _trail[i] : double.NaN;
            outShortOpen[i] = _trend[i]==-1 && Bars.ClosePrices[i] > _level1[i] ? _trail[i] : double.NaN;
        }
    }

    public enum enumTrialType
    {
        Modified,
        UnModified
    }
}

NI
nilesh.parmar3358

Joined on 19.01.2023

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: mSwingArmATRtrend.algo
  • Rating: 0
  • Installs: 1981
  • Modified: 19/01/2023 18:26
Comments
Log in to add a comment.
SO
sounderweaver · 1 year ago

thank you for sharing. My problem is solved drive mad