Codificar Indicador Ninjatrader CCI divergencias
Forums › ProRealTime foro Español › Soporte ProBuilder › Codificar Indicador Ninjatrader CCI divergencias
- This topic has 7 replies, 4 voices, and was last updated 2 years ago by pepe.
-
-
11/03/2020 at 10:38 AM #149360
Hola buenas días. Me gustaría emplear la herramienta Prorealtime, pero para ello me gustaría tener el indicador que uso muy frecuentemente que es un indicador de divergencias entre el precio y el indicador. Se que en la plataforma 11.0 de prorealtime hay un CCI divergencias, pero lo que me interesa a mi es que siga pintando en el gráfico que la divergencia se sigue cumpliendo….
El indicador está pensado para toda clase de divergencias en cualquier indicador, pero en mi caso solo me interesa el CCI.
Adjunto capturas de pantalla y el código.
Muchas gracias.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234//Código#region Using declarationsusing System;using System.Collections.Generic;using System.ComponentModel;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Input;using System.Windows.Media;using System.Xml.Serialization;using NinjaTrader.Cbi;using NinjaTrader.Gui;using NinjaTrader.Gui.Chart;using NinjaTrader.Gui.SuperDom;using NinjaTrader.Gui.Tools;using NinjaTrader.Data;using NinjaTrader.NinjaScript;using NinjaTrader.Core.FloatingPoint;using NinjaTrader.NinjaScript.DrawingTools;using System.Net;using System.IO;using System.Data.SqlClient;using System.Collections.ObjectModel;#endregion//This namespace holds Indicators in this folder and is required. Do not change it.namespace NinjaTrader.NinjaScript.Indicators{#region Clasespublic class SignalsDivergencia{public DateTime time;public string direccion;public string instrumento;}public static class DivergenciasSignals{private static ObservableCollection _coleccionSignalsDivergencias = new ObservableCollection();public static ObservableCollection ColeccionSignalsDivergencias{get{return _coleccionSignalsDivergencias;}}}#endregionpublic class DivergenceSpotterV2 : Indicator{private DivergenceSpotter_IndicatorType indicatorType; // Default setting for IndicatorTypeprivate int fastPeriod; // Default setting for FastPeriodprivate int slowPeriod; // Default setting for SlowPeriodprivate int signalPeriod; // Default setting for SignalPeriodprivate int lookbackPeriod; //If “0”, then lookback to first instance of indicator crossing 0 line//if “>0”, then lookback only that amount of barsprivate int barSensitivity; //small values increase divergences, large values decrease//ideal value is 50% of lookbackPeriodprivate bool alerta;private int bkgopacity;private int LastSignal;private int BarOfLastSignal;// User defined variables (add any user defined variables below)private int bardiff, i;private bool DoneSearching, RunInit;private Brush StripeBackgroundColor;private Series TheIndicator;protected override void OnStateChange(){if (State == State.SetDefaults){Description = @”Enter the description for your new custom Indicator here.”;Name = “DivergenceSpotterV2”;Calculate = Calculate.OnBarClose;IsOverlay = true;DisplayInDataBox = true;DrawOnPricePanel = true;DrawHorizontalGridLines = true;DrawVerticalGridLines = true;PaintPriceMarkers = true;ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;//Disable this property if your indicator requires custom values that cumulate with each new market data event.//See Help Guide for additional information.IsSuspendedWhileInactive = false;indicatorType = DivergenceSpotter_IndicatorType.CCI; // Default setting for IndicatorTypefastPeriod = 20; // Default setting for FastPeriodslowPeriod = 26; // Default setting for SlowPeriodsignalPeriod = 9; // Default setting for SignalPeriodlookbackPeriod = 0; //If “0”, then lookback to first instance of indicator crossing 0 line//if “>0”, then lookback only that amount of barsbarSensitivity=7; //small values increase divergences, large values decrease//ideal value is 50% of lookbackPeriodalerta = false;bkgopacity = 25;LastSignal = 0;BarOfLastSignal=-10;// User defined variables (add any user defined variables below)bardiff=0;DoneSearching = true;RunInit=true;AddPlot(new Stroke(Brushes.Blue, 2), PlotStyle.Dot, “BuySignal”);AddPlot(new Stroke(Brushes.DeepPink, 2), PlotStyle.Dot, “SellSignal”);}else if (State == State.Configure){if (RunInit && ChartControl != null){RunInit = false;IsAutoScale = false;}}else if (State == State.DataLoaded){TheIndicator = new Series(this, MaximumBarsLookBack.Infinite);}}protected override void OnBarUpdate(){if(RunInit) return;int LowestBarIndexPossible = Math.Max(fastPeriod,Math.Max(slowPeriod,lookbackPeriod));if(CurrentBar < 1+LowestBarIndexPossible) return; if(indicatorType == DivergenceSpotter_IndicatorType.MACD) TheIndicator[0] = MACD(fastPeriod,slowPeriod,signalPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.TRIX) TheIndicator[0] = TRIX(slowPeriod,signalPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.StochFastK) TheIndicator[0] = StochasticsFast(slowPeriod, fastPeriod).K[0]-50.0; else if(indicatorType == DivergenceSpotter_IndicatorType.StochRSI) TheIndicator[0] = StochRSI(fastPeriod)[0]-0.5; else if(indicatorType == DivergenceSpotter_IndicatorType.CCI) TheIndicator[0] = CCI(fastPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.BOP) TheIndicator[0] = BOP(fastPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.CMO) TheIndicator[0] = CMO(fastPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.ChaikinMoneyFlow) TheIndicator[0] = ChaikinMoneyFlow(fastPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.Momentum) TheIndicator[0] = Momentum(fastPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.MFI) TheIndicator[0] = MFI(fastPeriod)[0]; else if(indicatorType == DivergenceSpotter_IndicatorType.RSI) TheIndicator[0] = RSI(fastPeriod,signalPeriod)[0]-50; //signalPeriod is here, but is ignored in the divergence calc else if(indicatorType == DivergenceSpotter_IndicatorType.ROC) TheIndicator[0] = ROC(fastPeriod)[0]; else if (indicatorType == DivergenceSpotter_IndicatorType.StochSlowD) TheIndicator[0] = Stochastics(slowPeriod, fastPeriod, signalPeriod).D[0] - 50; else if (indicatorType == DivergenceSpotter_IndicatorType.StochFastD) TheIndicator[0] = StochasticsFast(slowPeriod, fastPeriod).D[0] - 50; else return; double Hprice = double.MinValue; double Lprice = High[0]; double Hindicator = TheIndicator[0]; double Lindicator = TheIndicator[0]; int HPriceBar = -1; int LPriceBar = -1; int LIndicatorBar = -1; int HIndicatorBar = -1; i=1; DoneSearching=false; while(!DoneSearching) { if (High[i]>Hprice) //a new high in price was found, record it{ Hprice = High[i];HPriceBar = i; //this is the bar number of the highest price in the lookbackPeriod}if(Low[i]Hindicator) //a new high in the indicator was found, record it{ Hindicator = TheIndicator[i];HIndicatorBar = i;//this is the bar number of the highest indicator value in the lookbackPeriod}if(TheIndicator[i]CurrentBar-LowestBarIndexPossible-1)DoneSearching =true; //limit of search reachedif(lookbackPeriod==0)//then find the last time the indicator crossed the “0” line{if (TheIndicator[i] * TheIndicator[i+1] < 0.0) DoneSearching =true; } else //terminate the search when i has exceeded the lookbackPeriod { if (i > lookbackPeriod)DoneSearching =true;}}SellSignal[0] = 0;BuySignal[0] = 0;BackBrush = null;if(CurrentBar – BarOfLastSignal > 10) LastSignal=0;if(TheIndicator[0]>0) //look for sell divergence since Indicator is above ZERO{bardiff = HIndicatorBar-HPriceBar; //How many bars separated the highs?if(bardiff>barSensitivity) {SellSignal[0] = Low[0]-Math.Max((High[0]-Low[0])/2,5*TickSize);if (State == State.Realtime && alerta){Print(Time[0] + “–> Sell Signal en –>” + Instrument.MasterInstrument.Name + “–>TimeFrame: ” + BarsPeriod.Value + “–> Precio” + SellSignal[0]);InsertarSignals(Instrument.MasterInstrument.Name, “DIVERGENCIA”, 0, (decimal)SellSignal[0], “SELL”);}if (LastSignal != -1 && bkgopacity > 0){BackBrush = new SolidColorBrush(Color.FromArgb((byte)Math.Round(255.0 * bkgopacity / 10, 0), 255, 51, 153));//Añadimos la señal a la colecciónDivergenciasSignals.ColeccionSignalsDivergencias.Add(new SignalsDivergencia() { time = Time[0], instrumento = Instrument.MasterInstrument.Name, direccion = “SELL” });if (State == State.Realtime && alerta){Print(“Divergencia detectada<-->Sell>–>” + Instrument.MasterInstrument.Name);InsertarSignals(Instrument.MasterInstrument.Name, “DIVERGENCIA”, 0, 0, “SELL”);}}LastSignal = -1;BarOfLastSignal = CurrentBar;}}else //look for Buy divergence since Indicator is below ZERO{bardiff = LIndicatorBar-LPriceBar; //How many bars separated the lows?if(bardiff>barSensitivity) {BuySignal[0] = High[0]+Math.Max((High[0]-Low[0])/2,5*TickSize);if (State == State.Realtime && alerta){Print(Time[0] + “–> Buy Signal en –>” + Instrument.MasterInstrument.Name + “–>TimeFrame: ” + BarsPeriod.Value + “–> Precio” + BuySignal[0]);InsertarSignals(Instrument.MasterInstrument.Name, “DIVERGENCIA”, 0, (decimal)BuySignal[0], “BUY”);}if (LastSignal != 1 && bkgopacity > 0){BackBrush = new SolidColorBrush(Color.FromArgb((byte)Math.Round(255.0 * bkgopacity / 10, 0), 0, 0, 255));DivergenciasSignals.ColeccionSignalsDivergencias.Add(new SignalsDivergencia() { time = Time[0], instrumento = Instrument.MasterInstrument.Name, direccion = “BUY” });if (State == State.Realtime && alerta){Print(“Divergencia detectada<-->Buy>–>” + Instrument.MasterInstrument.Name);InsertarSignals(Instrument.MasterInstrument.Name, “DIVERGENCIA”, 0, 0, “BUY”);}}LastSignal = 1;BarOfLastSignal = CurrentBar;}}}11/03/2020 at 11:34 AM #149367- Siempre use el botón “Insert PRT Code” cuando incluya e inserte un código en sus mensajes para que sea más fácil de leer para otros.
- Dale a tu asunto un título significativo. Describa su pregunta o tema en su título. No utilice títulos sin sentido como “Ayuda con la codificación, por favor, etc“.
- No duplique los mensajes. Haga su pregunta una vez y en un foro. Cualquier mensaje duplicado se eliminará de todos modos, por lo que publicar la misma pregunta varias veces le hará perder su tiempo y no recibirá respuestas más rápidas.
La doble publicación solo crea confusión en los foros(¿Este indicador es el mismo que el que publicaste?)
Gracias 🙂
11/03/2020 at 11:37 AM #149368Algunas de las reglas principales del foro están BIEN DESTACADAS a continuación (en amarillo).
Léalos atentamente por respeto a los demás.
Gracias 🙂
11/03/2020 at 5:02 PM #14939511/03/2020 at 5:11 PM #149398En primer lugar muchas gracias.
Siento la duplicidad del mensaje, ha sido un error.
Gracias…
11/13/2020 at 9:55 AM #150355Buenos días. He conseguido codificar el indicador, pero solo estoy consiguiendo que me indique las divergencias bajistas, que coinciden con el indicador que lleva la plataforma CCIDivergencias, y coincide con mi indicador en NinjaTrader.
El código lo adjunto, por si me pueden ayudar en que estoy haciendo mal, para que no me marque las divergencias alcistas.
Soy programador de C# y es la primera vez que intento codificar algo en este lenguaje.
Gracias
CCI Divergencias123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108Indicador = CCI[FastPeriod](close)LowestBarIndexPossible = MAX(FastPeriod,MAX(SlowPeriod,LookBackPeriod))Hprice = 0Lprice = HighHindicador = IndicadorLIndicador = IndicadorHPriceBar = -1LPriceBar = -1LIndicatorBar = -1HIndicatorBar = -1i = 1Resultado = 1DoneSearching = 0LastSignal = 0BarOfLastSignal = -10bardiff = 0bkgOpacity = 25if BarIndex < LowestBarIndexPossible + 1 ThenResultado = undefinedelserem Procesamos si esxisten divergencias...While DoneSearching = 0 DOIf High[i] > Hprice ThenHprice = High[i]HPriceBar = iEndIfIf Low[i] < LPrice ThenLowPrice = LowLPriceBar = iEndIfIf Indicador[i] > HIndicador ThenHIndicador = Indicador[i]HIndicatorBar = iEndIFIf Indicador[i] < LIndicador ThenLIndicador = Indicador[i]LIndicator = iEndIFi = i + 1If i > (BarIndex - LowestBarIndexPossible -1) ThenDoneSearching = 1EndIFIf LookBackPeriod = 0 ThenIf Indicador[i] * Indicador[i+1] < 0.0 ThenDoneSearching = 1EndIfElseIf i > LookBackPeriod ThenDoneSearching = 1EndIfEndIFWendREM Buscamos las divergencias....If BarIndex - BarOfLastSignal > 10 ThenLastSignal = 0EndIfRem look for sell divergence since Indicator is above ZERODRAWPOINT(barindex, close, 2)If Indicador[0] > 0 Thenbardiff = HIndicatorBar - HPriceBarIf bardiff > BarSensity ThenDRAWARROWUP(barindex, Low - ((High - Low)/2))COLOURED (255, 0, 0)Resultado = -10If LastSignal <> -1 AND bkgOpacity > 0 ThenBACKGROUNDCOLOR (255,153,153)EndIfLastSignal = -1BarOfLastSignal = BarIndexEndIFElse Rem //look for Buy divergence since Indicator is below ZERObardiff = LIndicatorBar - LPriceBarIf bardiff > BarSensity ThenDRAWARROWDOWN(barindex, High - ((High - Low)/2))COLOURED (0, 255, 0)Resultado = 10If LastSignal <> 1 AND bkgOpacity > 0 ThenBACKGROUNDCOLOR (51,255,153)EndIfLastSignal = 1BarOfLastSignal = BarIndexEndIFEndIfrem Resultado = -10EndIFreturn resultado11/13/2020 at 10:31 AM #150359Ya lo he conseguido, era que estaba asignando mal una variable..
Ahora lo que me gustaría saber, es que el indicador me exige que devuelva un resultado, pero no quiero devolver nada. Cómo puedo ignorar eso.
No quiero devolver nada, ya que el el panel principal, ya tengo mis señales.
Gracias
08/08/2022 at 5:33 PM #198760 -
AuthorPosts
Find exclusive trading pro-tools on