Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- using System.Windows.Controls;
- #endregion
- //This namespace holds Indicators in this folder and is required. Do not change it.
- namespace NinjaTrader.NinjaScript.Indicators
- {
- public class AlansPositionSizeLevelCalculator : Indicator
- {
- private Grid GridLayout;
- private Button LongButton;
- private Button ShortButton;
- private Button ClearButton;
- protected override void OnStateChange()
- {
- if (State == State.SetDefaults)
- {
- Description = @"Calculates the position size and entry levels given two horizontal lines";
- Name = "AlansPositionSizeLevelCalculator";
- 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 = true;
- AccountSize = 10000;
- RiskPercentage = 3;
- StopLossDistanceMultiplier = 2;
- LevelsCount = 5;
- }
- else if (State == State.Historical)
- {
- Initiate();
- }
- }
- private void Initiate()
- {
- ClearOutputWindow();
- Print("Position Size/Level Calculator is loaded");
- UI();
- }
- private void CalculateAll(bool IsLong) {
- List<IDrawingTool> HorizontalLines = DrawObjects.ToList().FindAll(Drawing => {
- if (Drawing.Tag.StartsWith("Generated-Line")) {
- RemoveDrawObject(Drawing.Tag);
- return false;
- }
- return Drawing is DrawingTools.HorizontalLine;
- });
- if (HorizontalLines.Count != 2) {
- Print("You must have exactly 2 horizontal lines on the chart to make this calculation.");
- return;
- }
- double PriceA = HorizontalLines[0].Anchors.ElementAt(0).Price;
- double PriceB = HorizontalLines[1].Anchors.ElementAt(0).Price;
- if (PriceB > PriceA) {
- double Temp = PriceB;
- PriceB = PriceA;
- PriceA = Temp;
- }
- CalculateLevels(PriceA, PriceB, IsLong);
- }
- private void CalculateLevels(double PriceA, double PriceB, bool IsLong) {
- ClearOutputWindow();
- Print("");
- if (!IsLong) {
- double Temp = PriceB;
- PriceB = PriceA;
- PriceA = Temp;
- }
- double Price, PositionSize;
- double DeltaPrice = (PriceB - PriceA) / (LevelsCount - 1);
- double StopLossPrice = PriceB + DeltaPrice * StopLossDistanceMultiplier;
- Print(" | Price | Pos'n Sz");
- for (int i = (IsLong ? 0 : LevelsCount - 1); (IsLong ? i < LevelsCount : i >= 0); i += IsLong ? 1 : -1) {
- Price = PriceA + DeltaPrice * i;
- PositionSize = CalculatePositionSize(PriceA, DeltaPrice, StopLossPrice, i + 1, IsLong);
- // Print(" Level " + (i + 1) + ": " + ToRoundedString(Price) + " | Position Size: $" + PositionSize.ToString("N2"));
- Print(String.Format(" L{0,-3} | {1,-8} | {2}", (i + 1), ToRoundedString(Price), PositionSize.ToString("N0")));
- Draw.HorizontalLine(this, "Generated-Line-Level-" + (i + 1), false, Price, Brushes.Black, DashStyleHelper.Solid, 4);
- }
- Draw.HorizontalLine(this, "Generated-Line-Stop-Loss", false, StopLossPrice, Brushes.Red, DashStyleHelper.Solid, 4);
- Print("");
- Print("Stop Loss: " + ToRoundedString(StopLossPrice));
- }
- private double CalculatePositionSize(double PriceA, double DeltaPrice, double StopLossPrice, double LevelsCount, bool IsLong) {
- double EntryLevelDistance = Math.Abs(DeltaPrice);
- double RiskCapital = AccountSize * RiskPercentage / 100;
- double PipValue = GetPipValue(PriceA);
- double StrangeNumber = IsLong ? PriceA - StopLossPrice : StopLossPrice - PriceA;
- double StrangeSumA = 0;
- double StrangeSumB = 0;
- for (int i = 1; i <= LevelsCount; i++) {
- StrangeSumA += i;
- StrangeSumB += i * (i - 1);
- }
- return RiskCapital / (PipValue * ((StrangeNumber) * StrangeSumA - EntryLevelDistance * StrangeSumB));
- }
- private double GetPipValue(double FirstEntryPrice) {
- if (Instrument.FullName.EndsWith("USD")) return 10;
- return 10 / FirstEntryPrice;
- }
- private String ToRoundedString(double value) {
- int Precision = 5;
- if (Instrument.FullName.Contains("JPY")) Precision = 3;
- return value.ToString("N" + Precision);
- }
- private void UI() {
- ChartControl.Dispatcher.InvokeAsync(() => {
- if (UserControlCollection.Contains(GridLayout)) return;
- GridLayout = new Grid{
- Name = "GridLayout",
- HorizontalAlignment = HorizontalAlignment.Right,
- VerticalAlignment = VerticalAlignment.Bottom,
- };
- GridLayout.ColumnDefinitions.Add(new ColumnDefinition());
- GridLayout.ColumnDefinitions.Add(new ColumnDefinition());
- GridLayout.ColumnDefinitions.Add(new ColumnDefinition());
- Brush Foreground = Brushes.White;
- int FontSize = 10;
- LongButton = new Button {
- Name = "LongButton",
- Content = "LONG",
- Foreground = Foreground,
- Background = Brushes.LimeGreen,
- FontSize = FontSize
- };
- ShortButton = new Button {
- Name = "ShortButton",
- Content = "SHORT",
- Foreground = Foreground,
- Background = Brushes.Salmon,
- FontSize = FontSize
- };
- ClearButton = new Button {
- Name = "ClearButton",
- Content = "CLEAR",
- Foreground = Foreground,
- Background = Brushes.DarkGray,
- FontSize = FontSize
- };
- LongButton.Click += OnLongButtonClick;
- ShortButton.Click += OnShortButtonClick;
- ClearButton.Click += OnClearButtonClick;
- Grid.SetColumn(LongButton, 0);
- Grid.SetColumn(ShortButton, 1);
- Grid.SetColumn(ClearButton, 2);
- GridLayout.Children.Add(LongButton);
- GridLayout.Children.Add(ShortButton);
- GridLayout.Children.Add(ClearButton);
- UserControlCollection.Add(GridLayout);
- });
- }
- private void OnLongButtonClick(object Sender, RoutedEventArgs EventArgs) {
- CalculateAll(true);
- }
- private void OnShortButtonClick(object Sender, RoutedEventArgs EventArgs) {
- CalculateAll(false);
- }
- private void OnClearButtonClick(object Sender, RoutedEventArgs EventArgs) {
- ClearOutputWindow();
- DrawObjects.ToList().ForEach(Drawing => {
- if (Drawing.Tag.StartsWith("Generated-Line")) RemoveDrawObject(Drawing.Tag);
- });
- Print("Cleared calculated levels");
- }
- #region Properties
- [NinjaScriptProperty]
- [Range(1000, double.MaxValue)]
- [Display(Name="AccountSize", Order=1, GroupName="Parameters")]
- public double AccountSize
- { get; set; }
- [NinjaScriptProperty]
- [Range(0.01, double.MaxValue)]
- [Display(Name="RiskPercentage", Order=2, GroupName="Parameters")]
- public double RiskPercentage
- { get; set; }
- [NinjaScriptProperty]
- [Range(0, double.MaxValue)]
- [Display(Name="StopLossDistanceMultiplier", Order=3, GroupName="Parameters")]
- public double StopLossDistanceMultiplier
- { get; set; }
- [NinjaScriptProperty]
- [Range(2, int.MaxValue)]
- [Display(Name="LevelsCount", Order=4, GroupName="Parameters")]
- public int LevelsCount
- { get; set; }
- #endregion
- }
- }
- #region NinjaScript generated code. Neither change nor remove.
- namespace NinjaTrader.NinjaScript.Indicators
- {
- public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
- {
- private AlansPositionSizeLevelCalculator[] cacheAlansPositionSizeLevelCalculator;
- public AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
- {
- return AlansPositionSizeLevelCalculator(Input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
- }
- public AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(ISeries<double> input, double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
- {
- if (cacheAlansPositionSizeLevelCalculator != null)
- for (int idx = 0; idx < cacheAlansPositionSizeLevelCalculator.Length; idx++)
- if (cacheAlansPositionSizeLevelCalculator[idx] != null && cacheAlansPositionSizeLevelCalculator[idx].AccountSize == accountSize && cacheAlansPositionSizeLevelCalculator[idx].RiskPercentage == riskPercentage && cacheAlansPositionSizeLevelCalculator[idx].StopLossDistanceMultiplier == stopLossDistanceMultiplier && cacheAlansPositionSizeLevelCalculator[idx].LevelsCount == levelsCount && cacheAlansPositionSizeLevelCalculator[idx].EqualsInput(input))
- return cacheAlansPositionSizeLevelCalculator[idx];
- return CacheIndicator<AlansPositionSizeLevelCalculator>(new AlansPositionSizeLevelCalculator(){ AccountSize = accountSize, RiskPercentage = riskPercentage, StopLossDistanceMultiplier = stopLossDistanceMultiplier, LevelsCount = levelsCount }, input, ref cacheAlansPositionSizeLevelCalculator);
- }
- }
- }
- namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
- {
- public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
- {
- public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
- {
- return indicator.AlansPositionSizeLevelCalculator(Input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
- }
- public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(ISeries<double> input , double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
- {
- return indicator.AlansPositionSizeLevelCalculator(input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
- }
- }
- }
- namespace NinjaTrader.NinjaScript.Strategies
- {
- public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
- {
- public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
- {
- return indicator.AlansPositionSizeLevelCalculator(Input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
- }
- public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(ISeries<double> input , double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
- {
- return indicator.AlansPositionSizeLevelCalculator(input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
- }
- }
- }
- #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement