Пример #1
0
 private void showKeltnerEntries()
 {
     if (PlotKeltnerEntries)
     {
         if (CrossBelow(Low, KeltnerChannel(Close, 1.25, 13).Lower[0], 1))
         {
             shortEnabled = true;
         }
         if (CrossAbove(High, KeltnerChannel(Close, 1.25, 13).Upper[0], 1))
         {
             longEnabled = true;
         }
         // short
         if (shortEnabled && trend == -1 && CrossAbove(High, SMA(13), 1))
         {
             Draw.ArrowDown(this, "short" + CurrentBar, false, 0, High[0] + TickSize, Brushes.Red);
             sendAlert(message: "Short Pullback Entry", sound: "ES_EnteringShortZone.wav");
             shortEnabled = false;
         }
         if (longEnabled && trend == 1 && CrossBelow(Low, SMA(13), 1))
         {
             Draw.ArrowUp(this, "long" + CurrentBar, false, 0, Low[0] - TickSize, Brushes.DodgerBlue);
             sendAlert(message: "Long Pullback Entry", sound: "ES_EnteringLongZone.wav");
             longEnabled = false;
         }
     }
 }
Пример #2
0
 private void ShortEntry()
 {
     if (Close[0] >= upper2 && !InTradeS)
     {
         Draw.ArrowDown(this, "SE" + CurrentBar, false, 0, High[0] + 0.25, Brushes.Red);
         EntryPriceS = Close[0];
         StopS       = EntryPriceS + 1.5;
         TargetS     = EntryPriceS - 1.5;
         InTradeS    = true;
     }
     /// stop
     if (InTradeS && Low[0] > StopS)
     {
         InTradeS = false;
         Draw.Dot(this, "shortStop" + CurrentBar, true, 0, StopS, Brushes.Red);
         LooseCountS += 1;
         DayGain     -= 75;
         GetStats(longs: false);
     }
     /// target
     if (InTradeS && High[0] < TargetS)
     {
         InTradeS = false;
         Draw.Dot(this, "LongStop" + CurrentBar, true, 0, TargetS, Brushes.Green);
         WinCountS += 1;
         DayGain   += 75;
         GetStats(longs: false);
     }
 }
Пример #3
0
        protected override void OnBarUpdate()
        {
            if (CurrentBar < 1)
            {
                return;
            }

            // Trailing stop
            double trail;
            double loss = Close[0] * ((double)Percent / 100);

            if (Close[0] > Value[1] && Close[1] > Value[1])
            {
                trail = Math.Max(Value[1], Close[0] - loss);
            }

            else if (Close[0] < Value[1] && Close[1] < Value[1])
            {
                trail = Math.Min(Value[1], Close[0] + loss);
            }

            else if (Close[0] > Value[1])
            {
                trail = Close[0] - loss;
                Draw.ArrowDown(this, CurrentBar.ToString(), false, 1, Value[1], Brushes.Orange);
            }

            else
            {
                trail = Close[0] + loss;
                Draw.ArrowUp(this, CurrentBar.ToString(), false, 1, Value[1], Brushes.Orange);
            }

            Value[0] = trail;
        }
Пример #4
0
 /// ////////////////////////////////////////////////////////////////////////////////////////////////
 ///                                     Enter Short
 /// ////////////////////////////////////////////////////////////////////////////////////////////////
 protected void enterShort(bool showStop)
 {
     if (!ShortTrades)
     {
         return;
     }
     entryOne = entryConditionsORShort();
     if (entryOne)
     {
         EnterShort(Convert.ToInt32(shares), "SE 1");
         if (showStop)
         {
             Draw.Text(this, "stop" + CurrentBar, "-", 0, theStop);
             Draw.ArrowDown(this, "entryArruw" + CurrentBar, true, 0, High[0] + (TickSize * 20), Brushes.Crimson);
         }
     }
     if (showStop)
     {
         /// show stop
         if (Position.MarketPosition == MarketPosition.Short)
         {
             Draw.Text(this, "stop" + CurrentBar, "-", 0, theStop);
         }
     }
 }
Пример #5
0
        private void showShortTrades(bool showCount, bool showMarkers)
        {
            if (tradesToday == 3)
            {
                return;
            }                                             // same results -  if ( winsToday == 2 ) {return;}
            if (!inShortTrade && shortSignal)
            {
                //Share("EcoMail", "Short NQ");
                SendMail("*****@*****.**", "Trade Alert", "Buy NQ");
                PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\OrderPending.wav");
                tradesToday++;
                shortEntryActual = shortEntryPrice;
                if (showMarkers)
                {
                    Draw.ArrowDown(this, "SE" + CurrentBar, true, 0, shortEntryActual, Brushes.Crimson);
                }
                if (showCount)
                {
                    Draw.Text(this, "sttoday" + CurrentBar, tradesToday.ToString(), 0, High[0] + 2, Brushes.Red);
                }
                inShortTrade    = true;
                barsSinceEntryS = 0;

                mpe            = 0; mae = 0;
                tradeDirection = "SE";

//				Draw.Text(this, "StopLine"+CurrentBar, "=", 0, stopPrice);
//				Draw.Text(this, "EntryLine"+CurrentBar, "-", 0, shortEntryPrice);
//				Draw.Text(this, "TargetLine"+CurrentBar, "+", 0, targetPrice);
            }

            if (inShortTrade)
            {
                var mpeNow = shortEntryActual - Low[0];
                var maeNow = High[0] - shortEntryActual;

                if (mpeNow > mpe)
                {
                    mpe = mpeNow;
                }

                if (maeNow > mae)
                {
                    mae = maeNow;
                }
            }
        }
Пример #6
0
        protected override void OnBarUpdate()
        {
            if (CurrentBar == 0)
            {
                Value[0] = 0;
            }
            else
            {
                double mean = 0;
                double sma0 = sma[0];

                for (int idx = Math.Min(CurrentBar, Period - 1); idx >= 0; idx--)
                {
                    mean += Math.Abs(Typical[idx] - sma0);
                }

                Value[0] = (Typical[0] - sma0) / (mean.ApproxCompare(0) == 0 ? 1 : (0.015 * (mean / Math.Min(Period, CurrentBar + 1))));

                // crossing down
                if (CrossBelow(CCI(Period), 180, 1))
                {
                    Draw.ArrowDown(this, "200" + CurrentBar.ToString(), true, 0, High[0] + (TickSize * 200), Brushes.Red);
                    //Print("We Crossed Below 180");
                }

                if (CrossBelow(CCI(Period), 100, 1))
                {
                    Draw.TriangleDown(this, "100" + CurrentBar.ToString(), true, 0, High[0] + (TickSize * 200), Brushes.Crimson);
                    //Print("We Crossed Below 100");
                }

                // crossing up
                if (CrossAbove(CCI(Period), -180, 1))
                {
                    Draw.ArrowUp(this, "200" + CurrentBar.ToString(), true, 0, Low[0] - (TickSize * 200), Brushes.Blue);
                    //Print("We Crossed above 180");
                }

                if (CrossAbove(CCI(Period), -100, 1))
                {
                    Draw.TriangleUp(this, "100" + CurrentBar.ToString(), true, 0, Low[0] - (TickSize * 200), Brushes.DodgerBlue);
                    //Print("We Crossed above 100");
                }
            }
        }
Пример #7
0
 /// <summary>
 ///  Short Entry Arrow
 /// </summary>
 /// <param name="inLongTrade"></param>
 public void showShortEntryArrow(bool inShortTrade)
 {
     if (inShortTrade)
     {
         return;
     }
     if (entry.shortEntryPrice == null)
     {
         return;
     }
     if (High[0] > entry.shortEntryPrice && Low[0] < entry.shortEntryPrice)
     {
         //Draw.Text(this, "SE"+CurrentBar.ToString(), "SE", 0, entry.shortEntryPrice + (TickSize * 10), Brushes.Crimson);
         ArrowDown myArrowDn = Draw.ArrowDown(this, "SEmade" + CurrentBar.ToString(), true, 0, entry.shortEntryPrice + (TickSize * 5), Brushes.Red);
         signals[0]        = -1;
         secondPivStopFlag = false;
     }
 }
Пример #8
0
 private void setPSS()
 {
     if (!Shorts)
     {
         return;
     }
     /// setup
     if ((High[0] > High[1] || Low[0] > Low[1]) && trend <= 0)
     {
         hhCount += 1;
         if (trend <= 0 && showCount)
         {
             Draw.Text(this, "HH" + CurrentBar, hhCount.ToString(), 0, Low[0] - 1 * TickSize, Brushes.Red);
         }
         if (showTradeApproaching && hhCount >= 3 && trend <= 0)
         {
             RemoveDrawObject("shortClose" + lastBar);
             Draw.TriangleDown(this, "shortClose" + CurrentBar, true, 0, High[0], Brushes.Gray);
             sendAlert(message: "Setting Up Sell on " + name, sound: AlertPSS);
         }
     }
     /// entry
     if (!inTradeShort && !inTradeLong && Low[0] < Low[1])
     {
         if (hhCount >= 3 && trend <= 0)
         {
             hhCount = 0;
             llCount = 0;
             Draw.ArrowDown(this, "PSSb" + CurrentBar, false, 0, High[0] + 1 * TickSize, Brushes.Crimson);
             tradeCount     += 1;
             entryPriceS     = Low[1];
             inTradeShort    = true;
             targetPriceS    = entryPriceS - (targetTicks * TickSize);
             stopPriceS      = entryPriceS + (stopTicks * TickSize);
             breakevenPriceS = entryPriceS - (breakEvenTicks * TickSize);
             if (deBug)
             {
                 Print("Short Entry " + entryPriceS + " \tTarget " + targetPriceS + " \tStop " + stopPriceS);
             }
             sendAlert(message: "Sell " + name, sound: AlertApproach);
         }
     }
 }
Пример #9
0
 private void enterShort()
 {
     if (ToTime(Time[0]) < ToTime(StartTime) || ToTime(Time[0]) > ToTime(EndTime))
     {
         return;
     }
     if ((inShort || !CalcStats) && !systemOff)
     {
         return;
     }
     if (Close[0] < Open[0])
     {
         Draw.ArrowDown(this, "SE" + CurrentBar, false, 0, High[0] + (TickSize * 3), Brushes.Red);
         inShort          = true;
         shortEntryPrice  = Close[0];
         shortEntryBar    = CurrentBar;
         shortTradeCount += 1;
     }
 }
Пример #10
0
        protected override void OnBarUpdate()
        {
            double fastMa = EMA(34)[0];
            double medMa  = EMA(68)[0];
            double slowMa = SMA(116)[0];

            /// Long
            if (CrossAbove(EMA(34), EMA(68), 1) && Close[0] >= slowMa)
            {
                Draw.ArrowUp(this, "xUP" + CurrentBar.ToString(), true, 1, Close[0], Brushes.LimeGreen);
            }
            /// Short
            if (CrossBelow(EMA(34), EMA(68), 1) && Close[0] <= slowMa)
            {
                Draw.ArrowDown(this, "xDN" + CurrentBar.ToString(), true, 1, Close[0], Brushes.Red);
            }

            Values[0][0] = fastMa;
            Values[1][0] = medMa;
            Values[2][0] = slowMa;
        }
Пример #11
0
        protected override void OnBarUpdate()
        {
            if (CurrentBars[0] < 20)
            {
                return;
            }

            // set bands
            int    VwmaAverage  = 42;
            int    RangeLength  = 100;
            int    SmoothLength = 100;
            int    bandOne      = 2;
            double bandTwo      = 3.5;

            double sma0         = VWMA(Close, VwmaAverage)[0];
            double smoothRange  = SMA(ATR(RangeLength), SmoothLength)[0];
            double upperBandOne = sma0 + (smoothRange * bandOne);
            double upperBandTwo = sma0 + (smoothRange * bandTwo);
            double lowerBandOne = sma0 - (smoothRange * bandOne);
            double lowerBandTwo = sma0 - (smoothRange * bandTwo);



            // Set Short Signal
            if ((High[0] >= upperBandOne))              //&& (Close[0] < Open[0]))
            {
                //BarBrush = Brushes.Crimson;
                Draw.ArrowDown(this, @"Forex4Hr Arrow down" + CurrentBar.ToString(), true, 0, High[0] + 0.0001, Brushes.Red);
            }

            // Set Long Signal
            if ((Low[0] <= lowerBandOne))              // && (Close[0] > Open[0]))
            {
                //BarBrush = Brushes.Crimson;
                Draw.ArrowUp(this, @"Forex4Hr Arrow Up" + CurrentBar.ToString(), true, 0, Low[0] - 0.0001, Brushes.Lime);
            }
        }
Пример #12
0
        protected override void OnBarUpdate()
        {
            if (CurrentBars[0] < 20)
            {
                return;
            }

            // set up higher time frame
            foreach (int CurrentBarI in CurrentBars)
            {
                if (CurrentBarI < BarsRequiredToPlot)
                {
                    return;
                }
            }

            // day bars
            if (BarsInProgress == 1)
            {
                UTFst = TSSuperTrend(SuperTrendMode.ATR, MovingAverageType.HMA, 14, 2.2, 14, false, false, false, false)[0];
                return;
            }

            // lower time frame bars
            if (BarsInProgress == 0)
            {
                // set bands
                int    VwmaAverage  = 42;
                int    RangeLength  = 100;
                int    SmoothLength = 100;
                int    bandOne      = 2;
                double bandTwo      = 3.5;

                double sma0         = VWMA(Close, VwmaAverage)[0];
                double smoothRange  = SMA(ATR(RangeLength), SmoothLength)[0];
                double upperBandOne = sma0 + (smoothRange * bandOne);
                double upperBandTwo = sma0 + (smoothRange * bandTwo);
                double lowerBandOne = sma0 - (smoothRange * bandOne);
                double lowerBandTwo = sma0 - (smoothRange * bandTwo);

                // plot ltf activity
                // set long signal form HTF
                if (Close[0] > UTFst && UTFst > 0)
                {
                    UTFdir = 1;
                    Draw.TriangleUp(this, @"HTF Up" + CurrentBar.ToString(), true, 0, UTFst - TickSize, Brushes.DodgerBlue);
                }
                else
                {
                    UTFdir = 0;
                    if (UTFst > 0)
                    {
                        Draw.TriangleDown(this, @"HTF dn " + CurrentBar.ToString(), true, 0, UTFst + TickSize, Brushes.Crimson);
                    }
                }

                // Set Long Signal
                if ((Low[0] <= lowerBandOne) && (UTFdir == 1))
                {
                    Draw.ArrowUp(this, @"lin reg long" + CurrentBar.ToString(), true, 0, Low[0] - 0.0001, Brushes.Lime);
                }

                // Set Short Signal from lin reg
                if ((High[0] >= upperBandOne) && (UTFdir == 0))
                {
                    Draw.ArrowDown(this, @"lin reg short" + CurrentBar.ToString(), true, 0, High[0] + 0.0001, Brushes.Red);
                }

                return;
            }
        }
Пример #13
0
        protected override void OnBarUpdate()
        {
            //******************************************		Swing Low - Higher Low	************************************************
            if (CurrentBar > strength + 1)
            {
                if (Swing(Low, 3).SwingLow[0] == Low[strength + 1])
                {
                    //DrawDot( "swingL" + CurrentBar, true, strength + 1, Low[strength + 1] , Color.Lime );
                    // update bar array
                    pivLowBar[2] = pivLowBar[1];
                    pivLowBar[1] = pivLowBar[0];
                    pivLowBar[0] = CurrentBar - (strength + 1);
                    //update price array
                    pivLowPrice[2] = pivLowPrice[1];
                    pivLowPrice[1] = pivLowPrice[0];
                    pivLowPrice[0] = Low[strength + 1];

                    // mark Higher pivot Low
                    if (pivLowPrice[0] > pivLowPrice[1])
                    {
                        if (HPL_Counter == 0)
                        {
                            Draw.Dot(this, "swingL" + CurrentBar.ToString(), true, strength + 1, Low[strength + 1] - TickSize, Brushes.LimeGreen);
                        }
                        HPL_Counter = HPL_Counter + 1;
                        //LPH_Counter = 0;
                        //if( HPL_Counter > 2 )
                        //	DrawText("hplc"+CurrentBar, HPL_Counter.ToString(),0, pivLowPrice[0]-TickSize , Color.Lime);
                        if (HPL_Counter == 2)
                        {
                            // DrawArrowUp("hpl"+CurrentBar, 0, pivLowPrice[0]-TickSize, Color.Lime);
                            ArrowUp myArrow = Draw.ArrowUp(this, "hpl" + CurrentBar.ToString(), true, 0, pivLowPrice[0] - TickSize, Brushes.LimeGreen);
                            myArrow.OutlineBrush = Brushes.Green;
                            //DrawText("hplc"+CurrentBar, "_____",2, pivLowPrice[0] , Color.Lime);
                            Draw.Text(this, "hplc" + CurrentBar.ToString(), "_____", 2, pivLowPrice[0], Brushes.Green);
                        }
                        //DrawLine( "BotLine"+CurrentBar,  pivLowBar[0]+(strength+1) - pivLowBar[1], pivLowPrice[1],
                        //strength+1, pivLowPrice[0], Color.Green);
                    }
                    if (pivLowPrice[0] < pivLowPrice[1])
                    {
                        HPL_Counter = 0;
                    }
                }
            }

            //******************************************		Swing High - Lower High	************************************************
            if (CurrentBar > strength + 1)
            {
                if (Swing(High, 3).SwingHigh[0] == High[strength + 1])
                {
                    // Update Bar Array
                    pivHighBar[2] = pivHighBar[1];
                    pivHighBar[1] = pivHighBar[0];
                    pivHighBar[0] = CurrentBar - (strength + 1);
                    // update price array
                    pivHighPrice[2] = pivHighPrice[1];
                    pivHighPrice[1] = pivHighPrice[0];
                    pivHighPrice[0] = High[strength + 1];
                    // mark Lower pivot High -- Top
                    if (pivHighPrice[0] < pivHighPrice[1])                              //
                    {
                        if (LPH_Counter == 0)
                        {
                            Draw.Dot(this, "swingH" + CurrentBar.ToString(), true, strength + 1, High[strength + 1] + TickSize, Brushes.Crimson);
                        }
                        LPH_Counter = LPH_Counter + 1;
                        //HPL_Counter = 0;
                        //if( LPH_Counter > 2 )
                        //	DrawText("lphc"+CurrentBar, LPH_Counter.ToString(), strength+1, pivHighPrice[0]+TickSize , Color.Red);
                        if (LPH_Counter == 2)
                        {
                            //DrawArrowDown("lph"+CurrentBar, 0, pivHighPrice[0]+TickSize, Color.Red);
                            ArrowDown myArrowDn = Draw.ArrowDown(this, "lph" + CurrentBar.ToString(), true, 0, pivHighPrice[0] + TickSize, Brushes.Crimson);
                            myArrowDn.OutlineBrush = Brushes.Red;
                            //DrawText("lphc"+CurrentBar, "_____", 2, pivHighPrice[0] , Color.Red);
                            Draw.Text(this, "lphc" + CurrentBar.ToString(), "_____", 2, pivHighPrice[0], Brushes.Red);
                        }
                        //DrawLine( "TopLine"+CurrentBar,  pivHighBar[0]+(strength+1) - pivHighBar[1], pivHighPrice[1],
                        //strength+1, pivHighPrice[0], Color.DarkRed);
                    }
                    if (pivHighPrice[0] > pivHighPrice[1])
                    {
                        LPH_Counter = 0;
                    }
                }
            }
        }
Пример #14
0
        protected override void OnBarUpdate()
        {
            // Limit Historical processing in case a chart uses too many bars for calculation (I.E. EURUSD Renko charts)
            if (State == State.Historical && LimitHistory && CurrentBar < Bars.Count - LimitHistoricalLookback)
            {
                return;
            }

            //DETERMINE LOCATION OF LAST UP/DOWN TREND LINES
            signal[0]       = 0;
            trendStarted[0] = 0;
            int upTrendOccurence = 1; int upTrendStartBarsAgo = 0; int upTrendEndBarsAgo = 0;
            int downTrendOccurence = 1; int downTrendStartBarsAgo = 0; int downTrendEndBarsAgo = 0;

            // Only calculate new autotrend line if ray hasent been put into manual mode by unlocking current ray
            if (((DrawObjects["UpTrendRay" + unique] == null) || (DrawObjects["UpTrendRay" + unique].IsLocked)) && ((DrawObjects["DownTrendRay" + unique] == null) || (DrawObjects["DownTrendRay" + unique].IsLocked)))
            {
                //Only do the following if existing ray is in auto mode
                // Calculate up trend line
                upTrendOccurence = 1;
                while (Low[upTrendEndBarsAgo] <= Low[upTrendStartBarsAgo])
                {
                    upTrendStartBarsAgo = Swing(Strength).SwingLowBar(0, upTrendOccurence + 1, CurrentBar);
                    upTrendEndBarsAgo   = Swing(Strength).SwingLowBar(0, upTrendOccurence, CurrentBar);
                    if (upTrendStartBarsAgo < 0 || upTrendEndBarsAgo < 0)
                    {
                        break;
                    }
                    upTrendOccurence++;
                }
                // Calculate down trend line
                downTrendOccurence = 1;
                while (High[downTrendEndBarsAgo] >= High[downTrendStartBarsAgo])
                {
                    downTrendStartBarsAgo = Swing(Strength).SwingHighBar(0, downTrendOccurence + 1, CurrentBar);
                    downTrendEndBarsAgo   = Swing(Strength).SwingHighBar(0, downTrendOccurence, CurrentBar);
                    if (downTrendStartBarsAgo < 0 || downTrendEndBarsAgo < 0)
                    {
                        break;
                    }
                    downTrendOccurence++;
                }
            }

            // Clear out arrows that mark trend line breaks unless ShowHistory flag is true
            if (!ShowHistory)
            {
                RemoveDrawObject("DownTrendBreak" + unique);
            }
            if (!ShowHistory)
            {
                RemoveDrawObject("UpTrendBreak" + unique);
            }

            //PROCESS UPTREND LINE IF CURRENT
            if (upTrendStartBarsAgo > 0 && upTrendEndBarsAgo > 0 && upTrendStartBarsAgo < downTrendStartBarsAgo)
            {
                RemoveDrawObject("DownTrendRay" + unique);
                double startBarPrice = Low[upTrendStartBarsAgo];
                double endBarPrice   = Low[upTrendEndBarsAgo];
                changePerBar[0] = (endBarPrice - startBarPrice) / (Math.Abs(upTrendEndBarsAgo - upTrendStartBarsAgo));
                //Test to see if this is a new trendline and increment lineCounter if so.
                if (startBarPrice != startBarPriceOld)
                {
                    direction = 1;  //Signal that we have a new uptrend and put dot on trendline where new trend detected
                    if (ShowHistory)
                    {
                        Draw.Dot(this, CurrentBar.ToString(), true, 0, startBarPrice + (upTrendStartBarsAgo * changePerBar[0]), UpTrendColor);
                        trendStarted[0] = 1;
                    }
                    lineCount       = lineCount + 1;
                    triggerBarIndex = 0;
                    //ResetAlert("Alert");
                }
                startBarPriceOld = startBarPrice;
                //
                // Draw the up trend line
                // If user has unlocked the ray use manual rays position instead of auto generated positions to track ray position
                if ((DrawObjects["UpTrendRay" + unique] != null) && (!DrawObjects["UpTrendRay" + unique].IsLocked))
                {
                    Ray upTrendRay = (Ray)DrawObjects["UpTrendRay" + unique];
                    startBarPrice       = upTrendRay.StartAnchor.Price;
                    endBarPrice         = upTrendRay.EndAnchor.Price;
                    upTrendStartBarsAgo = upTrendRay.StartAnchor.BarsAgo;
                    upTrendEndBarsAgo   = upTrendRay.EndAnchor.BarsAgo;
                    changePerBar[0]     = (endBarPrice - startBarPrice) / (Math.Abs(upTrendRay.EndAnchor.BarsAgo - upTrendRay.StartAnchor.BarsAgo));
                }
                else
                {
                    Draw.Ray(this, "UpTrendRay" + unique, false, upTrendStartBarsAgo, startBarPrice, upTrendEndBarsAgo, endBarPrice, UpTrendColor, DashStyleHelper.Solid, lineWidth);
                }

                //Draw the history line that will stay persistent on chart using lineCounter to establish a unique name
                if (ShowHistory)
                {
                    Draw.Line(this, "HistoryLine" + unique + lineCount.ToString(), false, upTrendStartBarsAgo, startBarPrice, 0, startBarPrice + (upTrendStartBarsAgo * changePerBar[0]), UpHistColor, DashStyleHelper.Solid, lineWidth);
                }
                //SET RETURN VALUES FOR INDICATOR
                // Check for an uptrend line break
                trendPrice = (startBarPrice + (upTrendStartBarsAgo * changePerBar[0]));
                for (int barsAgo = upTrendEndBarsAgo - 1; barsAgo >= 0; barsAgo--)
                {
                    if (Close[barsAgo] < endBarPrice + (Math.Abs(upTrendEndBarsAgo - barsAgo) * changePerBar[0]))
                    {
                        if (ShowHistory)
                        {
                            Draw.ArrowDown(this, "UpTrendBreak" + unique + lineCount.ToString(), true, barsAgo, High[barsAgo] + TickSize, DownTrendColor);
                        }
                        else
                        {
                            Draw.ArrowDown(this, "UpTrendBreak" + unique, true, barsAgo, High[barsAgo] + TickSize, DownTrendColor);
                        }
                        // Set the break signal only if the break is on the right most bar
                        //if (barsAgo == 0)
                        signal[barsAgo] = -1;
                        // Alert will only trigger in real-time
                        if (AlertOnBreak && triggerBarIndex == 0)
                        {
                            triggerBarIndex = CurrentBar - upTrendEndBarsAgo;
                            Alert("Alert" + unique, Priority.High, "Up trend line broken", "Alert2.wav", 100000, Brushes.Black, Brushes.Red);
                        }
                        break;
                    }
                }
            }

            else
            //DETECT AND PROCESS DOWNTREND LINE	IF CURRENT
            if (downTrendStartBarsAgo > 0 && downTrendEndBarsAgo > 0 && upTrendStartBarsAgo > downTrendStartBarsAgo)
            {
                RemoveDrawObject("UpTrendRay" + unique);
                double startBarPrice = High[downTrendStartBarsAgo];
                double endBarPrice   = High[downTrendEndBarsAgo];
                changePerBar[0] = (endBarPrice - startBarPrice) / (Math.Abs(downTrendEndBarsAgo - downTrendStartBarsAgo));
                //Test to see if this is a new trendline and increment lineCount if so.
                if (startBarPrice != startBarPriceOld)
                {
                    direction = -1;     //signl that we have a new downtrend
                    if (ShowHistory)
                    {
                        Draw.Dot(this, CurrentBar.ToString(), true, 0, startBarPrice + (downTrendStartBarsAgo * changePerBar[0]), DownTrendColor);
                        trendStarted[0] = -1;
                    }
                    lineCount       = lineCount + 1;
                    triggerBarIndex = 0;
                }
                startBarPriceOld = startBarPrice;
                //
                // Draw the down trend line
                // If user has unlocked the ray use manual rays position instead
                if ((DrawObjects["DownTrendRay" + unique] != null) && (!DrawObjects["DownTrendRay" + unique].IsLocked))
                {
                    Ray downTrendRay = (Ray)DrawObjects["DownTrendRay" + unique];
                    startBarPrice         = downTrendRay.StartAnchor.Price;
                    endBarPrice           = downTrendRay.EndAnchor.Price;
                    downTrendStartBarsAgo = downTrendRay.StartAnchor.BarsAgo;
                    downTrendEndBarsAgo   = downTrendRay.EndAnchor.BarsAgo;
                    changePerBar[0]       = (endBarPrice - startBarPrice) / (Math.Abs(downTrendRay.EndAnchor.BarsAgo - downTrendRay.StartAnchor.BarsAgo));
                }
                else
                {
                    Draw.Ray(this, "DownTrendRay" + unique, false, downTrendStartBarsAgo, startBarPrice, downTrendEndBarsAgo, endBarPrice, DownTrendColor, DashStyleHelper.Solid, lineWidth);
                }
                if (ShowHistory)
                {
                    Draw.Line(this, "HistoryLine" + unique + lineCount.ToString(), false, downTrendStartBarsAgo, startBarPrice, 0, startBarPrice + (downTrendStartBarsAgo * changePerBar[0]), DownHistColor, DashStyleHelper.Solid, lineWidth);
                }
                //SET RETURN VALUES FOR INDICATOR
                // Check for a down trend line break
                trendPrice = (startBarPrice + (downTrendStartBarsAgo * changePerBar[0]));
                for (int barsAgo = downTrendEndBarsAgo - 1; barsAgo >= 0; barsAgo--)
                {
                    //	direction=-1;
                    if (Close[barsAgo] > endBarPrice + (Math.Abs(downTrendEndBarsAgo - barsAgo) * changePerBar[0]))
                    {
                        if (ShowHistory)
                        {
                            Draw.ArrowUp(this, "DownTrendBreak" + unique + lineCount.ToString(), true, barsAgo, Low[barsAgo] - TickSize, UpTrendColor);
                        }
                        else
                        {
                            Draw.ArrowUp(this, "DownTrendBreak" + unique, true, barsAgo, Low[barsAgo] - TickSize, UpTrendColor);
                        }
                        // Set the break signal only if the break is on the right most bar
                        //if (barsAgo == 0)
                        signal[barsAgo] = 1;
                        // Alert will only trigger in real-time
                        if (AlertOnBreak && triggerBarIndex == 0)
                        {
                            triggerBarIndex = CurrentBar - downTrendEndBarsAgo;
                            Alert("Alert" + unique, Priority.High, "Down trend line broken", "Alert2.wav", 100000, Brushes.Black, Brushes.Green);
                        }
                        break;
                    }
                }
            }
        }
Пример #15
0
        protected override void OnBarUpdate()
        {
            //******************************************		Swing Low - Higher Low	************************************************
            if (CurrentBar > strength + 1)
            {
                if (Swing(Low, 3).SwingLow[0] == Low[strength + 1])
                {
                    //DrawDot( "swingL" + CurrentBar, true, strength + 1, Low[strength + 1] , Color.Lime );
                    //Draw.Dot(this, "swingLows"+ CurrentBar.ToString(), true, strength + 1, Low[strength + 1]  - TickSize, Brushes.DarkGray);
                    // update bar array
                    pivLowBar[2] = pivLowBar[1];
                    pivLowBar[1] = pivLowBar[0];
                    pivLowBar[0] = CurrentBar - (strength + 1);
                    //update price array
                    pivLowPrice[2] = pivLowPrice[1];
                    pivLowPrice[1] = pivLowPrice[0];
                    pivLowPrice[0] = Low[strength + 1];

                    // mark Higher pivot Low
                    if (pivLowPrice[0] > pivLowPrice[1])
                    {
                        //if( HPL_Counter == 0 )
                        //Draw.Dot(this, "swingL"+ CurrentBar.ToString(), true, strength + 1, Low[strength + 1]  - TickSize, Brushes.LimeGreen);
                        HPL_Counter = HPL_Counter + 1;
                        //LPH_Counter = 0;
                        if (HPL_Counter <= 2)
                        {
                            Draw.Text(this, "hplc" + CurrentBar.ToString(), "HL " + HPL_Counter.ToString(), strength + 1, pivLowPrice[0] - (TickSize * 100), Brushes.LimeGreen);
                        }
                        if (HPL_Counter == 2)
                        {
                            // DrawArrowUp("hpl"+CurrentBar, 0, pivLowPrice[0]-TickSize, Color.Lime);
                            //ArrowUp myArrow = Draw.ArrowUp(this, "hpl"+CurrentBar.ToString(), true, 0, pivLowPrice[0]-TickSize, Brushes.LimeGreen);
                            //myArrow.OutlineBrush =  Brushes.Green;
                            //DrawText("hplc"+CurrentBar, "_____",2, pivLowPrice[0] , Color.Lime);
                            //Draw.Text(this, "hplLine"+CurrentBar.ToString(), "_____", 2, pivLowPrice[0] , Brushes.Green);
                        }
                        //DrawLine( "BotLine"+CurrentBar,  pivLowBar[0]+(strength+1) - pivLowBar[1], pivLowPrice[1],
                        //strength+1, pivLowPrice[0], Color.Green);
                    }
                    if (pivLowPrice[0] < pivLowPrice[1])
                    {
                        HPL_Counter = 0;
                        HPL_Line    = false;
                    }
                }
            }

            //******************************************		Swing High - Lower High	************************************************
            if (CurrentBar > strength + 1)
            {
                if (Swing(High, 3).SwingHigh[0] == High[strength + 1])
                {
                    // Update Bar Array
                    pivHighBar[2] = pivHighBar[1];
                    pivHighBar[1] = pivHighBar[0];
                    pivHighBar[0] = CurrentBar - (strength + 1);
                    // update price array
                    pivHighPrice[2] = pivHighPrice[1];
                    pivHighPrice[1] = pivHighPrice[0];
                    pivHighPrice[0] = High[strength + 1];

                    // mark Higher High
                    if (pivHighPrice[0] > pivHighPrice[1])
                    {
                        HPH_Counter = HPH_Counter + 1;
                        if (HPH_Counter <= 2)
                        {
                            Draw.Text(this, "hphigh" + CurrentBar.ToString(), "HH " + HPH_Counter.ToString(), strength + 1, pivHighPrice[0], Brushes.LimeGreen);
                        }
                    }

                    // mark Lower pivot High -- Top
                    if (pivHighPrice[0] < pivHighPrice[1])                      //
                    {
                        HPH_Counter = 0;
                        if (LPH_Counter == 0)
                        {
                            Draw.Dot(this, "swingH" + CurrentBar.ToString(), true, strength + 1, High[strength + 1] + TickSize, Brushes.Crimson);
                        }
                        LPH_Counter = LPH_Counter + 1;

                        if (LPH_Counter == 2)
                        {
                            ArrowDown myArrowDn = Draw.ArrowDown(this, "lph" + CurrentBar.ToString(), true, 0, pivHighPrice[0] + TickSize, Brushes.Crimson);
                            myArrowDn.OutlineBrush = Brushes.Red;
                            Draw.Text(this, "lphc" + CurrentBar.ToString(), "_____", 2, pivHighPrice[0], Brushes.Red);
                        }
                    }
                    if (pivHighPrice[0] > pivHighPrice[1])
                    {
                        LPH_Counter = 0;
                    }
                }
            }

            // IF HL == 2 and HH = 1   Draw rect HH1 -> HL2
            if (pivHighBar[0] < pivLowBar[0])              // HH befor higher low
            {
                if (HPL_Counter == 2 && HPH_Counter == 1 && !HPL_Line)
                {
                    //Draw.Rectangle(this, "tag1", false, 10, Low[10] - TickSize, 5, High[5] + TickSize, Brushes.PaleGreen, Brushes.PaleGreen, 2);
                    //Draw.Rectangle(this, "goinUp"+CurrentBar.ToString(), true, CurrentBar - pivHighBar[0], pivLowPrice[0], CurrentBar - (pivLowBar[0]),pivHighPrice[0], Brushes.Green, Brushes.Green, 2);
                    Draw.Line(this, "lineUp" + CurrentBar.ToString(), true, CurrentBar - pivLowBar[1], pivLowPrice[1], strength + 1, pivLowPrice[0], Brushes.LimeGreen, DashStyleHelper.Dot, 2);
                    HPL_Line = true;
                }
            }
        }
Пример #16
0
        protected override void OnBarUpdate()
        {
            #region Ablesys Signals

            if (CurrentBars[0] < 20)
            {
                return;
            }

            // set up higher time frame
            foreach (int CurrentBarI in CurrentBars)
            {
                if (CurrentBarI < BarsRequiredToPlot)
                {
                    return;
                }
            }

            // HTF bars
            if (BarsInProgress == 1)
            {
                LowerHTF = AblesysT2(dATR, dPeriod, dRisk).Lower[0];
                UpperHTF = AblesysT2(dATR, dPeriod, dRisk).Upper[0];

                if (LowerHTF != 0)                              // short signal
                {
                    HTFdn[0] = LowerHTF;
                    HTFstate = 0;
                }
                if (UpperHTF != 0)                              // Long signal
                {
                    HTFup[0] = UpperHTF;
                    HTFstate = 1;
                }
                return;
            }

            // lower time frame bars
            if (BarsInProgress == 0)
            {
                // Ablesys trend 1
                myDataSeries[0] = (-100 * (MAX(High, Period)[0] - Close[0]) / (MAX(High, Period)[0] - MIN(Low, Period)[0] == 0 ? 1 : MAX(High, Period)[0] - MIN(Low, Period)[0]));

                if (myDataSeries[0] >= -30)
                {
                    CandleOutlineBrush = Brushes.DodgerBlue;
                    if (Open[0] < Close[0])
                    {
                        BarBrush = Brushes.Transparent;
                    }
                    else
                    {
                        BarBrush = Brushes.DodgerBlue;
                    }
                    trend[0] = 1;
                }
                else
                if (myDataSeries[0] <= -70)
                {
                    CandleOutlineBrush = Brushes.Red;
                    if (Open[0] < Close[0])
                    {
                        BarBrush = Brushes.Transparent;
                    }
                    else
                    {
                        BarBrush = Brushes.Red;
                    }
                    trend[0] = -1;
                }
                else
                {
                    CandleOutlineBrush = Brushes.ForestGreen;
                    if (Open[0] < Close[0])
                    {
                        BarBrush = Brushes.Transparent;
                    }
                    else
                    {
                        BarBrush = Brushes.Lime;
                    }
                    trend[0] = 0;
                }

                UpperLTF = AblesysT2(ATR, Period, Risk).Upper[0];
                LowerLTF = AblesysT2(ATR, Period, Risk).Lower[0];

                if (LowerLTF != 0)                  // short signal
                {
                    ATRTrailingDn[0] = LowerLTF;
                    LTFstate         = 0;
                    ATRTrailingUp.Reset();
                }
                if (UpperLTF != 0)
                {
                    ATRTrailingUp[0] = UpperLTF;                                // Long signal
                    LTFstate         = 1;
                }

                // Show MTF Confluence
                if (colorBarsAgreement)
                {
                    BarBrush           = Brushes.Lime;
                    CandleOutlineBrush = Brushes.Lime;
                    if (Close[0] > Open[0])
                    {
                        BarBrush = Brushes.Transparent;
                    }
                }

                #endregion

                #region Short Entry
                if (HTFstate == 0 && LTFstate == 0)                             // short signal
                {
                    if (colorBarsAgreement)
                    {
                        BarBrush           = Brushes.Red;
                        CandleOutlineBrush = Brushes.Red;
                        if (Close[0] > Open[0])
                        {
                            BarBrush = Brushes.Transparent;
                        }
                    }

                    /// show entry near 10 sma
                    if (enterNearMA)
                    {
                        shortFilter = maPullback(Bullish: false, BarDir: barDir);                                            // this one true
                    }
                    /// show entry near ma
                    if (enterT2)
                    {
                        shortFilter = enterNearT2(Bullish: false);
                        Print("Inside Enter T2");
                    }
                    /// show entry with T1
                    if (enterT1)
                    {
                        shortFilter = enterWithT1(Bullish: false, BarDir: barDir);
                    }


                    if (LowerLTF != 0 && shortFilter)
                    {
                        if (showTradesChart)
                        {
                            ArrowDown myArrowDn = Draw.ArrowDown(this, "Sell" + CurrentBar.ToString(), true, Time[0], High[0], Brushes.Red);
                            myArrowDn.OutlineBrush = Brushes.Black;
                        }
                        marketPosition = -1;
                        entryPrice     = Close[0];
                        numTrades     += 1;
                        entryBarNumber = CurrentBar;
                        signals[0]     = -1;
                        // set stop + target
                        origStop   = LowerLTF;
                        origTarget = Close[0] - (origStop - Close[0]);

                        // set stop + target
                        origStop     = LowerLTF;
                        stopDistance = (origStop - Close[0]);
                        // min target
                        if (stopDistance < minStopDistance)
                        {
                            stopDistance = minStopDistance;
                        }
                        origTarget = Close[0] - stopDistance;
                    }
                }
                #endregion

                #region Long Entry
                ///----- Long signal	-----
                if (HTFstate == 1 && LTFstate == 1)
                {
                    if (colorBarsAgreement)
                    {
                        BarBrush           = Brushes.DodgerBlue;
                        CandleOutlineBrush = Brushes.DodgerBlue;
                        if (Close[0] > Open[0])
                        {
                            BarBrush = Brushes.Transparent;
                        }
                    }

                    /// show entry near 10 sma
                    if (enterNearMA)
                    {
                        longFilter = maPullback(Bullish: true, BarDir: barDir);
                    }
                    /// show entry near ma
                    if (enterT2)
                    {
                        longFilter = enterNearT2(Bullish: true);
                    }
                    /// show entry with T1
                    if (enterT1)
                    {
                        longFilter = enterWithT1(Bullish: true, BarDir: barDir);
                    }

                    if (longFilter)
                    {
                        if (showTradesChart)
                        {
                            ArrowUp myArrowUp = Draw.ArrowUp(this, "Buy" + CurrentBar.ToString(), true, Time[0], Low[0], Brushes.DodgerBlue);
                            myArrowUp.OutlineBrush = Brushes.DodgerBlue;
                        }
                        marketPosition = 1;
                        entryPrice     = Close[0];
                        numTrades     += 1;
                        entryBarNumber = CurrentBar;
                        signals[0]     = 1;
                        // set stop + target
                        origStop     = UpperLTF;
                        stopDistance = (Close[0] - origStop);
                        // min target
                        if (stopDistance < minStopDistance)
                        {
                            stopDistance = minStopDistance;
                        }

                        origTarget = Close[0] + stopDistance;
                    }
                }
                #endregion

                #region Long Exits
                // show orig stop and tgt
                if (showTradesChart && marketPosition != 0 && useAtrTraget)
                {
                    Draw.Text(this, "stop" + CurrentBar.ToString(), "-", 0, origStop, Brushes.Red);
                    Draw.Text(this, "tgt" + CurrentBar.ToString(), "-", 0, origTarget, Brushes.Green);
                }

                //---- show LX at close < atr stop[1]
                if (useAtrStop && marketPosition == 1 && Close[0] < AblesysT2(ATR, Period, Risk).Upper[1] && CurrentBar > entryBarNumber)
                {
                    marketPosition = 0;
                    if (showTradesChart)
                    {
                        Dot myDot = Draw.Dot(this, "LX" + CurrentBar.ToString(), true, 0, Low[0] - TickSize, Brushes.Blue);
                    }
                    exitPrice       = Close[0];
                    exitBarNumber   = CurrentBar;
                    tradeProfitLoss = profitLossCalc(longEntry: true);
                    RecordResults(onChart: showTradesChart, showLog: showTradesLog);
                    signals[0] = 2;
                }

                // useAtrTraget Long
                if (useAtrTraget)
                {
                    if (marketPosition == 1 && CurrentBar > entryBarNumber)
                    {
                        // target hit
                        if (High[0] >= origTarget)
                        {
                            if (showTradesChart)
                            {
                                Dot myDot = Draw.Dot(this, "LX" + CurrentBar.ToString(), true, 0, origTarget, Brushes.DodgerBlue);
                            }
                            exitPrice       = origTarget;
                            marketPosition  = 0;
                            exitBarNumber   = CurrentBar;
                            tradeProfitLoss = profitLossCalc(longEntry: true);
                            signals[0]      = 2;
                        }

                        // stop hit
                        if (Close[0] < origStop)
                        {
                            if (showTradesChart)
                            {
                                Dot myDot = Draw.Dot(this, "LX" + CurrentBar.ToString(), true, 0, origStop, Brushes.DodgerBlue);
                            }
                            exitPrice       = Close[0];
                            marketPosition  = 0;
                            exitBarNumber   = CurrentBar;
                            tradeProfitLoss = profitLossCalc(longEntry: true);
                            signals[0]      = 2;
                        }
                        RecordResults(onChart: showTradesChart, showLog: showTradesLog);
                    }
                }


                #endregion

                #region Short Exits
                // show SX at close > atr stop[1]
                if (useAtrStop && marketPosition == -1 && Close[0] > AblesysT2(ATR, Period, Risk).Lower[1] && CurrentBar > entryBarNumber)
                {
                    marketPosition = 0;
                    if (showTradesChart)
                    {
                        Dot myDot = Draw.Dot(this, "SX" + CurrentBar.ToString(), true, 0, High[0] + TickSize, Brushes.Red);
                    }
                    exitPrice       = Close[0];
                    tradeProfitLoss = profitLossCalc(longEntry: false);
                    RecordResults(onChart: showTradesChart, showLog: showTradesLog);
                    exitBarNumber = CurrentBar;
                    signals[0]    = -2;
                }

                // useAtrTraget Short
                if (useAtrTraget && marketPosition == -1 && CurrentBar > entryBarNumber)
                {
                    // target hit
                    if (Low[0] <= origTarget)
                    {
                        if (showTradesChart)
                        {
                            Dot myDot = Draw.Dot(this, "SX" + CurrentBar.ToString(), true, 0, origTarget, Brushes.Red);
                        }
                        exitPrice       = origTarget;
                        marketPosition  = 0;
                        exitBarNumber   = CurrentBar;
                        tradeProfitLoss = profitLossCalc(longEntry: false);
                        signals[0]      = -2;
                    }

                    // stop hit
                    if (Close[0] > origStop)
                    {
                        if (showTradesChart)
                        {
                            Dot myDot = Draw.Dot(this, "SX" + CurrentBar.ToString(), true, 0, origStop, Brushes.Red);
                        }
                        exitPrice       = Close[0];
                        marketPosition  = 0;
                        exitBarNumber   = CurrentBar;
                        tradeProfitLoss = profitLossCalc(longEntry: false);
                        signals[0]      = -2;
                    }

                    RecordResults(onChart: showTradesChart, showLog: showTradesLog);
                }
            }
            #endregion
        }
Пример #17
0
        public void Start(int barsAgo, bool justCurrentCandleSignal)
        {
            if (starting)
            {
                low  = pb.Input[0];
                high = pb.Input[0];

                isFirstLowValue  = true;
                isFirstHighValue = true;

                currentLowTagNamePb  = "0";
                currentHighTagNamePb = "1";

                starting = false;
            }

            if (pb.IsFirstTickOfBar)
            {
                pb.RemoveDrawObject(@"Arrow down");
                pb.RemoveDrawObject(@"Arrow up");
                pb.RemoveDrawObject(@"Fall Dot");
                pb.RemoveDrawObject(@"Rise Dot");
            }

            //Calculation
            isFalling = pb.Close[barsAgo] < pb.Close[barsAgo + 1];
            isRising  = pb.Close[barsAgo] > pb.Close[barsAgo + 1];

            isOverLowPipDiff  = pb.Close[barsAgo] <= (high - (pb.PipDiff * (pb.TickSize * 10)));
            isOverHighPipDiff = pb.Close[barsAgo] >= (low + (pb.PipDiff * (pb.TickSize * 10)));

            // Add low
            if (isFirstLowValue && isFalling && isOverLowPipDiff)
            {
                low       = pb.Close[barsAgo];
                lastPrice = low;
                lastTop   = high;

                // Show fibo signals
                if (fiboCalc(high, lastBottom, lastPrice, -1) < pb.MaxFiboPercent &&
                    fiboCalc(high, lastBottom, lastPrice, -1) > pb.MinFiboPercent)
                {
                    pb.Value[barsAgo] = 1;
                    if (!justCurrentCandleSignal)
                    {
                        currentLowTagNamePb = @"Arrow up " + pb.Time[barsAgo].ToString();
                        Draw.ArrowUp(pb, currentLowTagNamePb, false, barsAgo, pb.Close[barsAgo] - (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotUpColor);
                    }
                    else
                    {
                        Draw.ArrowUp(pb, @"Arrow up", false, barsAgo, pb.Close[barsAgo] - (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotUpColor);
                    }
                }

                // Show zigzag points
                if (pb.ShowTopBottomPoints)
                {
                    if (!justCurrentCandleSignal)
                    {
                        currentLowTagNameZz = @"Fall Dot " + pb.Time[barsAgo].ToString();
                        Draw.Dot(pb, currentLowTagNameZz, false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotDownColor);
                    }
                    else
                    {
                        Draw.Dot(pb, @"Fall Dot", false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotDownColor);
                    }
                }

                isFirstLowValue  = false;
                isFirstHighValue = true;
                return;
            }
            // Add high
            else if (isFirstHighValue && isRising && isOverHighPipDiff)
            {
                high       = pb.Close[barsAgo];
                lastPrice  = high;
                lastBottom = low;

                // Show fibo signals
                if (fiboCalc(lastTop, low, lastPrice, 1) < pb.MaxFiboPercent &&
                    fiboCalc(lastTop, low, lastPrice, 1) > pb.MinFiboPercent)
                {
                    pb.Value[barsAgo] = -1;
                    if (!justCurrentCandleSignal)
                    {
                        currentHighTagNamePb = @"Arrow down " + pb.Time[barsAgo].ToString();
                        Draw.ArrowDown(pb, currentHighTagNamePb, false, barsAgo, pb.Close[barsAgo] + (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotDownColor);
                    }
                    else
                    {
                        Draw.ArrowDown(pb, @"Arrow down", false, barsAgo, pb.Close[barsAgo] + (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotDownColor);
                    }
                }

                // Show zigzag points
                if (pb.ShowTopBottomPoints)
                {
                    if (!justCurrentCandleSignal)
                    {
                        currentHighTagNameZz = @"Rise Dot " + pb.Time[barsAgo].ToString();
                        Draw.Dot(pb, currentHighTagNameZz, false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotUpColor);
                    }
                    else
                    {
                        Draw.Dot(pb, @"Rise Dot", false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotUpColor);
                    }
                }

                isFirstHighValue = false;
                isFirstLowValue  = true;
                return;
            }
            // Update low
            if (!isFirstLowValue && isFalling && isOverLowPipDiff && pb.Close[barsAgo] < lastPrice)
            {
                low       = pb.Close[barsAgo];
                lastPrice = low;

                // Show fibo signals
                if (fiboCalc(high, lastBottom, lastPrice, -1) < pb.MaxFiboPercent &&
                    fiboCalc(high, lastBottom, lastPrice, -1) > pb.MinFiboPercent)
                {
                    pb.Value[barsAgo] = 1;
                    if (!justCurrentCandleSignal)
                    {
                        Draw.ArrowUp(pb, currentLowTagNamePb, false, barsAgo, pb.Close[barsAgo] - (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotUpColor);
                    }
                    else
                    {
                        Draw.ArrowUp(pb, @"Arrow up", false, barsAgo, pb.Close[barsAgo] - (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotUpColor);
                    }
                }

                // Show zigzag points
                if (pb.ShowTopBottomPoints)
                {
                    if (!justCurrentCandleSignal)
                    {
                        Draw.Dot(pb, currentLowTagNameZz, false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotDownColor);
                    }
                    else
                    {
                        Draw.Dot(pb, @"Fall Dot", false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotDownColor);
                    }
                }
            }
            // Update high
            else if (!isFirstHighValue && isRising && isOverHighPipDiff && pb.Close[barsAgo] > lastPrice)
            {
                high      = pb.Close[barsAgo];
                lastPrice = high;

                // Show fibo signals
                if (fiboCalc(lastTop, low, lastPrice, 1) < pb.MaxFiboPercent &&
                    fiboCalc(lastTop, low, lastPrice, 1) > pb.MinFiboPercent)
                {
                    pb.Value[barsAgo] = -1;
                    if (!justCurrentCandleSignal)
                    {
                        Draw.ArrowDown(pb, currentHighTagNamePb, false, barsAgo, pb.Close[barsAgo] + (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotDownColor);
                    }
                    else
                    {
                        Draw.ArrowDown(pb, @"Arrow down", false, barsAgo, pb.Close[barsAgo] + (pipSpace * (pb.TickSize * 10)), pb.Arrow_DotDownColor);
                    }
                }

                // Show zigzag points
                if (pb.ShowTopBottomPoints)
                {
                    if (!justCurrentCandleSignal)
                    {
                        Draw.Dot(pb, currentHighTagNameZz, false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotUpColor);
                    }
                    else
                    {
                        Draw.Dot(pb, @"Rise Dot", false, barsAgo, pb.Close[barsAgo], pb.Arrow_DotUpColor);
                    }
                }
            }
        }
Пример #18
0
        protected override void OnBarUpdate()
        {
            /*
             * --print spy strength
             * -- print local strength
             * --print combined level
             *
             * --calc rsi
             * --plot rsi
             *
             * --color lines of rsi
             *
             * --show arrow entries on chart
             * show square exits on char
             * calc P&L on upper left of chart
             *
             * AAPL, MSFT, AMZN, JNJ, GOOG
             * XLY, XLP, XLE, XLF, XLV, XLI, XLB, XLRE, XLK, XLU
             *
             * mixed results accross the board
             */
            if (CurrentBars[0] < 20)
            {
                return;
            }

            // set up higher time frame
            foreach (int CurrentBarI in CurrentBars)
            {
                if (CurrentBarI < BarsRequiredToPlot)
                {
                    return;
                }
            }

            // -- trend of Spy and local chart
            if (BarsInProgress == 1)                            //SPY Bars
            {
                fastSpy = SMA(FastMA)[0];
                slowSpy = SMA(SlowMA)[0];

                if (fastSpy > slowSpy)
                {
                    stateOfSpy = 1;

                    if (Close[0] > fastSpy)
                    {
                        stateOfSpy = 2;
                    }
                }

                if (fastSpy < slowSpy)
                {
                    stateOfSpy = -1;

                    if (Close[0] < fastSpy)
                    {
                        stateOfSpy = -2;
                    }
                }
            }

            if (BarsInProgress == 0)                            //Chart tf Bars
            {
                fast = SMA(FastMA)[0];
                slow = SMA(SlowMA)[0];

                if (fast > slow)
                {
                    stateOfLocal = 1;
                    //Print(stateOfLocal);

                    if (Close[0] > fast)
                    {
                        stateOfLocal = 2;
                        //Print(stateOfLocal);
                    }
                }

                if (fast < slow)
                {
                    stateOfLocal = -1;
                    //Print(stateOfLocal);

                    if (Close[0] < fast)
                    {
                        stateOfLocal = -2;
                        //Print(stateOfLocal);
                    }
                }

                Print("Spy " + stateOfSpy + "  Local " + stateOfLocal);

                double myRSI = RSI(14, 3)[0];

                // rsi signals
                if (myRSI >= 70)
                {
                    shortRsi = true;
                }
                else
                {
                    shortRsi = false;
                }

                if (myRSI <= 30)
                {
                    longRsi = true;
                }
                else
                {
                    longRsi = false;
                }

                // -- plot rsi
                Values[0][0] = RSI(14, 3)[0];
                Values[1][0] = EMA(RSI(14, 3), 3)[0];

                // --color lines of rsi
                switch (stateOfSpy)
                {
                case 1:
                    PlotBrushes[0][0] = Brushes.DodgerBlue;
                    break;

                case 2:
                    PlotBrushes[0][0] = Brushes.DodgerBlue;
                    break;

                case -1:
                    PlotBrushes[0][0] = Brushes.Red;
                    break;

                case -2:
                    PlotBrushes[0][0] = Brushes.Red;
                    break;

                default:
                    break;
                }

                switch (stateOfLocal)
                {
                case 1:
                    PlotBrushes[1][0] = Brushes.DodgerBlue;
                    break;

                case 2:
                    PlotBrushes[1][0] = Brushes.DodgerBlue;
                    break;

                case -1:
                    PlotBrushes[1][0] = Brushes.Red;
                    break;

                case -2:
                    PlotBrushes[1][0] = Brushes.Red;
                    break;

                default:
                    break;
                }

                // Long Entries
                if (stateOfSpy > 0 && stateOfLocal > 0 && longRsi)
                {
                    ArrowUp myArrow = Draw.ArrowUp(this, "Buysig" + CurrentBar.ToString(), true, Time[0], Low[0] - (2 * TickSize), Brushes.DodgerBlue);

                    // Set the outline color of the Arrow
                    myArrow.OutlineBrush = Brushes.DodgerBlue;

//						  BarBrush = Brushes.DodgerBlue;
//						  CandleOutlineBrush = Brushes.DodgerBlue;
                }
                // Short Entries
                if (stateOfSpy < 0 && stateOfLocal < 0 && shortRsi)
                {
                    ArrowDown myArrowDn = Draw.ArrowDown(this, "Sellsig" + CurrentBar.ToString(), true, Time[0], High[0] + (2 * TickSize), Brushes.Crimson);

                    // Set the outline color of the Arrow
                    myArrowDn.OutlineBrush = Brushes.Crimson;

//						  BarBrush = Brushes.Red;
//						  CandleOutlineBrush = Brushes.Red;
                }
            }
        }
Пример #19
0
        protected override void OnBarUpdate()
        {
            if (CurrentBar < SlowMaPeriod)
            {
                return;
            }

            double fastMa = EMA(FastMaPeriod)[0];
            double slowMa = EMA(SlowMaPeriod)[0];

            FastMaPlot[0] = fastMa;
            SlowMaPlot[0] = slowMa;

            double diff = fastMa - slowMa;
            //diffSeries[0] = diff;
            //double diffMa = EMA(diffSeries, DiffMaLength)[0];

            Brush trendBrush = fastMa < slowMa ? BearishBrush : BullishBrush;

            PlotBrushes[0][0] = trendBrush;

            bool isGreenOneBack = Close[0] > Open[0];
            bool isGreenTwoBack = Close[1] > Open[1];
            bool isRedOneBack   = Close[0] < Open[0];
            bool isRedTwoBack   = Close[1] < Open[1];

            highLowSeries[0] = (High[0] - Low[0]) / TickSize;
            double tickRange      = EMA(highLowSeries, TickRangePeriod)[0];
            bool   validTickRange = tickRange > MinTickRange && tickRange < MaxTickRange;

            String alertText = String.Format("{0:C2} / {1:N2} / {2:N2}", Close[0], tickRange, diff);

            Print(String.Format("GoLong: {0}", GoLong));

            bool buy = GoLong && validTickRange && isRedTwoBack && isGreenOneBack && diff > MinMaDiff && diff < MaxMaDiff;

            if (buy)
            {
                ArrowUp buyArrow = Draw.ArrowUp(this, String.Format("buy_arrow_{0}", CurrentBar), true, 0, Low[0] - (4 * TickSize), Brushes.Yellow);

                if (FireAlerts)
                {
                    Alert(String.Format("buy_alert_{0}", CurrentBar), Priority.High, alertText,
                          NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav", 10, Brushes.Green, Brushes.White);
                }

                Signal = 1;
            }

            bool sell = GoShort && validTickRange && isGreenTwoBack && isRedOneBack && diff <-MinMaDiff && diff> -MaxMaDiff;

            if (sell)
            {
                ArrowDown sellArrow = Draw.ArrowDown(this, String.Format("sell_arrow_{0}", CurrentBar), true, 0, High[0] + (4 * TickSize), Brushes.Pink);

                if (FireAlerts)
                {
                    Alert(String.Format("sell_alert_{0}", CurrentBar), Priority.High, alertText,
                          NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav", 10, Brushes.Red, Brushes.White);
                }

                Signal = -1;
            }

            if (!buy && !sell)
            {
                Signal = 0;
            }

//			Draw.TextFixed(this, "smaDiff", String.Format("ATR: {0:N0}, SMA Diff: {1:N2}", tickRange, diff), TextPosition.TopRight,
//				ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, trendBrush, 100);
        }
Пример #20
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            if (CurrentBar < 21)               //based on logic that is used in the BW Pivot Calculations (BarsRequired)
            {
                return;
            }

            if (firsttime)
            {
                firsttime = false;

                if (displaymsg)
                {
                    if (BarsPeriods[0].Value != pricePeriod || BarsPeriod.BarsPeriodType != priceDataType)
                    {
                        Draw.TextFixed(this, "divmsg", " Adjust Price Type and Period input paratmeters to match chart's values", TextPosition.BottomLeft);
                    }
                    else
                    {
                        Draw.TextFixed(this, "divmsg", " Checking for indicator divergence with price", TextPosition.BottomLeft);
                    }
                }
            }

/* debug to view input data
 *                      if( BarsInProgress == 0 )
 *                      {
 *                              Print(" input "+BarsInProgress+" "+Input[0]+" High0 "+Highs[0][0]+" Low0 "+Lows[0][0]+" Open0 "+Opens[0][0]+" Close0 "+Closes[0][0]+" High1 "+Highs[1][0]+" Low1 "+Lows[1][0]+" Open1 "+Opens[1][0]+" Close1 "+Closes[1][0]);
 *                      }
 *                      else
 *                      {
 *                              Print(" input "+BarsInProgress+" "+Input[0]+" High "+Highs[1][0]+" Low "+Lows[1][0]+" Open "+Opens[1][0]+" Close "+Closes[1][0]);
 *                      }
 *                      return;
 */
            // only do calculations based on base bar series defined by input
            if (BarsInProgress == 0)
            {
                indicator_data = Input[0];

                // ///////////////////////////////////
                // up signal - pre swing point check
                // ///////////////////////////////////

                if (hl_mode)
                {
                    tvalue = Lows[1][0];
                }
                else
                {
                    tvalue = Closes[1][0];
                }

                if (tvalue <= (sl_price - (stoffset0 * TickSize)))
                {
                    if (indicator_data > sl_value)
                    {
                        if (barSig_mode)
                        {
                            if (Closes[1][0] >= Opens[1][0])                              // only displayes on up bars
                            {
                                Draw.ArrowUp(this, Convert.ToString(CurrentBar) + "usig", true, 0, Lows[1][0] - (sigoffset * TickSize), uparrowcolor);
                            }
                        }
                        else
                        {
                            Draw.ArrowUp(this, Convert.ToString(CurrentBar) + "usig", true, 0, Lows[1][0] - (sigoffset * TickSize), uparrowcolor);
                        }
                    }
                }

                // //////////////////////////////////////////
                // down signal down  - pre swing point check
                // //////////////////////////////////////////
                if (hl_mode)
                {
                    tvalue = Highs[1][0];
                }
                else
                {
                    tvalue = Closes[1][0];
                }

                if (tvalue >= (sh_price + (stoffset0 * TickSize)))
                {
                    if (indicator_data < sh_value)
                    {
                        if (barSig_mode)
                        {
                            if (Closes[1][0] <= Opens[1][0])                               // only displayes on down bars
                            {
                                Draw.ArrowDown(this, Convert.ToString(CurrentBar) + "dsig", true, 0, Highs[1][0] + (sigoffset * TickSize), dnarrowcolor);
                            }
                        }
                        else
                        {
                            Draw.ArrowDown(this, Convert.ToString(CurrentBar) + "dsig", true, 0, Highs[1][0] + (sigoffset * TickSize), dnarrowcolor);
                        }
                    }
                }

                // //////////////////////////////////
                // swing point calculations start here
                // //////////////////////////////////

                haveswinghigh = false;
                if (!pre_bar_swing_high)
                {
                    haveswinghigh = isHighPivot2(bbefore0, bafter0, hl_mode);
                }

                haveswinglow = false;
                if (!pre_bar_swing_low)
                {
                    haveswinglow = isLowPivot2(bbefore0, bafter0, hl_mode);
                }
                // swing point high calculations closed based
                if (haveswinghigh)
                {
                    pre_bar_swing_high = true;

                    if (hl_mode)
                    {
                        sh_price = Highs[1][bar_to_test];
                    }
                    else
                    {
                        sh_price = Closes[1][bar_to_test];
                    }

                    sh_value = Input[bar_to_test];

                    if (displayswings0)
                    {
//	debug				Print(" high at "+Highs[1][bar_to_test]);
                        Draw.Text(this, Convert.ToString(CurrentBar) + "h", false, dot, bar_to_test, Highs[1][bar_to_test] + (TickSize * swingoffset), 0, swinghighcolor, new SimpleFont("Wingdings", dotsize), TextAlignment.Center, Brushes.Transparent, Brushes.Transparent, 0);
                    }
                }
                else
                {
                    pre_bar_swing_high = false;
                }

                // swing point low calculations closed based


                if (haveswinglow)
                {
                    pre_bar_swing_low = true;


                    if (hl_mode)
                    {
                        sl_price = Lows[1][bar_to_test];
                    }
                    else
                    {
                        sl_price = Closes[1][bar_to_test];
                    }

//	debug			Print("LOW SWING "+Time[0]+" "+sl_price);

                    sl_value = Input[bar_to_test];

                    if (displayswings0)
                    {
//	debug				Print(" low at "+Lows[1][bar_to_test]);
                        Draw.Text(this, Convert.ToString(CurrentBar) + "l", false, dot, bar_to_test, Lows[1][bar_to_test] - (TickSize * swingoffset), 0, swinglowcolor, new SimpleFont("Wingdings", dotsize), TextAlignment.Center, Brushes.Transparent, Brushes.Transparent, 0);
                    }
                }
                else
                {
                    pre_bar_swing_low = false;
                }
            }             // end of base bar trigger
        }// end of onbar update
Пример #21
0
        /* --------------------------------------------------------------------------------------------------- */

        protected override void OnBarUpdate()
        {
            if ((Calculate == Calculate.OnBarClose) || IsFirstTickOfBar)
            {
                ArrowDrawn  = false;
                SoundPlayed = false;
            }

            /* ------- */

            switch (TriggerMAType)
            {
            case MAType.EMA: Trigger[0] = EMA(Input, TriggerPeriod)[0]; break;

            case MAType.HMA: Trigger[0] = HMA(Input, TriggerPeriod)[0]; break;

            case MAType.SMA: Trigger[0] = SMA(Input, TriggerPeriod)[0]; break;

            case MAType.TMA: Trigger[0] = TMA(Input, TriggerPeriod)[0]; break;

            case MAType.WMA: Trigger[0] = WMA(Input, TriggerPeriod)[0]; break;

            case MAType.DEMA: Trigger[0] = DEMA(Input, TriggerPeriod)[0]; break;

            case MAType.TEMA: Trigger[0] = TEMA(Input, TriggerPeriod)[0]; break;

            case MAType.VWMA: Trigger[0] = VWMA(Input, TriggerPeriod)[0]; break;

            case MAType.ZLEMA: Trigger[0] = ZLEMA(Input, TriggerPeriod)[0]; break;

            case MAType.LinReg: Trigger[0] = LinReg(Input, TriggerPeriod)[0]; break;
            }

            switch (AverageMAType)
            {
            case MAType.EMA: Average[0] = EMA(Trigger, AveragePeriod)[0]; break;

            case MAType.HMA: Average[0] = HMA(Trigger, AveragePeriod)[0]; break;

            case MAType.SMA: Average[0] = SMA(Trigger, AveragePeriod)[0]; break;

            case MAType.TMA: Average[0] = TMA(Trigger, AveragePeriod)[0]; break;

            case MAType.WMA: Average[0] = WMA(Trigger, AveragePeriod)[0]; break;

            case MAType.DEMA: Average[0] = DEMA(Trigger, AveragePeriod)[0]; break;

            case MAType.TEMA: Average[0] = TEMA(Trigger, AveragePeriod)[0]; break;

            case MAType.VWMA: Average[0] = VWMA(Trigger, AveragePeriod)[0]; break;

            case MAType.ZLEMA: Average[0] = ZLEMA(Trigger, AveragePeriod)[0]; break;

            case MAType.LinReg: Average[0] = LinReg(Trigger, AveragePeriod)[0]; break;
            }

            /* ------- */

            if (CurrentBar < MinBarsNeeded)
            {
                return;
            }

            /* ------- */

            if (ColorLines == ColorStyle.Transparent)
            {
                PlotBrushes[0][-Displacement] = Brushes.Transparent;
                PlotBrushes[1][-Displacement] = Brushes.Transparent;
            }

            else if (ColorLines == ColorStyle.CustomColors)
            {
                Brush TriggerColor = IsRising(Trigger) ? TriggerRisingColor : TriggerFallingColor;
                Brush AverageColor = IsRising(Average) ? AverageRisingColor : AverageFallingColor;

                if (IsBrushEqual(TriggerColor, Brushes.Transparent))
                {
                    TriggerColor = Plots[0].Brush;
                }
                if (IsBrushEqual(AverageColor, Brushes.Transparent))
                {
                    AverageColor = Plots[1].Brush;
                }

                PlotBrushes[0][-Displacement] = TriggerColor;
                PlotBrushes[1][-Displacement] = AverageColor;
            }

            /* ------- */

            if (CrossAbove(Trigger, Average, 1))
            {
                if (DrawArrows)
                {
                    Draw.ArrowUp(this, "Arrow" + CurrentBar, false, 0, Average[0] - ArrowTickOffset, ArrowUpColor);
                    ArrowDrawn = true;
                }
                if (SoundAlert && !SoundPlayed)
                {
                    PlaySound(NinjaTrader.Core.Globals.InstallDir + "\\sounds\\" + SoundFile);
                    SoundPlayed = true;
                }
            }
            else if (CrossBelow(Trigger, Average, 1))
            {
                if (DrawArrows)
                {
                    Draw.ArrowDown(this, "Arrow" + CurrentBar, false, 0, Average[0] + ArrowTickOffset, ArrowDownColor);
                    ArrowDrawn = true;
                }
                if (SoundAlert && !SoundPlayed)
                {
                    PlaySound(NinjaTrader.Core.Globals.InstallDir + "\\sounds\\" + SoundFile);
                    SoundPlayed = true;
                }
            }
            else
            {
                if (ArrowDrawn)
                {
                    RemoveDrawObject("Arrow" + CurrentBar);
                    ArrowDrawn = false;
                }
            }

            /* ------- */

            if (Trigger[0] > Average[0])
            {
                if (ColorLines == ColorStyle.RegionColors)
                {
                    PlotBrushes[0][-Displacement] = UpTrend[1] ? RegionUpColor : RegionDownColor;
                    PlotBrushes[1][-Displacement] = UpTrend[1] ? RegionUpColor : RegionDownColor;
                }
                if (ColorRegion && RegionOpacity != 0)
                {
                    if (IsFirstTickOfBar)
                    {
                        PriorIndex = StartIndex;
                    }
                    int CountBars = CurrentBar - PriorIndex + 1 - Displacement;
                    if (UpTrend[1])
                    {
                        if (StartIndex == CurrentBar)
                        {
                            RemoveDrawObject("Region" + CurrentBar);
                        }
                        if (CountBars <= CurrentBar)
                        {
                            Draw.Region(this, "Region" + PriorIndex, CountBars, -Displacement, Trigger, Average, null, RegionUpColor, RegionOpacity);
                        }
                        StartIndex = PriorIndex;
                    }
                    else
                    {
                        if (CountBars <= CurrentBar && StartIndex == PriorIndex)
                        {
                            Draw.Region(this, "Region" + PriorIndex, CountBars, 1 - Displacement, Trigger, Average, null, RegionDownColor, RegionOpacity);
                        }
                        Draw.Region(this, "Region" + CurrentBar, 1 - Displacement, -Displacement, Trigger, Average, null, RegionUpColor, RegionOpacity);
                        StartIndex = CurrentBar;
                    }
                }
                UpTrend[0] = true;
            }
            else if (Trigger[0] < Average[0])
            {
                if (ColorLines == ColorStyle.RegionColors)
                {
                    PlotBrushes[0][-Displacement] = UpTrend[1] ? RegionUpColor : RegionDownColor;
                    PlotBrushes[1][-Displacement] = UpTrend[1] ? RegionUpColor : RegionDownColor;
                }
                if (ColorRegion && RegionOpacity != 0)
                {
                    if (IsFirstTickOfBar)
                    {
                        PriorIndex = StartIndex;
                    }
                    int CountBars = CurrentBar - PriorIndex + 1 - Displacement;
                    if (!UpTrend[1])
                    {
                        if (StartIndex == CurrentBar)
                        {
                            RemoveDrawObject("Region" + CurrentBar);
                        }
                        if (CountBars <= CurrentBar)
                        {
                            Draw.Region(this, "Region" + PriorIndex, CurrentBar - PriorIndex + 1 - Displacement, -Displacement, Trigger, Average, null, RegionDownColor, RegionOpacity);
                        }
                        StartIndex = PriorIndex;
                    }
                    else
                    {
                        if (CountBars <= CurrentBar && StartIndex == PriorIndex)
                        {
                            Draw.Region(this, "Region" + PriorIndex, CurrentBar - PriorIndex + 1 - Displacement, 1 - Displacement, Trigger, Average, null, RegionUpColor, RegionOpacity);
                        }
                        Draw.Region(this, "Region" + CurrentBar, 1 - Displacement, -Displacement, Trigger, Average, null, RegionDownColor, RegionOpacity);
                        StartIndex = CurrentBar;
                    }
                }
                UpTrend[0] = false;
            }
            else
            {
                if (ColorLines == ColorStyle.RegionColors)
                {
                    PlotBrushes[0][-Displacement] = UpTrend[1] ? RegionUpColor : RegionDownColor;
                    PlotBrushes[1][-Displacement] = UpTrend[1] ? RegionUpColor : RegionDownColor;
                }
                if (ColorRegion && RegionOpacity != 0)
                {
                    if (IsFirstTickOfBar)
                    {
                        PriorIndex = StartIndex;
                    }
                    int CountBars = CurrentBar - PriorIndex + 1 - Displacement;
                    if (StartIndex == CurrentBar)
                    {
                        RemoveDrawObject("Region" + CurrentBar);
                    }
                    if (CountBars <= CurrentBar)
                    {
                        Draw.Region(this, "Region" + PriorIndex, CountBars, -Displacement, Trigger, Average, null, UpTrend[1] ? RegionUpColor : RegionDownColor, RegionOpacity);
                    }
                    StartIndex = PriorIndex;
                }
                UpTrend[0] = UpTrend[1];
            }
        }
        protected override void OnBarUpdate()
        {
            #region Indicator
            double min0 = min[0];
            nom[0] = Close[0] - min0;
            den[0] = max[0] - min0;

            if (den[0].ApproxCompare(0) == 0)
            {
                K[0] = CurrentBar == 0 ? 50 : K[1];
            }
            else
            {
                K[0] = Math.Min(100, Math.Max(0, 100 * nom[0] / den[0]));
            }

            D[0] = smaK[0];

            CrossBelowUpperThreshold[0] = CrossBelow(D, 80, 1);
            CrossAboveLowerThreshold[0] = CrossAbove(D, 20, 1);
            #endregion

            #region TrendDetection
            if (this.DetectTrends)
            {
                //DETERMINE LOCATION OF LAST UP/DOWN TREND LINES
                signal[0]          = 0;
                trendStartPrice[0] = 0;
                trendEndPrice[0]   = 0;
                int upTrendOccurence = 1; int upTrendStartBarsAgo = 0; int upTrendEndBarsAgo = 0;
                int downTrendOccurence = 1; int downTrendStartBarsAgo = 0; int downTrendEndBarsAgo = 0;

                upTrendOccurence = 1;
                //Goes until first found or reaches lookback period
                while (D[upTrendEndBarsAgo] <= D[upTrendStartBarsAgo])
                {
                    upTrendStartBarsAgo = Swing(D, Strength).SwingLowBar(0, upTrendOccurence + 1, CurrentBar);
                    upTrendEndBarsAgo   = Swing(D, Strength).SwingLowBar(0, upTrendOccurence, CurrentBar);
                    if (upTrendStartBarsAgo < 0 || upTrendEndBarsAgo < 0)
                    {
                        break;
                    }
                    upTrendOccurence++;
                }

                // Calculate down trend line
                downTrendOccurence = 1;
                while (D[downTrendEndBarsAgo] >= D[downTrendStartBarsAgo])
                {
                    downTrendStartBarsAgo = Swing(D, Strength).SwingHighBar(0, downTrendOccurence + 1, CurrentBar);
                    downTrendEndBarsAgo   = Swing(D, Strength).SwingHighBar(0, downTrendOccurence, CurrentBar);
                    if (downTrendStartBarsAgo < 0 || downTrendEndBarsAgo < 0)
                    {
                        break;
                    }
                    downTrendOccurence++;
                }

                //PROCESS UPTREND LINE IF CURRENT
                if (upTrendStartBarsAgo > 0 && upTrendEndBarsAgo > 0 && upTrendStartBarsAgo < downTrendStartBarsAgo)
                {
                    RemoveDrawObject("DownTrendRay" + unique);
                    double startBarPrice = D[upTrendStartBarsAgo];
                    double endBarPrice   = D[upTrendEndBarsAgo];
                    double changePerBar  = (endBarPrice - startBarPrice) / (Math.Abs(upTrendEndBarsAgo - upTrendStartBarsAgo));
                    //Test to see if this is a new trendline and increment lineCounter if so.
                    if (startBarPrice != startBarPriceOld)
                    {
                        direction[0] = 1;  //Signal that we have a new uptrend and put dot on trendline where new trend detected
                                           //if (ShowHistory)
                                           //{
                        Draw.Dot(this, CurrentBar.ToString(), true, 0, startBarPrice + (upTrendStartBarsAgo * changePerBar), UpTrendColor, false);
                        trendStartPrice[0] = startBarPrice;
                        trendEndPrice[0]   = endBarPrice;
                        //}
                        lineCount       = lineCount + 1;
                        triggerBarIndex = 0;
                        //ResetAlert("Alert");
                    }
                    startBarPriceOld = startBarPrice;
                    //
                    // Draw the up trend line
                    // If user has unlocked the ray use manual rays position instead of auto generated positions to track ray position
                    if ((DrawObjects["UpTrendRay" + unique] != null) && (!DrawObjects["UpTrendRay" + unique].IsLocked))
                    {
                        Ray upTrendRay = (Ray)DrawObjects["UpTrendRay" + unique];
                        startBarPrice       = upTrendRay.StartAnchor.Price;
                        endBarPrice         = upTrendRay.EndAnchor.Price;
                        upTrendStartBarsAgo = upTrendRay.StartAnchor.BarsAgo;
                        upTrendEndBarsAgo   = upTrendRay.EndAnchor.BarsAgo;
                        changePerBar        = (endBarPrice - startBarPrice) / (Math.Abs(upTrendRay.EndAnchor.BarsAgo - upTrendRay.StartAnchor.BarsAgo));
                    }
                    else
                    {
                        Draw.Ray(this, "UpTrendRay" + unique, false, upTrendStartBarsAgo, startBarPrice, upTrendEndBarsAgo, endBarPrice, UpTrendColor, DashStyleHelper.Solid, lineWidth, false);
                    }

                    //Draw the history line that will stay persistent on chart using lineCounter to establish a unique name
                    //if (ShowHistory)
                    //{
                    Draw.Line(this, "HistoryLine" + unique + lineCount.ToString(), false, upTrendStartBarsAgo, startBarPrice, 0, startBarPrice + (upTrendStartBarsAgo * changePerBar), UpHistColor, DashStyleHelper.Solid, lineWidth, false);
                    //}

                    //SET RETURN VALUES FOR INDICATOR
                    // Check for an uptrend line break
                    trendPrice[0] = (startBarPrice + (upTrendStartBarsAgo * changePerBar));
                    for (int barsAgo = upTrendEndBarsAgo - 1; barsAgo >= 0; barsAgo--)
                    {
                        if (D[barsAgo] < endBarPrice + (Math.Abs(upTrendEndBarsAgo - barsAgo) * changePerBar))
                        {
                            //if (ShowHistory)
                            //{
                            Draw.ArrowDown(this, "UpTrendBreak" + unique + lineCount.ToString(), true, barsAgo, D[barsAgo] + TickSize, DownTrendColor, false);
                            //}
                            //else
                            //{
                            //    Draw.ArrowDown(this, "UpTrendBreak" + unique, true, barsAgo, D[barsAgo] + TickSize, DownTrendColor, false);
                            //}
                            // Set the break signal only if the break is on the right most bar
                            if (barsAgo == 0)
                            {
                                signal[0] = -1;
                            }
                            // Alert will only trigger in real-time
                            //if (AlertOnBreak && triggerBarIndex == 0)
                            //{
                            //    triggerBarIndex = CurrentBar - upTrendEndBarsAgo;
                            //    Alert("Alert" + unique, Priority.High, "Up trend line broken", "Alert2.wav", 100000, Brushes.Black, Brushes.Red);
                            //}
                            break;
                        }
                    }
                }

                else
                //DETECT AND PROCESS DOWNTREND LINE	IF CURRENT
                if (downTrendStartBarsAgo > 0 && downTrendEndBarsAgo > 0 && upTrendStartBarsAgo > downTrendStartBarsAgo)
                {
                    RemoveDrawObject("UpTrendRay" + unique);
                    double startBarPrice = D[downTrendStartBarsAgo];
                    double endBarPrice   = D[downTrendEndBarsAgo];
                    double changePerBar  = (endBarPrice - startBarPrice) / (Math.Abs(downTrendEndBarsAgo - downTrendStartBarsAgo));
                    //Test to see if this is a new trendline and increment lineCount if so.
                    if (startBarPrice != startBarPriceOld)
                    {
                        direction[0] = -1;     //signl that we have a new downtrend
                        //if (ShowHistory)
                        //{
                        Draw.Dot(this, CurrentBar.ToString(), true, 0, startBarPrice + (downTrendStartBarsAgo * changePerBar), DownTrendColor, false);
                        trendStartPrice[0] = startBarPrice;
                        trendEndPrice[0]   = endBarPrice;
                        //}
                        lineCount       = lineCount + 1;
                        triggerBarIndex = 0;
                    }
                    startBarPriceOld = startBarPrice;
                    //
                    // Draw the down trend line
                    // If user has unlocked the ray use manual rays position instead
                    if ((DrawObjects["DownTrendRay" + unique] != null) && (!DrawObjects["DownTrendRay" + unique].IsLocked))
                    {
                        Ray downTrendRay = (Ray)DrawObjects["DownTrendRay" + unique];
                        startBarPrice         = downTrendRay.StartAnchor.Price;
                        endBarPrice           = downTrendRay.EndAnchor.Price;
                        downTrendStartBarsAgo = downTrendRay.StartAnchor.BarsAgo;
                        downTrendEndBarsAgo   = downTrendRay.EndAnchor.BarsAgo;
                        changePerBar          = (endBarPrice - startBarPrice) / (Math.Abs(downTrendRay.EndAnchor.BarsAgo - downTrendRay.StartAnchor.BarsAgo));
                    }
                    else
                    {
                        Draw.Ray(this, "DownTrendRay" + unique, false, downTrendStartBarsAgo, startBarPrice, downTrendEndBarsAgo, endBarPrice, DownTrendColor, DashStyleHelper.Solid, lineWidth, false);
                    }
                    //if (ShowHistory)
                    //{
                    Draw.Line(this, "HistoryLine" + unique + lineCount.ToString(), false, downTrendStartBarsAgo, startBarPrice, 0, startBarPrice + (downTrendStartBarsAgo * changePerBar), DownHistColor, DashStyleHelper.Solid, lineWidth, false);
                    //}
                    //SET RETURN VALUES FOR INDICATOR
                    // Check for a down trend line break
                    trendPrice[0] = (startBarPrice + (downTrendStartBarsAgo * changePerBar));
                    for (int barsAgo = downTrendEndBarsAgo - 1; barsAgo >= 0; barsAgo--)
                    {
                        //	direction=-1;
                        if (D[barsAgo] > endBarPrice + (Math.Abs(downTrendEndBarsAgo - barsAgo) * changePerBar))
                        {
                            //if (ShowHistory)
                            //{
                            Draw.ArrowUp(this, "DownTrendBreak" + unique + lineCount.ToString(), true, barsAgo, D[barsAgo] - TickSize, UpTrendColor, false);
                            //}
                            //else
                            //{
                            //    Draw.ArrowUp(this, "DownTrendBreak" + unique, true, barsAgo, D[barsAgo] - TickSize, UpTrendColor, false);
                            //}
                            // Set the break signal only if the break is on the right most bar
                            if (barsAgo == 0)
                            {
                                signal[0] = 1;
                            }
                            // Alert will only trigger in real-time
                            //if (AlertOnBreak && triggerBarIndex == 0)
                            //{
                            //    triggerBarIndex = CurrentBar - downTrendEndBarsAgo;
                            //    Alert("Alert" + unique, Priority.High, "Down trend line broken", "Alert2.wav", 100000, Brushes.Black, Brushes.Green);
                            //}
                            break;
                        }
                    }
                }

                //switch (direction[0])
                //{
                //    case -1:
                //        TrendInfo[0] = 35;
                //        break;
                //    case 0:
                //        TrendInfo[0] = 50;
                //        break;
                //    case 1:
                //        TrendInfo[0] = 65;
                //        break;
                //}

                //TrendInfo[0] = trendEndPrice[0];
            }
            #endregion
        }
Пример #23
0
        protected override void OnBarUpdate()
        {
            if (CurrentBar > Smooth && CurrentBar > Length)
            {
                switch (MaType)
                {
                case MovingAverageType.SMA:
                    Avg[0] = SMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.SMMA:
                    Avg[0] = SMMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.TMA:
                    Avg[0] = TMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.WMA:
                    Avg[0] = WMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.VWMA:
                    Avg[0] = VWMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.TEMA:
                    Avg[0] = TEMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.HMA:
                    Avg[0] = HMA(Input, Smooth)[0];
                    break;

                case MovingAverageType.VMA:
                    Avg[0] = VMA(Input, Smooth, Smooth)[0];
                    break;

                default:
                    Avg[0] = EMA(Input, Smooth)[0];
                    break;
                }
            }
            else
            {
                _trend[0]    = (true);
                Values[0][0] = (Input[0]);
                return;
            }

            switch (StMode)
            {
            case SuperTrendMode.ATR:
                _offset = ATR(Length)[0] * Multiplier;
                break;

            case SuperTrendMode.Adaptive:
                double per = CycleSmootherPeriod();
                _offset = ATR(Length)[0] * per / 10;
                break;

            case SuperTrendMode.DualThrust:
                _offset = Dtt(Length, Multiplier);
                break;
            }

            if (Close[0] > Value[1])
            {
                _trend[0] = (true);
            }
            else if (Close[0] < Value[1])
            {
                _trend[0] = (false);
            }
            else
            {
                _trend[0] = (_trend[1]);
            }

            if (_trend[0] && !_trend[1])
            {
                _th      = High[0];
                Value[0] = (Math.Max(Avg[0] - _offset, _tl));
                if (ShowIndicator)
                {
                    PlotBrushes[0][0] = UpColor;
                }
                else
                {
                    PlotBrushes[0][0] = Brushes.Transparent;
                }
                if (ShowArrows)
                {
                    Draw.ArrowUp(this, CurrentBar.ToString(), true, 0, Value[0] - TickSize, UpColor);
                }
                if (ColorBars)
                {
                    BarBrush = UpColor;
                }
                if (PlayAlert && _thisbar != CurrentBar)
                {
                    _thisbar = CurrentBar;
                    PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav");
                }
            }
            else
            if (!_trend[0] && _trend[1])
            {
                _tl      = Low[0];
                Value[0] = (Math.Min(Avg[0] + _offset, _th));
                if (ShowIndicator)
                {
                    PlotBrushes[0][0] = DownColor;
                }
                else
                {
                    PlotBrushes[0][0] = Brushes.Transparent;
                }
                if (ShowArrows)
                {
                    Draw.ArrowDown(this, CurrentBar.ToString(), true, 0, Value[0] + TickSize, DownColor);
                }
                if (ColorBars)
                {
                    BarBrush = DownColor;
                }
                if (PlayAlert && _thisbar != CurrentBar)
                {
                    _thisbar = CurrentBar;
                    PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav");
                }
            }
            else
            {
                if (_trend[0])
                {
                    Value[0] = ((Avg[0] - _offset) > Value[1] ? (Avg[0] - _offset) : Value[1]);
                    _th      = Math.Max(_th, High[0]);
                    if (ShowIndicator)
                    {
                        PlotBrushes[0][0] = UpColor;
                    }
                    else
                    {
                        PlotBrushes[0][0] = Brushes.Transparent;
                    }
                    if (ColorBars)
                    {
                        BarBrush = UpColor;
                    }
                }
                else
                {
                    Value[0] = ((Avg[0] + _offset) < Value[1] ? (Avg[0] + _offset) : Value[1]);
                    _tl      = Math.Min(_tl, Low[0]);
                    if (ShowIndicator)
                    {
                        PlotBrushes[0][0] = DownColor;
                    }
                    else
                    {
                        PlotBrushes[0][0] = Brushes.Transparent;
                    }
                    if (ColorBars)
                    {
                        BarBrush = DownColor;
                    }
                }
                RemoveDrawObject(CurrentBar.ToString());
            }
        }
Пример #24
0
        protected override void OnBarUpdate()
        {
            if (BarsInProgress != 0)
            {
                return;
            }

            if (CurrentBars[0] < 1 ||
                CurrentBars[1] < 1 ||
                CurrentBars[2] < 1)
            {
                return;
            }

            /* Set 1
             * Long signal if:
             *     Fast MA crosses above Slow MA on 4HR AND
             *     Fast MA > Slow MA Daily AND
             *     Fast MA > Slow MA Weekly
             */
            if ((CrossAbove(SMA1, SMA2, 1)) &&
                (SMA3[0] > SMA4[0]))
            //&& (SMA5[0] > SMA6[0]))
            {
                Draw.ArrowUp(this, @"TrendRider Arrow up_1", true, 0, 0, Brushes.Lime);
                if (AutoTrading)
                {
                    EnterLong(Convert.ToInt32(OrderQuantity), @"Long");
                    ExitShort(Convert.ToInt32(Position.Quantity), @"ExitShort", @"Short");
                }
            }

            /* Set 2
             * Short signal if:
             *     Fast MA crosses below Slow MA on 4HR AND
             *     Fast MA < Slow MA Daily AND
             *     Fast MA < Slow MA Weekly
             */
            if ((CrossBelow(SMA1, SMA2, 1)) &&
                (SMA3[0] < SMA4[0]))
            //&& (SMA5[0] < SMA6[0]))
            {
                Draw.ArrowDown(this, @"TrendRider Arrow down_1", false, 0, 0, Brushes.Red);
                if (AutoTrading)
                {
                    EnterShort(Convert.ToInt32(OrderQuantity), @"Short");
                    ExitLong(Convert.ToInt32(Position.Quantity), @"ExitLong", @"Long");
                }
            }

            /* Set 3
             * Close Long Positions if:
             *     Fast MA crosses below Slow MA on 4HR
             *
             * TODO:    SL hit if 1HR price closes below 4HR Swing Low
             *          if (Swing1.SwingHigh[0] > Close[0])
             */
            if (CrossBelow(SMA1, SMA2, 1))
            {
                if (AutoTrading)
                {
                    ExitLong(Convert.ToInt32(Position.Quantity), @"ExitLongMACross", @"Long");
                }
            }

            /* Set 3
             * Close Long Positions if:
             *     SL hit if 1HR price closes below 4HR Swing Low
             */
            if (Close[0] <= Swing1.SwingLow[0])
            {
                if (AutoTrading)
                {
                    ExitLong(Convert.ToInt32(Position.Quantity), @"ExitLongSwingLHit", @"Long");
                }
            }


            /* Set 4
             * Close Short Positions if:
             *     Fast MA crosses above Slow MA on 4HR
             */
            if (CrossAbove(SMA1, SMA2, 1))
            {
                if (AutoTrading)
                {
                    ExitShort(Convert.ToInt32(Position.Quantity), @"ExitShortMACross", @"Short");
                }
            }

            /* Set 3
             * Close Short Positions if:
             *     SL hit if 1HR price closes above 4HR Swing High
             */
            if (Close[0] >= Swing1.SwingHigh[0])
            {
                if (AutoTrading)
                {
                    ExitShort(Convert.ToInt32(Position.Quantity), @"ExitShortSwingLHit", @"Short");
                }
            }
        }