Category Trend  Published on 09/06/2020

Pivot Points (Weekly fixed)

Description

original code https://ctrader.com/algos/indicators/show/45

fixed the weekly pivots not working. can now choose between auto pivot timeframe and fixed pivot timeframe.

 

Pivot Point is a technical indicator used in technical analysis derived by calculating the numerical average of a particular stock's (or any other financial asset like forex pair or any future contract) high, low and closing prices.

On the following day, if the market price trades above the pivot point it is usually considered as a bullish sentiment, whereas if it trades below the pivot point is seen as bearish

A pivot point and the associated support and resistance levels are often turning points for the direction of price movement in a market. In an up-trending market, the pivot point and the resistance levels may represent a ceiling level in price above which the uptrend is no longer sustainable and a reversal may occur. In a declining market, a pivot point and the support levels may represent a low price level of stability or a resistance to further decline.It is customary to calculate additional levels of support and resistance, below and above the pivot point, respectively, by subtracting or adding price differentials calculated from previous trading ranges of the market.

 


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

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.EasternStandardTime, AccessRights = AccessRights.None)]
    public class PivotPoints : Indicator
    {
        private DateTime _previousPeriodStartTime;
        private int _previousPeriodStartIndex;
        private TimeFrame PivotTimeFrame;
        private VerticalAlignment vAlignment = VerticalAlignment.Top;
        private HorizontalAlignment hAlignment = HorizontalAlignment.Right;

        private Colors pivotColor = Colors.White;
        private Colors supportColor = Colors.Red;
        private Colors resistanceColor = Colors.Green;

        [Parameter("Use Custom Timeframe", DefaultValue = true)]
        public bool UseCustomTimeFrame { get; set; }

        [Parameter("Custom Timeframe", DefaultValue = "Daily")]
        public TimeFrame CustomTimeFrame { get; set; }

        [Parameter("Show Labels", DefaultValue = true)]
        public bool ShowLabels { get; set; }

        [Parameter("Pivot Color", DefaultValue = "White")]
        public string PivotColor { get; set; }

        [Parameter("Support Color", DefaultValue = "Red")]
        public string SupportColor { get; set; }

        [Parameter("Resistance Color", DefaultValue = "Green")]
        public string ResistanceColor { get; set; }

        protected override void Initialize()
        {
            if (UseCustomTimeFrame)
            {
                PivotTimeFrame = CustomTimeFrame;
            }
            else if (TimeFrame <= TimeFrame.Hour)
            {
                PivotTimeFrame = TimeFrame.Daily;
            }
            else if (TimeFrame < TimeFrame.Daily)
            {
                PivotTimeFrame = TimeFrame.Weekly;
            }
            else
            {
                PivotTimeFrame = TimeFrame.Monthly;
            }

            Enum.TryParse(PivotColor, out pivotColor);
            Enum.TryParse(SupportColor, out supportColor);
            Enum.TryParse(ResistanceColor, out resistanceColor);
        }

        private DateTime GetStartOfPeriod(DateTime dateTime)
        {
            return CutToOpenByNewYork(dateTime, PivotTimeFrame);
        }

        private DateTime GetEndOfPeriod(DateTime dateTime)
        {
            if (PivotTimeFrame == TimeFrame.Monthly)
            {
                return new DateTime(dateTime.Year, dateTime.Month, 1).AddMonths(1);
            }
            if (PivotTimeFrame == TimeFrame.Weekly)
            {
                return dateTime.AddDays(7);
            }

            return AddPeriod(CutToOpenByNewYork(dateTime, PivotTimeFrame), PivotTimeFrame);
        }

        public override void Calculate(int index)
        {
            var currentPeriodStartTime = GetStartOfPeriod(MarketSeries.OpenTime[index]);
            if (currentPeriodStartTime == _previousPeriodStartTime)
                return;

            if (index > 0)
                CalculatePivots(_previousPeriodStartTime, _previousPeriodStartIndex, currentPeriodStartTime, index);

            _previousPeriodStartTime = currentPeriodStartTime;
            _previousPeriodStartIndex = index;
        }

        private void CalculatePivots(DateTime startTime, int startIndex, DateTime startTimeOfNextPeriod, int index)
        {
            var high = MarketSeries.High[startIndex];
            var low = MarketSeries.Low[startIndex];
            var close = MarketSeries.Close[startIndex];
            var i = startIndex + 1;

            while (GetStartOfPeriod(MarketSeries.OpenTime[i]) == startTime && i < MarketSeries.Close.Count)
            {
                high = Math.Max(high, MarketSeries.High[i]);
                low = Math.Min(low, MarketSeries.Low[i]);
                close = MarketSeries.Close[i];

                i++;
            }

            var pivotStartTime = startTimeOfNextPeriod;
            var pivotEndTime = GetEndOfPeriod(startTimeOfNextPeriod);

            var pivot = (high + low + close) / 3;

            var r1 = 2 * pivot - low;
            var s1 = 2 * pivot - high;

            var r2 = pivot + high - low;
            var s2 = pivot - high + low;

            var r3 = high + 2 * (pivot - low);
            var s3 = low - 2 * (high - pivot);

            ChartObjects.DrawLine("pivot " + startIndex, pivotStartTime, pivot, pivotEndTime, pivot, Colors.White);
            ChartObjects.DrawLine("r1 " + startIndex, pivotStartTime, r1, pivotEndTime, r1, Colors.Green);
            ChartObjects.DrawLine("r2 " + startIndex, pivotStartTime, r2, pivotEndTime, r2, Colors.Green);
            ChartObjects.DrawLine("r3 " + startIndex, pivotStartTime, r3, pivotEndTime, r3, Colors.Green);
            ChartObjects.DrawLine("s1 " + startIndex, pivotStartTime, s1, pivotEndTime, s1, Colors.Red);
            ChartObjects.DrawLine("s2 " + startIndex, pivotStartTime, s2, pivotEndTime, s2, Colors.Red);
            ChartObjects.DrawLine("s3 " + startIndex, pivotStartTime, s3, pivotEndTime, s3, Colors.Red);

            if (!ShowLabels)
                return;

            ChartObjects.DrawText("Lpivot " + startIndex, "P", index, pivot, vAlignment, hAlignment, pivotColor);
            ChartObjects.DrawText("Lr1 " + startIndex, "R1", index, r1, vAlignment, hAlignment, resistanceColor);
            ChartObjects.DrawText("Lr2 " + startIndex, "R2", index, r2, vAlignment, hAlignment, resistanceColor);
            ChartObjects.DrawText("Lr3 " + startIndex, "R3", index, r3, vAlignment, hAlignment, resistanceColor);
            ChartObjects.DrawText("Ls1 " + startIndex, "S1", index, s1, vAlignment, hAlignment, supportColor);
            ChartObjects.DrawText("Ls2 " + startIndex, "S2", index, s2, vAlignment, hAlignment, supportColor);
            ChartObjects.DrawText("Ls3 " + startIndex, "S3", index, s3, vAlignment, hAlignment, supportColor);
        }

        private static DateTime CutToOpenByNewYork(DateTime date, TimeFrame timeFrame)
        {
            if (timeFrame == TimeFrame.Daily)
            {
                var hourShift = (date.Hour + 24 - 17) % 24;
                return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0, DateTimeKind.Unspecified).AddHours(-hourShift);
            }

            if (timeFrame == TimeFrame.Weekly)
                return GetStartOfTheWeek(date);

            if (timeFrame == TimeFrame.Monthly)
            {
                return new DateTime(date.Year, date.Month, 1, 0, 0, 0, DateTimeKind.Unspecified);
            }

            throw new ArgumentException(string.Format("Unknown timeframe: {0}", timeFrame), "timeFrame");
        }

        private static DateTime GetStartOfTheWeek(DateTime dateTime)
        {
            return dateTime.Date.AddDays((double)DayOfWeek.Sunday - (double)dateTime.Date.DayOfWeek).AddHours(-7);
        }

        public DateTime AddPeriod(DateTime dateTime, TimeFrame timeFrame)
        {
            if (timeFrame == TimeFrame.Daily)
            {
                return dateTime.AddDays(1);
            }
            if (timeFrame == TimeFrame.Weekly)
            {
                return dateTime.AddDays(7);
            }
            if (timeFrame == TimeFrame.Monthly)
                return dateTime.AddMonths(1);

            throw new ArgumentException(string.Format("Unknown timeframe: {0}", timeFrame), "timeFrame");
        }
    }

    //    static internal class DateTimeExtencions
    //    {
    //    }
}


2bnnp's avatar
2bnnp

Joined on 12.02.2019

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: Pivot Points (2).algo
  • Rating: 0
  • Installs: 2962
  • Modified: 13/10/2021 09:54
Comments
Log in to add a comment.
GO
goldballon5041 · 1 year ago

Im bardziej rozwija się nasza cywilizacja, tym bardziej zmieniają się różne nawykowe momenty naszego życia. Znalezienie pracowników do firmy nie jest wyjątkiem. Nie ma już standardowego poszukiwania osób, które siedzą w biurze, ludzie korzystają teraz z usług freelancerów. Jeśli potrzebujesz wysokiej jakości freelancer poland , polecam https://freelancehunt.com/pl/freelancers. Tam można znaleźć wysokiej jakości pracownika.

JE
jeremyjeremy12121 · 1 year ago

There are so many different writing services that students use. However, many of them are quality and often use plagiarized material. That's why I recommend all students to use this service https://essaywriters.org/ essay writers . In this service, you can meet only strict quality control and no plagiarism which will give you the maximum score when checking.

DA
darifull81 · 1 year ago

Shaxsan men sizga profilga kirish tavsiya qilmoqchiman. Ushbu ma'lumotlar ushbu bukmekerlik konsernida shaxsiy hisobning funksiyasi haqida tushunchani o'z ichiga oladi. O'ylaymanki, funksionallik nuqtai nazaridan, bu ofis barcha raqobatchilarni xafa qiladi. Men sizga ma'lumotni iloji boricha batafsil o'qib chiqishingizni, shuningdek, shaxsiy ma'lumotlar nima ekanligini bilib olishingizni tavsiya qilaman.

GG
ggorm709 · 1 year ago

If you want to find a platform that allows users to play quite legally, I recommend casinosnotongamstopuk.co.uk/reviews/prestige-spin-casino/. And the jurisdiction of this platform protects very well all customers who register on this site. Also thanks to this license you have quite legal protection and thus you will never get into various embarrassing situations.

kaeden.demetri's avatar
kaeden.demetri · 1 year ago

Love the script, thanks! I run a couple indicators and sit back for a perfect moment. But you need some hedge against fluctuations, and precious metals like palladium here https://www.pacificpreciousmetals.com/product/2306-any-year-1oz-canadian-palladium-maple-leaf are in a league of their own. How else would you secure your finance, any tips?

EV
evgenijpotapov999 · 1 year ago

Guys , thanks a lot

TR
triplelorenz · 2 years ago

Hi, can I use this indicator in a Cbot? I am trying to reference it and cant seem to find it when I do the custom indicator part in my Cbot ?

XXX = Indicators.GetIndicator<"Cant find it here ???">(AAA, BBB,CCC,DDD???);

I would like to add the indicator twice, once for the daily and once for the weekly pivot points. 

Thanks