Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2021
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.64 KB | None | 0 0
  1. #region Using declarations
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Xml.Serialization;
  13. using NinjaTrader.Cbi;
  14. using NinjaTrader.Gui;
  15. using NinjaTrader.Gui.Chart;
  16. using NinjaTrader.Gui.SuperDom;
  17. using NinjaTrader.Gui.Tools;
  18. using NinjaTrader.Data;
  19. using NinjaTrader.NinjaScript;
  20. using NinjaTrader.Core.FloatingPoint;
  21. using NinjaTrader.NinjaScript.DrawingTools;
  22. #endregion
  23.  
  24. //This namespace holds Indicators in this folder and is required. Do not change it.
  25. namespace NinjaTrader.NinjaScript.Indicators
  26. {
  27.     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
  28.     public class BarTimerFlashFusion : Indicator
  29.     {
  30.         private string          timeLeft    = string.Empty;
  31.         private DateTime        now         = Core.Globals.Now;
  32.         private bool            connected,
  33.                                 hasRealtimeData;
  34.         private SessionIterator sessionIterator;
  35.  
  36.         private System.Windows.Threading.DispatcherTimer timer;
  37.        
  38.         private DisplayType dType   = DisplayType.All;
  39.         private FlashType   fType   = FlashType.WholePanel;
  40.        
  41.         private int var1 = 0;
  42.         private int var2 = 0;
  43.        
  44.         private TimeSpan barTimeLeft;
  45.        
  46.         private System.Windows.Media.Brush  textBrush;
  47.        
  48.         private SimpleFont textFont;
  49.  
  50.         protected override void OnStateChange()
  51.         {
  52.             if (State == State.SetDefaults)
  53.             {
  54.                 Description = @"Displays time countdown of interval based bar series.";
  55.                 Name = "BarTimerFlashFusion";
  56.                 Calculate = Calculate.OnEachTick;
  57.                 DrawOnPricePanel = false;
  58.                 IsChartOnly = true;
  59.                 IsOverlay = true;
  60.                 DisplayInDataBox = false;
  61.                 Sound           = true;
  62.                
  63.                 AlertDuration = 10;
  64.                 Alert = 12;
  65.                
  66.                 TextBrush = System.Windows.Media.Brushes.DodgerBlue;
  67.                
  68.                 TextFont = new SimpleFont("Arial", 12);
  69.             }
  70.             else if (State == State.DataLoaded)
  71.             {
  72.                 if (BarsPeriod.BarsPeriodType == BarsPeriodType.Minute)
  73.                     var2 = (BarsPeriod.Value*60) - Alert;
  74.                 else if (BarsPeriod.BarsPeriodType == BarsPeriodType.Second)
  75.                     var2 = BarsPeriod.Value - Alert;
  76.                 var1 = var2 - AlertDuration;
  77.             }
  78.             else if (State == State.Historical)
  79.             {
  80.                 SetZOrder(-1);
  81.             }
  82.             else if (State == State.Realtime)
  83.             {
  84.                 if (timer == null)
  85.                 {
  86.                     if (Bars.BarsType.IsTimeBased && Bars.BarsType.IsIntraday)
  87.                     {
  88.                         lock (Connection.Connections)
  89.                         {
  90.                             if (Connection.Connections.ToList().FirstOrDefault(c => c.Status == ConnectionStatus.Connected && c.InstrumentTypes.Contains(Instrument.MasterInstrument.InstrumentType)) == null)
  91.                                 Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerDisconnectedError, TextPosition.BottomRight);
  92.                             else
  93.                             {
  94.                                 if (!SessionIterator.IsInSession(Now, false, true))
  95.                                     Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerSessionTimeError, TextPosition.BottomRight);
  96.                                 else
  97.                                     Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerWaitingOnDataError, TextPosition.BottomRight);
  98.                             }
  99.                         }
  100.                     }
  101.                     else
  102.                         Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerTimeBasedError, TextPosition.BottomRight);
  103.                 }
  104.             }
  105.             else if (State == State.Terminated)
  106.             {
  107.                 if (timer == null)
  108.                     return;
  109.  
  110.                 timer.IsEnabled = false;
  111.                 timer = null;
  112.             }
  113.         }
  114.  
  115.         protected override void OnBarUpdate()
  116.         {
  117.             if (State == State.Realtime)
  118.             {
  119.                 hasRealtimeData = true;
  120.                 connected = true;
  121.                
  122.                 if (IsFirstTickOfBar && Sound)
  123.                 {
  124.                     PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav");
  125.                 }
  126.             }
  127.         }
  128.  
  129.         protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
  130.         {
  131.             if (connectionStatusUpdate.PriceStatus == ConnectionStatus.Connected
  132.                 && connectionStatusUpdate.Connection.InstrumentTypes.Contains(Instrument.MasterInstrument.InstrumentType)
  133.                 && Bars.BarsType.IsTimeBased
  134.                 && Bars.BarsType.IsIntraday)
  135.             {
  136.                 connected = true;
  137.  
  138.                 if (DisplayTime() && timer == null)
  139.                 {
  140.                     ChartControl.Dispatcher.InvokeAsync(() =>
  141.                     {
  142.                         timer = new System.Windows.Threading.DispatcherTimer { Interval = new TimeSpan(0, 0, 1), IsEnabled = true };
  143.                         timer.Tick += OnTimerTick;
  144.                     });
  145.                 }
  146.             }
  147.             else if (connectionStatusUpdate.PriceStatus == ConnectionStatus.Disconnected)
  148.                 connected = false;
  149.         }
  150.        
  151.         protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
  152.         {
  153.             SharpDX.Direct2D1.Brush textBrushDx                         = textBrush.ToDxBrush(RenderTarget);
  154.             NinjaTrader.Gui.Tools.SimpleFont simpleFont                 = TextFont;
  155.             SharpDX.DirectWrite.TextFormat textFormat1                  = simpleFont.ToDirectWriteTextFormat();
  156.             SharpDX.Vector2 upperTextPoint                              = new SharpDX.Vector2(ChartPanel.X + 10, ChartPanel.Y + (float)(simpleFont.Size * 1.5));
  157.             SharpDX.DirectWrite.TextLayout textLayout1                  = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, timeLeft, textFormat1, ChartPanel.X + ChartPanel.W, textFormat1.FontSize);
  158.            
  159.             RenderTarget.DrawTextLayout(upperTextPoint, textLayout1, textBrushDx, SharpDX.Direct2D1.DrawTextOptions.NoSnap);
  160.            
  161.             SharpDX.Vector2 startPoint                                  = new SharpDX.Vector2(ChartPanel.X, ChartPanel.Y);
  162.             SharpDX.Vector2 endPoint                                    = new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, ChartPanel.Y + ChartPanel.H);
  163.                
  164.             SharpDX.Direct2D1.LinearGradientBrush linearGradientBrush   = new SharpDX.Direct2D1.LinearGradientBrush(RenderTarget, new SharpDX.Direct2D1.LinearGradientBrushProperties()
  165.             {
  166.                 StartPoint = new SharpDX.Vector2(0, startPoint.Y),
  167.                 EndPoint = new SharpDX.Vector2(0, endPoint.Y),
  168.             },
  169.             new SharpDX.Direct2D1.GradientStopCollection(RenderTarget, new SharpDX.Direct2D1.GradientStop[]
  170.             {
  171.                 new SharpDX.Direct2D1. GradientStop()
  172.                 {
  173.                     Color = SharpDX.Color.DarkGray,
  174.                     Position = 0,
  175.                 },
  176.                 new     SharpDX.Direct2D1. GradientStop()
  177.                 {
  178.                     Color = SharpDX.Color.AntiqueWhite,
  179.                     Position = 1,
  180.                 }
  181.             }));
  182.            
  183.             if(fType != FlashType.None && (int)barTimeLeft.TotalSeconds < var2  && (int)barTimeLeft.TotalSeconds > var1)
  184.             {
  185.                 if((int)barTimeLeft.TotalSeconds % 2 < 1 )//alternate colors every second
  186.                 {                  
  187.                     if(fType == FlashType.WholePanel)
  188.                     {                      
  189.                         SharpDX.RectangleF rect = new SharpDX.RectangleF(startPoint.X, startPoint.Y, endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);
  190.                         RenderTarget.FillRectangle(rect, linearGradientBrush);
  191.                     }
  192.                     else if(fType == FlashType.ClockFaceOnly)
  193.                     {                      
  194.                         SharpDX.Vector2 lowerTextPoint = new SharpDX.Vector2(ChartPanel.X + 5, ChartPanel.Y + (ChartPanel.H - textLayout1.Metrics.Height));
  195.                         SharpDX.RectangleF rect = new SharpDX.RectangleF(upperTextPoint.X, upperTextPoint.Y, textLayout1.Metrics.Width, textLayout1.Metrics.Height);
  196.                        
  197.                         RenderTarget.FillRectangle(rect, linearGradientBrush);
  198.                         RenderTarget.DrawTextLayout(upperTextPoint, textLayout1, textBrushDx, SharpDX.Direct2D1.DrawTextOptions.NoSnap);
  199.                     }
  200.                     else if(fType == FlashType.TextOnly)
  201.                     {
  202.                         RenderTarget.DrawTextLayout(upperTextPoint, textLayout1, linearGradientBrush, SharpDX.Direct2D1.DrawTextOptions.NoSnap);
  203.                     }
  204.                 }
  205.             }
  206.            
  207.             linearGradientBrush.Dispose();
  208.             textBrushDx.Dispose();
  209.             textFormat1.Dispose();
  210.             textLayout1.Dispose();
  211.         }
  212.  
  213.         private bool DisplayTime()
  214.         {
  215.             return ChartControl != null
  216.                     && Bars != null
  217.                     && Bars.Instrument.MarketData != null;
  218.         }
  219.  
  220.         private void OnTimerTick(object sender, EventArgs e)
  221.         {
  222.             ForceRefresh();
  223.  
  224.             if (DisplayTime())
  225.             {
  226.                 if (timer != null && !timer.IsEnabled)
  227.                     timer.IsEnabled = true;
  228.  
  229.                 if (connected)
  230.                 {
  231.                     if (SessionIterator.IsInSession(Now, false, true))
  232.                     {
  233.                         if (hasRealtimeData)
  234.                         {
  235.                             barTimeLeft = Bars.GetTime(Bars.Count - 1).Subtract(Now);
  236.  
  237.                             if (dType == DisplayType.LapsedTimeOnly)
  238.                                 timeLeft = (barTimeLeft.Ticks < 0
  239.                                     ? "00:00:00"
  240.                                     : barTimeLeft.Hours.ToString("00") + ":" + barTimeLeft.Minutes.ToString("00") + ":" + barTimeLeft.Seconds.ToString("00"));
  241.                             if (dType == DisplayType.ClockOnly)
  242.                                 timeLeft = Now.ToString("T");
  243.                             if (dType == DisplayType.All)
  244.                                 timeLeft = Now.ToString("T")+ "\n[" + (barTimeLeft.Ticks < 0
  245.                                     ? "00:00:00"
  246.                                     : barTimeLeft.Hours.ToString("00") + ":" + barTimeLeft.Minutes.ToString("00") + ":" + barTimeLeft.Seconds.ToString("00")+"]");
  247.  
  248.                             RemoveDrawObject("NinjaScriptInfo");
  249.                         }
  250.                         else
  251.                             Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerWaitingOnDataError, TextPosition.BottomRight);
  252.                     }
  253.                     else
  254.                         Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerSessionTimeError, TextPosition.BottomRight);
  255.                 }
  256.                 else
  257.                 {
  258.                     Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerDisconnectedError, TextPosition.BottomRight);
  259.  
  260.                     if (timer != null)
  261.                         timer.IsEnabled = false;
  262.                 }
  263.                
  264.                 if(fType != FlashType.None && (int)barTimeLeft.TotalSeconds < var2  && (int)barTimeLeft.TotalSeconds > var1)
  265.                 {
  266.                     ForceRefresh();
  267.                 }
  268.             }
  269.         }
  270.  
  271.         private SessionIterator SessionIterator
  272.         {
  273.             get
  274.             {
  275.                 if (sessionIterator == null)
  276.                     sessionIterator = new SessionIterator(Bars);
  277.                 return sessionIterator;
  278.             }
  279.         }
  280.  
  281.         private DateTime Now
  282.         {
  283.             get
  284.             {
  285.                 now = (Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : Core.Globals.Now);
  286.  
  287.                 if (now.Millisecond > 0)
  288.                     now = Core.Globals.MinDate.AddSeconds((long)Math.Floor(now.Subtract(Core.Globals.MinDate).TotalSeconds));
  289.  
  290.                 return now;
  291.             }
  292.         }
  293.        
  294.         #region Properties
  295.         [Range(1, int.MaxValue), NinjaScriptProperty]
  296.         [Display(GroupName = "Parameters", Description="Duration of alert.")]
  297.         public int AlertDuration
  298.         { get; set; }
  299.        
  300.         [Range(1, int.MaxValue), NinjaScriptProperty]
  301.         [Display(GroupName = "Parameters", Description="Alert start.")]
  302.         public int Alert
  303.         { get; set; }
  304.        
  305.         [Display(GroupName = "Parameters", Description="Clock and Timer Font.")]
  306.         public SimpleFont TextFont
  307.         {
  308.             get { return textFont; }
  309.             set { textFont = value; }
  310.         }
  311.        
  312.         [Display(GroupName = "Parameters", Description="Show lapsed time only or with Actual time.")]
  313.         public DisplayType DType
  314.         {
  315.             get { return dType; }
  316.             set { dType = value; }
  317.         }
  318.        
  319.         [Display(GroupName = "Parameters", Description="Select Clock Face or Whole Panel.\nNone disables flashing.")]
  320.         public FlashType FType
  321.         {
  322.             get { return fType; }
  323.             set { fType = value; }
  324.         }
  325.        
  326.         [NinjaScriptProperty]
  327.         [Display(Name="Sound", Order=1, GroupName="Parameters")]
  328.         public bool Sound
  329.         { get; set; }
  330.        
  331.         [XmlIgnore]
  332.         [Display(ResourceType = typeof(Custom.Resource), Name = "TextColor", GroupName = "Parameters")]
  333.         public System.Windows.Media.Brush TextBrush
  334.         {
  335.             get { return textBrush; }
  336.             set { textBrush = value; }
  337.         }
  338.  
  339.         [Browsable(false)]
  340.         public string TextBrushSerialize
  341.         {
  342.             get { return Serialize.BrushToString(TextBrush); }
  343.             set { TextBrush = Serialize.StringToBrush(value); }
  344.         }
  345.         #endregion
  346.     }
  347. }
  348.  
  349. public enum DisplayType
  350. {
  351.     All,LapsedTimeOnly,ClockOnly
  352. }
  353.  
  354. public enum FlashType
  355. {
  356.     None,
  357.     WholePanel,
  358.     ClockFaceOnly,
  359.     TextOnly
  360. }
  361.  
  362. #region NinjaScript generated code. Neither change nor remove.
  363.  
  364. namespace NinjaTrader.NinjaScript.Indicators
  365. {
  366.     public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
  367.     {
  368.         private BarTimerFlashFusion[] cacheBarTimerFlashFusion;
  369.         public BarTimerFlashFusion BarTimerFlashFusion(int alertDuration, int alert, bool sound)
  370.         {
  371.             return BarTimerFlashFusion(Input, alertDuration, alert, sound);
  372.         }
  373.  
  374.         public BarTimerFlashFusion BarTimerFlashFusion(ISeries<double> input, int alertDuration, int alert, bool sound)
  375.         {
  376.             if (cacheBarTimerFlashFusion != null)
  377.                 for (int idx = 0; idx < cacheBarTimerFlashFusion.Length; idx++)
  378.                     if (cacheBarTimerFlashFusion[idx] != null && cacheBarTimerFlashFusion[idx].AlertDuration == alertDuration && cacheBarTimerFlashFusion[idx].Alert == alert && cacheBarTimerFlashFusion[idx].Sound == sound && cacheBarTimerFlashFusion[idx].EqualsInput(input))
  379.                         return cacheBarTimerFlashFusion[idx];
  380.             return CacheIndicator<BarTimerFlashFusion>(new BarTimerFlashFusion(){ AlertDuration = alertDuration, Alert = alert, Sound = sound }, input, ref cacheBarTimerFlashFusion);
  381.         }
  382.     }
  383. }
  384.  
  385. namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
  386. {
  387.     public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
  388.     {
  389.         public Indicators.BarTimerFlashFusion BarTimerFlashFusion(int alertDuration, int alert, bool sound)
  390.         {
  391.             return indicator.BarTimerFlashFusion(Input, alertDuration, alert, sound);
  392.         }
  393.  
  394.         public Indicators.BarTimerFlashFusion BarTimerFlashFusion(ISeries<double> input , int alertDuration, int alert, bool sound)
  395.         {
  396.             return indicator.BarTimerFlashFusion(input, alertDuration, alert, sound);
  397.         }
  398.     }
  399. }
  400.  
  401. namespace NinjaTrader.NinjaScript.Strategies
  402. {
  403.     public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
  404.     {
  405.         public Indicators.BarTimerFlashFusion BarTimerFlashFusion(int alertDuration, int alert, bool sound)
  406.         {
  407.             return indicator.BarTimerFlashFusion(Input, alertDuration, alert, sound);
  408.         }
  409.  
  410.         public Indicators.BarTimerFlashFusion BarTimerFlashFusion(ISeries<double> input , int alertDuration, int alert, bool sound)
  411.         {
  412.             return indicator.BarTimerFlashFusion(input, alertDuration, alert, sound);
  413.         }
  414.     }
  415. }
  416.  
  417. #endregion
  418.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement