Advertisement
Guest User

Untitled

a guest
Mar 28th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.80 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. using System.Windows.Controls;
  23. #endregion
  24.  
  25. //This namespace holds Indicators in this folder and is required. Do not change it.
  26. namespace NinjaTrader.NinjaScript.Indicators
  27. {
  28. public class AlansPositionSizeLevelCalculator : Indicator
  29. {
  30.  
  31. private Grid GridLayout;
  32. private Button LongButton;
  33. private Button ShortButton;
  34. private Button ClearButton;
  35.  
  36. protected override void OnStateChange()
  37. {
  38. if (State == State.SetDefaults)
  39. {
  40. Description = @"Calculates the position size and entry levels given two horizontal lines";
  41. Name = "AlansPositionSizeLevelCalculator";
  42. Calculate = Calculate.OnBarClose;
  43. IsOverlay = true;
  44. DisplayInDataBox = true;
  45. DrawOnPricePanel = true;
  46. DrawHorizontalGridLines = true;
  47. DrawVerticalGridLines = true;
  48. PaintPriceMarkers = true;
  49. ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
  50. //Disable this property if your indicator requires custom values that cumulate with each new market data event.
  51. //See Help Guide for additional information.
  52. IsSuspendedWhileInactive = true;
  53. AccountSize = 10000;
  54. RiskPercentage = 3;
  55. StopLossDistanceMultiplier = 2;
  56. LevelsCount = 5;
  57. }
  58. else if (State == State.Historical)
  59. {
  60. Initiate();
  61. }
  62. }
  63.  
  64. private void Initiate()
  65. {
  66. ClearOutputWindow();
  67. Print("Position Size/Level Calculator is loaded");
  68. UI();
  69. }
  70.  
  71. private void CalculateAll(bool IsLong) {
  72. List<IDrawingTool> HorizontalLines = DrawObjects.ToList().FindAll(Drawing => {
  73. if (Drawing.Tag.StartsWith("Generated-Line")) {
  74. RemoveDrawObject(Drawing.Tag);
  75. return false;
  76. }
  77. return Drawing is DrawingTools.HorizontalLine;
  78. });
  79. if (HorizontalLines.Count != 2) {
  80. Print("You must have exactly 2 horizontal lines on the chart to make this calculation.");
  81. return;
  82. }
  83.  
  84. double PriceA = HorizontalLines[0].Anchors.ElementAt(0).Price;
  85. double PriceB = HorizontalLines[1].Anchors.ElementAt(0).Price;
  86.  
  87. if (PriceB > PriceA) {
  88. double Temp = PriceB;
  89. PriceB = PriceA;
  90. PriceA = Temp;
  91. }
  92.  
  93. CalculateLevels(PriceA, PriceB, IsLong);
  94. }
  95.  
  96. private void CalculateLevels(double PriceA, double PriceB, bool IsLong) {
  97. ClearOutputWindow();
  98. Print("");
  99.  
  100. if (!IsLong) {
  101. double Temp = PriceB;
  102. PriceB = PriceA;
  103. PriceA = Temp;
  104. }
  105.  
  106. double Price, PositionSize;
  107. double DeltaPrice = (PriceB - PriceA) / (LevelsCount - 1);
  108. double StopLossPrice = PriceB + DeltaPrice * StopLossDistanceMultiplier;
  109. Print(" | Price | Pos'n Sz");
  110. for (int i = (IsLong ? 0 : LevelsCount - 1); (IsLong ? i < LevelsCount : i >= 0); i += IsLong ? 1 : -1) {
  111. Price = PriceA + DeltaPrice * i;
  112. PositionSize = CalculatePositionSize(PriceA, DeltaPrice, StopLossPrice, i + 1, IsLong);
  113. // Print(" Level " + (i + 1) + ": " + ToRoundedString(Price) + " | Position Size: $" + PositionSize.ToString("N2"));
  114. Print(String.Format(" L{0,-3} | {1,-8} | {2}", (i + 1), ToRoundedString(Price), PositionSize.ToString("N0")));
  115.  
  116. Draw.HorizontalLine(this, "Generated-Line-Level-" + (i + 1), false, Price, Brushes.Black, DashStyleHelper.Solid, 4);
  117. }
  118. Draw.HorizontalLine(this, "Generated-Line-Stop-Loss", false, StopLossPrice, Brushes.Red, DashStyleHelper.Solid, 4);
  119.  
  120. Print("");
  121. Print("Stop Loss: " + ToRoundedString(StopLossPrice));
  122. }
  123.  
  124. private double CalculatePositionSize(double PriceA, double DeltaPrice, double StopLossPrice, double LevelsCount, bool IsLong) {
  125. double EntryLevelDistance = Math.Abs(DeltaPrice);
  126. double RiskCapital = AccountSize * RiskPercentage / 100;
  127. double PipValue = GetPipValue(PriceA);
  128. double StrangeNumber = IsLong ? PriceA - StopLossPrice : StopLossPrice - PriceA;
  129. double StrangeSumA = 0;
  130. double StrangeSumB = 0;
  131. for (int i = 1; i <= LevelsCount; i++) {
  132. StrangeSumA += i;
  133. StrangeSumB += i * (i - 1);
  134. }
  135. return RiskCapital / (PipValue * ((StrangeNumber) * StrangeSumA - EntryLevelDistance * StrangeSumB));
  136. }
  137.  
  138. private double GetPipValue(double FirstEntryPrice) {
  139. if (Instrument.FullName.EndsWith("USD")) return 10;
  140. return 10 / FirstEntryPrice;
  141. }
  142.  
  143. private String ToRoundedString(double value) {
  144. int Precision = 5;
  145. if (Instrument.FullName.Contains("JPY")) Precision = 3;
  146. return value.ToString("N" + Precision);
  147. }
  148.  
  149. private void UI() {
  150. ChartControl.Dispatcher.InvokeAsync(() => {
  151. if (UserControlCollection.Contains(GridLayout)) return;
  152. GridLayout = new Grid{
  153. Name = "GridLayout",
  154. HorizontalAlignment = HorizontalAlignment.Right,
  155. VerticalAlignment = VerticalAlignment.Bottom,
  156. };
  157. GridLayout.ColumnDefinitions.Add(new ColumnDefinition());
  158. GridLayout.ColumnDefinitions.Add(new ColumnDefinition());
  159. GridLayout.ColumnDefinitions.Add(new ColumnDefinition());
  160.  
  161. Brush Foreground = Brushes.White;
  162. int FontSize = 10;
  163.  
  164. LongButton = new Button {
  165. Name = "LongButton",
  166. Content = "LONG",
  167. Foreground = Foreground,
  168. Background = Brushes.LimeGreen,
  169. FontSize = FontSize
  170. };
  171.  
  172. ShortButton = new Button {
  173. Name = "ShortButton",
  174. Content = "SHORT",
  175. Foreground = Foreground,
  176. Background = Brushes.Salmon,
  177. FontSize = FontSize
  178. };
  179.  
  180. ClearButton = new Button {
  181. Name = "ClearButton",
  182. Content = "CLEAR",
  183. Foreground = Foreground,
  184. Background = Brushes.DarkGray,
  185. FontSize = FontSize
  186. };
  187.  
  188. LongButton.Click += OnLongButtonClick;
  189. ShortButton.Click += OnShortButtonClick;
  190. ClearButton.Click += OnClearButtonClick;
  191.  
  192. Grid.SetColumn(LongButton, 0);
  193. Grid.SetColumn(ShortButton, 1);
  194. Grid.SetColumn(ClearButton, 2);
  195.  
  196. GridLayout.Children.Add(LongButton);
  197. GridLayout.Children.Add(ShortButton);
  198. GridLayout.Children.Add(ClearButton);
  199.  
  200. UserControlCollection.Add(GridLayout);
  201. });
  202. }
  203.  
  204. private void OnLongButtonClick(object Sender, RoutedEventArgs EventArgs) {
  205. CalculateAll(true);
  206. }
  207.  
  208. private void OnShortButtonClick(object Sender, RoutedEventArgs EventArgs) {
  209. CalculateAll(false);
  210. }
  211.  
  212. private void OnClearButtonClick(object Sender, RoutedEventArgs EventArgs) {
  213. ClearOutputWindow();
  214. DrawObjects.ToList().ForEach(Drawing => {
  215. if (Drawing.Tag.StartsWith("Generated-Line")) RemoveDrawObject(Drawing.Tag);
  216. });
  217. Print("Cleared calculated levels");
  218. }
  219.  
  220. #region Properties
  221. [NinjaScriptProperty]
  222. [Range(1000, double.MaxValue)]
  223. [Display(Name="AccountSize", Order=1, GroupName="Parameters")]
  224. public double AccountSize
  225. { get; set; }
  226.  
  227. [NinjaScriptProperty]
  228. [Range(0.01, double.MaxValue)]
  229. [Display(Name="RiskPercentage", Order=2, GroupName="Parameters")]
  230. public double RiskPercentage
  231. { get; set; }
  232.  
  233. [NinjaScriptProperty]
  234. [Range(0, double.MaxValue)]
  235. [Display(Name="StopLossDistanceMultiplier", Order=3, GroupName="Parameters")]
  236. public double StopLossDistanceMultiplier
  237. { get; set; }
  238.  
  239. [NinjaScriptProperty]
  240. [Range(2, int.MaxValue)]
  241. [Display(Name="LevelsCount", Order=4, GroupName="Parameters")]
  242. public int LevelsCount
  243. { get; set; }
  244. #endregion
  245.  
  246. }
  247. }
  248.  
  249. #region NinjaScript generated code. Neither change nor remove.
  250.  
  251. namespace NinjaTrader.NinjaScript.Indicators
  252. {
  253. public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
  254. {
  255. private AlansPositionSizeLevelCalculator[] cacheAlansPositionSizeLevelCalculator;
  256. public AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
  257. {
  258. return AlansPositionSizeLevelCalculator(Input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
  259. }
  260.  
  261. public AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(ISeries<double> input, double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
  262. {
  263. if (cacheAlansPositionSizeLevelCalculator != null)
  264. for (int idx = 0; idx < cacheAlansPositionSizeLevelCalculator.Length; idx++)
  265. if (cacheAlansPositionSizeLevelCalculator[idx] != null && cacheAlansPositionSizeLevelCalculator[idx].AccountSize == accountSize && cacheAlansPositionSizeLevelCalculator[idx].RiskPercentage == riskPercentage && cacheAlansPositionSizeLevelCalculator[idx].StopLossDistanceMultiplier == stopLossDistanceMultiplier && cacheAlansPositionSizeLevelCalculator[idx].LevelsCount == levelsCount && cacheAlansPositionSizeLevelCalculator[idx].EqualsInput(input))
  266. return cacheAlansPositionSizeLevelCalculator[idx];
  267. return CacheIndicator<AlansPositionSizeLevelCalculator>(new AlansPositionSizeLevelCalculator(){ AccountSize = accountSize, RiskPercentage = riskPercentage, StopLossDistanceMultiplier = stopLossDistanceMultiplier, LevelsCount = levelsCount }, input, ref cacheAlansPositionSizeLevelCalculator);
  268. }
  269. }
  270. }
  271.  
  272. namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
  273. {
  274. public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
  275. {
  276. public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
  277. {
  278. return indicator.AlansPositionSizeLevelCalculator(Input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
  279. }
  280.  
  281. public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(ISeries<double> input , double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
  282. {
  283. return indicator.AlansPositionSizeLevelCalculator(input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
  284. }
  285. }
  286. }
  287.  
  288. namespace NinjaTrader.NinjaScript.Strategies
  289. {
  290. public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
  291. {
  292. public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
  293. {
  294. return indicator.AlansPositionSizeLevelCalculator(Input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
  295. }
  296.  
  297. public Indicators.AlansPositionSizeLevelCalculator AlansPositionSizeLevelCalculator(ISeries<double> input , double accountSize, double riskPercentage, double stopLossDistanceMultiplier, int levelsCount)
  298. {
  299. return indicator.AlansPositionSizeLevelCalculator(input, accountSize, riskPercentage, stopLossDistanceMultiplier, levelsCount);
  300. }
  301. }
  302. }
  303.  
  304. #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement