Display distance from high/low to price
Created at 20 Sep 2021, 16:17
CT
Display distance from high/low to price
20 Sep 2021, 16:17
Hi,
I am trying to create a simple calculation wherein a downtrend, a distance is measured as HighPrices.LastValue - Price, and in an uptrend the distance is Price - LowPrices.LastValue.
Without Math.Round, I get a very long decimal. With it, I get 0.
See attached code, any advice? Thanks.
using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class SLDisplay : Indicator
{
[Parameter("MA Type", Group = "MA", DefaultValue = MovingAverageType.Simple)]
public MovingAverageType MaType { get; set; }
[Parameter("Vertical Alignment", DefaultValue = VerticalAlignment.Bottom)]
public VerticalAlignment slvAlignment { get; set; }
[Parameter("Horizontal Alignment", DefaultValue = HorizontalAlignment.Center)]
public HorizontalAlignment slhAlignment { get; set; }
private ChartStaticText details;
private string _sl;
MovingAverage FastMa;
MovingAverage SlowMa;
MovingAverage TrendMa;
protected override void Initialize()
{
details = Chart.DrawStaticText("idtext_white", string.Empty, this.slvAlignment, this.slhAlignment, Color.White);
FastMa = Indicators.MovingAverage(Bars.ClosePrices, 9, MaType);
SlowMa = Indicators.MovingAverage(Bars.ClosePrices, 21, MaType);
TrendMa = Indicators.MovingAverage(Bars.ClosePrices, 50, MaType);
}
public override void Calculate(int index)
{
_sl = GetSL();
details.Text = "SL: " + _sl;
details.Color = Color.White;
}
private string GetSL()
{
var trend = Bars.ClosePrices.LastValue > TrendMa.Result.LastValue ? true : false;
var fast = FastMa.Result.LastValue > SlowMa.Result.LastValue ? true : false;
var price = (Symbol.Ask + Symbol.Bid) / 2;
var distance = 0.0;
var buyorsell = trend && fast ? true : false;
if (buyorsell)
{
distance = (price - Bars.LowPrices.LastValue) * Symbol.PipSize;
}
if (!buyorsell)
{
distance = (Bars.HighPrices.LastValue - price) * Symbol.PipSize;
}
if (distance < 0.1)
{
return "N/A";
}
else
return Math.Round(distance, 1).ToString();
//return distance.ToString();
}
}
}
Replies
PanagiotisCharalampous
21 Sep 2021, 08:43
Hi ctid4633759,
Why do you multiply by the PipSize? Did you intend to divide instead?
Best Regards,
Panagiotis
Join us on Telegram and Facebook
@PanagiotisCharalampous
firemyst
21 Sep 2021, 03:38
RE:
ctid4633759 said:
One suggestion in your code. If you want your code to be dynamic and always round to the number of places based on the symbol you're watching, I would do:
Math.Round(distance, Symbol.Digits)
instead. So for example, if you're trading the EURUSD, it'll round to 4 digits; if trading any JPY pairs, it'll round to 2 digits; if trading the DOW or DAX, it'll round to 1 digit, etc etc.
That aside, you should read this on how to format decimal string numbers in C#:
@firemyst