focus qs
unknown
csharp
2 years ago
18 kB
13
Indexable
Never
#region Using declarations using 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; #endregion //This namespace holds Indicators in this folder and is required. Do not change it. namespace NinjaTrader.NinjaScript.Indicators { public class ProfitSniper : Indicator { #region Class Level Variables private Position accountPosition; private List<Order> changeOrdersArray, submitOrdersArray, multiOrders; private double currentPtPrice, currentSlPrice; private Order entryBuyMarketOrder, entrySellMarketOrder, profitTargetOrder, stopLossOrder; private Account myAccount; #region QuantitySelector // QS Define a Chart object to refer to the chart on which the indicator resides private Chart chartWindow; NinjaTrader.Gui.Tools.QuantityUpDown quantitySelector; // QS private bool Is_ToolBar_Controls_Added; // QS https://stackoverflow.com/a/9301272/10789707 private int qs; #endregion #endregion #region OnStateChange protected override void OnStateChange() { // NinjaTrader.Gui.Tools.QuantityUpDown quantitySelector; if (State == State.SetDefaults) { Description = @"Orders Hotkeys Manager."; Name = "ProfitSniper"; Calculate = Calculate.OnEachTick; IsOverlay = true; DisplayInDataBox = false; PrintDetails = false; ProfitTargetDistance = 10; StopLossDistance = 10; UseProfitTarget = true; UseStopLoss = true; ProfitTargetMove = 1; StopLossMove = 1; AccountName = "Sim101"; } else if (State == State.Configure) { } else if (State == State.Historical) { //Call the custom addButtonToToolbar method in State.Historical to ensure it is only done when applied to a chart // -- not when loaded in the Indicators window if (!Is_ToolBar_Controls_Added) Add_Controls_To_Toolbar(); } else if (State == State.DataLoaded) { // Find our account lock (Account.All) myAccount = Account.All.FirstOrDefault(a => a.Name == AccountName); if (myAccount != null) myAccount.OrderUpdate += Account_OrderUpdate; if (ChartControl != null) { ChartControl.PreviewKeyDown += ChartControl_PreviewKeyDown; ChartControl.Dispatcher.InvokeAsync((Action)(() => { quantitySelector = (Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlQuantitySelector") as NinjaTrader.Gui.Tools.QuantityUpDown); })); } } else if (State == State.Terminated) { if (myAccount != null) myAccount.OrderUpdate -= Account_OrderUpdate; if (ChartControl != null) { ChartControl.PreviewKeyDown -= ChartControl_PreviewKeyDown; } //Call a custom method to dispose of any leftover objects in State.Terminated DisposeCleanUp(); } } #endregion #region Hotkeys Snippets protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e) { TriggerCustomEvent(k => { if (Keyboard.IsKeyDown(Key.Insert)) { quantitySelector.Focus(); } }, null); e.Handled = true; // LONG Orders TriggerCustomEvent(o => { if (Keyboard.IsKeyDown(Key.NumPad1)) { multiOrders = new List<Order>(); for (int index = 0; index < quantitySelector.Value; index++) { entryBuyMarketOrder = myAccount.CreateOrder( Instrument, OrderAction.Buy, OrderType.Market, OrderEntry.Manual, TimeInForce.Day, 1, 0, 0, string.Empty, "Entry", Core.Globals.MaxDate, null); multiOrders.Add(entryBuyMarketOrder); } } myAccount.Submit(new[] { entryBuyMarketOrder }); myAccount.Submit(multiOrders); }, null); e.Handled = true; // SHORT Orders TriggerCustomEvent(p => { if (Keyboard.IsKeyDown(Key.NumPad2)) { multiOrders = new List<Order>(); for (int index = 0; index < quantitySelector.Value; index++) { entrySellMarketOrder = myAccount.CreateOrder( Instrument, OrderAction.Sell, OrderType.Market, OrderEntry.Manual, TimeInForce.Day, 1, 0, 0, string.Empty, "Entry", Core.Globals.MaxDate, null); multiOrders.Add(entrySellMarketOrder); } } myAccount.Submit(new[] { entrySellMarketOrder }); myAccount.Submit(multiOrders); }, null); e.Handled = true; // Move Up Target OCO Order TriggerCustomEvent(qa => { if (entryBuyMarketOrder != null) { if (Keyboard.IsKeyDown(Key.NumPad7) && !(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))) { currentPtPrice = profitTargetOrder.LimitPrice + (ProfitTargetMove * TickSize); for (int index = 0; index < quantitySelector.Value; index++) { submitOrdersArray[index].LimitPriceChanged = currentPtPrice; } myAccount.Change(submitOrdersArray); } } else if (entrySellMarketOrder != null) { if (Keyboard.IsKeyDown(Key.NumPad7) && !(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))) { currentPtPrice = profitTargetOrder.LimitPrice - (ProfitTargetMove * TickSize); for (int index = 0; index < quantitySelector.Value; index++) { submitOrdersArray[index].LimitPriceChanged = currentPtPrice; } myAccount.Change(submitOrdersArray); } } }, null); e.Handled = true; } #endregion #region Initial Target & StopLoss Snippets private async void Account_OrderUpdate(object sender, OrderEventArgs orderUpdateArgs) { if (entryBuyMarketOrder != null && entryBuyMarketOrder == orderUpdateArgs.Order && orderUpdateArgs.Order.OrderState == OrderState.Filled) { string oco = Guid.NewGuid().ToString("N"); submitOrdersArray = new List<Order>(); await ChartControl.Dispatcher.InvokeAsync((Action) (() => { if (UseProfitTarget) { currentPtPrice = orderUpdateArgs.AverageFillPrice + ProfitTargetDistance * TickSize; for (int index = 0; index < quantitySelector.Value; index++) { profitTargetOrder = myAccount.CreateOrder(orderUpdateArgs.Order.Instrument, OrderAction.Sell, OrderType.Limit, OrderEntry.Automated, TimeInForce.Day, orderUpdateArgs.Quantity, currentPtPrice, 0, oco+index, "Profit Target", Core.Globals.MaxDate, null); submitOrdersArray.Add(profitTargetOrder); } } if (UseStopLoss) { currentSlPrice = orderUpdateArgs.AverageFillPrice - StopLossDistance * TickSize; for (int index = 0; index < quantitySelector.Value; index++) { stopLossOrder = myAccount.CreateOrder(orderUpdateArgs.Order.Instrument, OrderAction.Sell, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Day, orderUpdateArgs.Quantity, 0, currentSlPrice, oco+index, "Stop Loss", Core.Globals.MaxDate, null); submitOrdersArray.Add(stopLossOrder); } } myAccount.Submit(submitOrdersArray); })); } // once the exit orders are closed, reset for a new entry. else if ((profitTargetOrder != null && (profitTargetOrder.OrderState == OrderState.Filled || profitTargetOrder.OrderState == OrderState.Rejected || profitTargetOrder.OrderState == OrderState.Cancelled)) || (stopLossOrder != null && (stopLossOrder.OrderState == OrderState.Filled || stopLossOrder.OrderState == OrderState.Rejected || stopLossOrder.OrderState == OrderState.Cancelled))) { entryBuyMarketOrder = null; profitTargetOrder = null; stopLossOrder = null; } } #endregion #region OnBarUpdate Prints Snippets protected override void OnBarUpdate() { if (myAccount != null && myAccount.Positions.Where(o => o.Instrument == Instrument).Count() > 0) accountPosition = myAccount.Positions.Where(o => o.Instrument == Instrument).Last(); else accountPosition = null; if (accountPosition == null) { } else { } } #endregion #region Add Controls To Toolbar private void Add_Controls_To_Toolbar() { // Use this.Dispatcher to ensure code is executed on the proper thread ChartControl.Dispatcher.InvokeAsync((Action)(() => { //Obtain the Chart on which the indicator is configured chartWindow = Window.GetWindow(this.ChartControl.Parent) as Chart; if (chartWindow == null) { Print("chartWindow == null"); return; } quantitySelector = new NinjaTrader.Gui.Tools.QuantityUpDown(); //quantitySelector.ValueChanged += On_quantitySelector_ValueChanged; quantitySelector.PreviewKeyDown += On_quantitySelector_PreviewKeyDown; chartWindow.MainMenu.Add(quantitySelector); Is_ToolBar_Controls_Added = true; quantitySelector.Value = 1; })); } #endregion #region QuantitySelector Snippets private void On_quantitySelector_PreviewKeyDown(object sender, KeyEventArgs p) { NinjaTrader.Gui.Tools.QuantityUpDown qs = sender as NinjaTrader.Gui.Tools.QuantityUpDown; // if (p.Key == Key.Insert) // { // p.Handled = true; // quantitySelector.Focus(); // } if (p.Key == Key.Delete || p.Key == Key.Back) { p.Handled = true; quantitySelector.Value = 0; } if ((p.Key >= Key.D0 && p.Key <= Key.D9 || (p.Key >= Key.NumPad0 && p.Key <= Key.NumPad9))) { p.Handled = true; string number = p.Key.ToString(); string newnumber = qs.Value.ToString(); number = number.Replace("NumPad", ""); number = number.Replace("D", ""); int num = int.Parse(newnumber + number); if (qs != null) qs.Value = num; } } #endregion #region DisposeCleanUp Snippet private void DisposeCleanUp() { //ChartWindow Null Check if (chartWindow != null) { //Dispatcher used to Assure Executed on UI Thread ChartControl.Dispatcher.InvokeAsync((Action)(() => { if( quantitySelector != null ) chartWindow.MainMenu.Remove(quantitySelector); })); } } #endregion #region Properties [TypeConverter(typeof(NinjaTrader.NinjaScript.AccountNameConverter))] [Display(Name = "Account Name", Description = "Selects The Account (from Ones Available)", Order = 1, GroupName = "#1 Account Selector")] public string AccountName { get; set; } [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name = "Profit Target Distance", Description = "Sets The ProfitTarget OCO Order Distance (in ticks)", Order = 2, GroupName = "#2 Indicator's Input Setings")] public int ProfitTargetDistance { get; set; } [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name = "Stop Loss Distance", Description = "Sets The StopLoss OCO Order Distance (in ticks)", Order = 3, GroupName = "#2 Indicator's Input Setings")] public int StopLossDistance { get; set; } [NinjaScriptProperty] [Display(Name = "Use Profit Target", Description = "Enables ProfitTarget OCO Order", Order = 4, GroupName = "#2 Indicator's Input Setings")] public bool UseProfitTarget { get; set; } [NinjaScriptProperty] [Display(Name = "Use Stop Loss", Description = "Enables StopLoss OCO Order", Order = 5, GroupName = "#2 Indicator's Input Setings")] public bool UseStopLoss { get; set; } [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name = "Profit Target Move (<= Profit Target Distance)", Description = "Sets The ProfitTarget OCO Order move (in ticks)", Order = 6, GroupName = "#2 Indicator's Input Setings")] public int ProfitTargetMove { get; set; } [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name = "Stop Loss Move (<= Stop Loss Distance)", Description = "Sets The StopLoss OCO Order move (in ticks)", Order = 7, GroupName = "#2 Indicator's Input Setings")] public int StopLossMove { get; set; } [NinjaScriptProperty] [Display(Name = "Print Details", Description = "Prints In Output Window (Debugging)", Order = 8, GroupName = "#3 Debug Mode")] public bool PrintDetails { get; set; } #endregion } } #region NinjaScript generated code. Neither change nor remove. namespace NinjaTrader.NinjaScript.Indicators { public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase { private ProfitSniper[] cacheProfitSniper; public ProfitSniper ProfitSniper(int profitTargetDistance, int stopLossDistance, bool useProfitTarget, bool useStopLoss, int profitTargetMove, int stopLossMove, bool printDetails) { return ProfitSniper(Input, profitTargetDistance, stopLossDistance, useProfitTarget, useStopLoss, profitTargetMove, stopLossMove, printDetails); } public ProfitSniper ProfitSniper(ISeries<double> input, int profitTargetDistance, int stopLossDistance, bool useProfitTarget, bool useStopLoss, int profitTargetMove, int stopLossMove, bool printDetails) { if (cacheProfitSniper != null) for (int idx = 0; idx < cacheProfitSniper.Length; idx++) if (cacheProfitSniper[idx] != null && cacheProfitSniper[idx].ProfitTargetDistance == profitTargetDistance && cacheProfitSniper[idx].StopLossDistance == stopLossDistance && cacheProfitSniper[idx].UseProfitTarget == useProfitTarget && cacheProfitSniper[idx].UseStopLoss == useStopLoss && cacheProfitSniper[idx].ProfitTargetMove == profitTargetMove && cacheProfitSniper[idx].StopLossMove == stopLossMove && cacheProfitSniper[idx].PrintDetails == printDetails && cacheProfitSniper[idx].EqualsInput(input)) return cacheProfitSniper[idx]; return CacheIndicator<ProfitSniper>(new ProfitSniper(){ ProfitTargetDistance = profitTargetDistance, StopLossDistance = stopLossDistance, UseProfitTarget = useProfitTarget, UseStopLoss = useStopLoss, ProfitTargetMove = profitTargetMove, StopLossMove = stopLossMove, PrintDetails = printDetails }, input, ref cacheProfitSniper); } } } namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns { public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase { public Indicators.ProfitSniper ProfitSniper(int profitTargetDistance, int stopLossDistance, bool useProfitTarget, bool useStopLoss, int profitTargetMove, int stopLossMove, bool printDetails) { return indicator.ProfitSniper(Input, profitTargetDistance, stopLossDistance, useProfitTarget, useStopLoss, profitTargetMove, stopLossMove, printDetails); } public Indicators.ProfitSniper ProfitSniper(ISeries<double> input , int profitTargetDistance, int stopLossDistance, bool useProfitTarget, bool useStopLoss, int profitTargetMove, int stopLossMove, bool printDetails) { return indicator.ProfitSniper(input, profitTargetDistance, stopLossDistance, useProfitTarget, useStopLoss, profitTargetMove, stopLossMove, printDetails); } } } namespace NinjaTrader.NinjaScript.Strategies { public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase { public Indicators.ProfitSniper ProfitSniper(int profitTargetDistance, int stopLossDistance, bool useProfitTarget, bool useStopLoss, int profitTargetMove, int stopLossMove, bool printDetails) { return indicator.ProfitSniper(Input, profitTargetDistance, stopLossDistance, useProfitTarget, useStopLoss, profitTargetMove, stopLossMove, printDetails); } public Indicators.ProfitSniper ProfitSniper(ISeries<double> input , int profitTargetDistance, int stopLossDistance, bool useProfitTarget, bool useStopLoss, int profitTargetMove, int stopLossMove, bool printDetails) { return indicator.ProfitSniper(input, profitTargetDistance, stopLossDistance, useProfitTarget, useStopLoss, profitTargetMove, stopLossMove, printDetails); } } } #endregion