Category Other  Published on 18/05/2023

Free Risk Reward Tool

Description

This is a Free and Best Risk Reward tool that you will get on this platform at the moment for free. So feel free to download it and share this link with your comunity, make videos and have fun and a lot of money.

 

You can find me by joyining this Telegram Group http://t.me/cTraderCoders

Grupo de Telegram Para Brasileiros, Portugueses e todos aqueles que falam portugues: http://t.me/ComunidadeCtrader

Grupo CTrader en Español para Latinos:  http://t.me/ComunidadCtrader

 

 


using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class RiskReward : Indicator
    {

        [Parameter("Lots / Units", Group = "Position & Sizing", DefaultValue = 1.0, MinValue = 0.01)]
        public double Lots { get; set; }

        [Parameter("Percentage Risk %", Group = "Position & Sizing", DefaultValue = 1.0, MinValue = 0.1, MaxValue = 100)]
        public double PctRisk { get; set; }

        [Parameter("Show Dashboard", Group = "Dashboard Settings", DefaultValue = true)]
        public bool showDashboard { get; set; }

        [Parameter("Reward Color", Group = "Risk Reward Grapic Settings", DefaultValue = Colors.Green)]
        public Colors RewardColor { get; set; }

        [Parameter("Risk Color", Group = "Risk Reward Grapic Settings", DefaultValue = Colors.Red)]
        public Colors RiskColor { get; set; }

        [Parameter("Reward Opacity", Group = "Risk Reward Grapic Settings", DefaultValue = 30, MinValue = 5, MaxValue = 100)]
        public int RewardOpacity { get; set; }

        [Parameter("Risk Opacity", Group = "Risk Reward Grapic Settings", DefaultValue = 30, MinValue = 5, MaxValue = 100)]
        public int RiskOpacity { get; set; }

        [Parameter("Text Color", Group = "Risk Reward Grapic Settings", DefaultValue = Colors.White)]
        public Colors TextColor { get; set; }

        [Parameter("Long Line Color", Group = "Entry Lines Grapic Settings", DefaultValue = Colors.LawnGreen)]
        public Colors LongLineColor { get; set; }

        [Parameter("Short Line Color", Group = "Entry Lines Grapic Settings", DefaultValue = Colors.Red)]
        public Colors ShortLineColor { get; set; }

        [Parameter("Line Style", Group = "Entry Lines Grapic Settings", DefaultValue = LineStyle.Lines)]
        public LineStyle EntryLineStyle { get; set; }

        [Parameter("Line Size", Group = "Entry Lines Grapic Settings", DefaultValue = 1, MinValue = 1, MaxValue = 5)]
        public int EntryLineSize { get; set; }




        List<RRConstructor> boxes = new List<RRConstructor>();
        public ChartRectangle BullRR;
        public ChartRectangle BullReward;
        public ChartRectangle BullRisk;
        public ChartHorizontalLine BullLine;
        public ChartRectangle BearRR;
        public ChartRectangle BearReward;
        public ChartRectangle BearRisk;
        public ChartHorizontalLine BearLine;
        private double PixelPrice;
        private double TargetRiskBoxPixels;
        private double costPerPip;
        private int DecimalCount;
        private string CurrencyName;
        public Color RewardColorRect;
        public Color RiskColorRect;
        public ToggleButton ShowPanel;
        public StackPanel panel;
        public Border panelBorder;
        public TextBlock text1;
        public TextBlock text2;
        public TextBlock text3;
        public TextBlock text4;
        public TextBlock text5;
        public TextBlock text6;
        public TextBlock text7;
        public double PositionSizeData;
        public string RiskRewardValue = "";
        public string PositionType = "";
        public string lastObjName;
        public string lastObjID;
        public string lastObjDirection;
        public double lastObjRectY1;
        public double lastObjRectY2;
        public double lastHorizontalLineY;
        public double lastHLineToRiskDistance;
        public double lastHLineToRewardDistance;

        public static Dictionary<string, string> Currencies = new Dictionary<string, string> 
        {
            {
                "AUD",
                "$"
            },
            {
                "CHF",
                "fr."
            },
            {
                "EUR",
                "€"
            },
            {
                "GBP",
                "£"
            },
            {
                "HKD",
                "HK$"
            },
            {
                "NZD",
                "$"
            },
            {
                "SEK",
                "kr"
            },
            {
                "USD",
                "$"
            },
            {
                "ZAR",
                "R"
            },
            {
                "CAD",
                "$"
            },
            {
                "CNY",
                "¥"
            },
            {
                "MXN",
                "$"
            },
            {
                "SGD",
                "$"
            },
            {
                "JPY",
                "¥"
            }
        };

        protected override void Initialize()
        {

            getCostPerPip();
            PctRisk = PctRisk / 100;
            if (Currencies.ContainsKey(Account.Asset.Name))
            {
                string val = Currencies[Account.Asset.Name];
                CurrencyName = val;
            }
            else
            {
                CurrencyName = Account.Asset.Name;
            }
            ShowPanel = new ToggleButton 
            {
                Width = 60,
                Height = 25,
                Text = "Show",
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = "20 110 0 0",
                BackgroundColor = Color.FromHex("FFBF9100"),
                FontWeight = FontWeight.DemiBold
            };
            Chart.AddControl(ShowPanel);
            DrawDashBoard();
            ShowPanel.Checked += OnShowPanelChecked;
            ShowPanel.Unchecked += OnShowPanelUnchecked;
            RewardOpacity = RewardOpacity > 100 ? 100 : RewardOpacity < 0 ? 0 : RewardOpacity;
            RewardOpacity = (int)(2.55 * RewardOpacity);
            RiskOpacity = RiskOpacity > 100 ? 100 : RiskOpacity < 0 ? 0 : RiskOpacity;
            RiskOpacity = (int)(2.55 * RiskOpacity);
            RewardColorRect = Color.FromArgb(RewardOpacity, Color.FromName(RewardColor.ToString()).R, Color.FromName(RewardColor.ToString()).G, Color.FromName(RewardColor.ToString()).B);
            RiskColorRect = Color.FromArgb(RiskOpacity, Color.FromName(RiskColor.ToString()).R, Color.FromName(RiskColor.ToString()).G, Color.FromName(RiskColor.ToString()).B);
            decimal argument = Convert.ToDecimal(Symbol.TickSize);
            DecimalCount = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];
            GetPixelsPrice();
            var data = DateTime.UtcNow.ToString();
            var str = "Short Line " + MD5Hash(data);
            var part = str.Substring(11, 32);
            FindLongRectangles();
            FindShortRectangles();
            Border border = new Border 
            {
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = "20 40 20 20",
                Width = 50,
                Child = new ToolBar(this)
            };
            Chart.AddControl(border);
            Border border2 = new Border 
            {
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = "20 70 20 20",
                Width = 50,
                Child = new ToolBar2(this)
            };
            Chart.AddControl(border2);
            Chart.ObjectUpdated += OnChartObjectUpdated;
            Chart.ObjectRemoved += OnChartObjectRemoved;
            Chart.ObjectSelectionChanged += OnChartObjectSelectionChanged;
            Chart.ObjectAdded += OnChartObjectAdded;
        }

        void OnChartObjectAdded(ChartObjectAddedEventArgs obj)
        {
            if (obj.ChartObject.ObjectType == ChartObjectType.Rectangle && obj.ChartObject.Name.Contains("Long Rectangle"))
            {
                var ObjId = obj.ChartObject.Name.Substring(15, 32);
                lastObjName = obj.ChartObject.Name;
                lastObjID = ObjId;
                lastObjDirection = "Buy";
                var rect = (ChartRectangle)obj.ChartObject;
                var hline = (ChartHorizontalLine)Chart.FindObject("Long Line " + ObjId);
                lastObjRectY1 = rect.Y1;
                lastObjRectY2 = rect.Y2;
                lastHLineToRiskDistance = hline.Y - rect.Y1;
                lastHLineToRewardDistance = rect.Y2 - hline.Y;
            }
            else if (obj.ChartObject.ObjectType == ChartObjectType.Rectangle && obj.ChartObject.Name.Contains("Short Rectangle"))
            {
                var ObjId = obj.ChartObject.Name.Substring(16, 32);
                lastObjName = obj.ChartObject.Name;
                lastObjID = ObjId;
                lastObjDirection = "Sell";
                var rect = (ChartRectangle)obj.ChartObject;
                var hline = (ChartHorizontalLine)Chart.FindObject("Short Line " + ObjId);
                lastObjRectY1 = rect.Y1;
                lastObjRectY2 = rect.Y2;

                lastHLineToRiskDistance = rect.Y2 - hline.Y;
                lastHLineToRewardDistance = hline.Y - rect.Y1;

            }
        }

        void OnChartObjectSelectionChanged(ChartObjectSelectionChangedEventArgs obj)
        {
            if (obj.IsObjectSelected && obj.ChartObject.ObjectType == ChartObjectType.Rectangle && obj.ChartObject.Name.Contains("Long Rectangle"))
            {
                var ObjId = obj.ChartObject.Name.Substring(15, 32);
                var bullLine = (ChartHorizontalLine)Chart.FindObject("Long Line " + ObjId);
                var bullRect = (ChartRectangle)obj.ChartObject;
                lastObjName = obj.ChartObject.Name;
                lastObjID = ObjId;
                lastObjDirection = "Buy";
                lastObjRectY1 = bullRect.Y1;
                lastObjRectY2 = bullRect.Y2;
                lastHLineToRiskDistance = bullLine.Y - bullRect.Y1;
                lastHLineToRewardDistance = bullRect.Y2 - bullLine.Y;
                var pips = Math.Round(Math.Abs((bullRect.Y1 - bullLine.Y) / Symbol.PipSize), 2);
                var PositionSize = (Account.Equity * PctRisk) / (pips * Symbol.PipValue);
                PositionSize = Symbol.NormalizeVolumeInUnits(PositionSize, RoundingMode.Down);
                PositionSizeData = Symbol.VolumeInUnitsToQuantity(PositionSize);
                text5.Text = "Position Size:  " + PositionSizeData;
                var reward = bullRect.Y2 - bullLine.Y;
                var risk = bullLine.Y - bullRect.Y1;
                var RRdata = RiskRewardRatio(reward, risk);
                text6.Text = RRdata;
                text7.Text = "Position Type: " + "Long/Buy";
            }
            else if (obj.IsObjectSelected && obj.ChartObject.ObjectType == ChartObjectType.Rectangle && obj.ChartObject.Name.Contains("Short Rectangle"))
            {
                var ObjId = obj.ChartObject.Name.Substring(16, 32);
                var bearLine = (ChartHorizontalLine)Chart.FindObject("Short Line " + ObjId);
                var bearRect = (ChartRectangle)obj.ChartObject;
                lastObjName = obj.ChartObject.Name;
                lastObjID = ObjId;
                lastObjDirection = "Sell";
                lastObjRectY1 = bearRect.Y1;
                lastObjRectY2 = bearRect.Y2;
                lastHLineToRiskDistance = bearRect.Y2 - bearLine.Y;
                lastHLineToRewardDistance = bearLine.Y - bearRect.Y1;
                var pips = Math.Round(Math.Abs((bearRect.Y1 - bearLine.Y) / Symbol.PipSize), 2);
                var PositionSize = (Account.Equity * PctRisk) / (pips * Symbol.PipValue);
                PositionSize = Symbol.NormalizeVolumeInUnits(PositionSize, RoundingMode.Down);
                PositionSizeData = Symbol.VolumeInUnitsToQuantity(PositionSize);
                text5.Text = "Position Size:  " + PositionSizeData;
                var reward = bearLine.Y - bearRect.Y1;
                var risk = bearRect.Y2 - bearLine.Y;
                var RRdata = RiskRewardRatio(reward, risk);
                text6.Text = RRdata;
                text7.Text = "Position Type: " + "Short/Sell";
            }
        }

        void OnShowPanelUnchecked(ToggleButtonEventArgs obj)
        {

            obj.ToggleButton.Text = "Show";
            Chart.RemoveControl(panelBorder);
        }

        void OnShowPanelChecked(ToggleButtonEventArgs obj)
        {
            obj.ToggleButton.Text = "Hide";
            Chart.AddControl(panelBorder);
        }
        public void DrawDashBoard()
        {
            panel = new StackPanel 
            {
                Orientation = Orientation.Vertical,
                Width = 170,
                Height = 170,
                BackgroundColor = "#BE262626"
            };

            text1 = new TextBlock 
            {
                Text = "Symbol: " + Symbol.Name,
                Margin = "0 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            text2 = new TextBlock 
            {
                Text = "Lots/Units:  " + Lots,
                Margin = "8 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold
            };
            text3 = new TextBlock 
            {
                Text = "Capital to Risk:  " + (PctRisk * 100) + "%",
                Margin = "8 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold
            };
            text4 = new TextBlock 
            {
                Text = "Price per Pip:   " + Math.Round(costPerPip, 4) + CurrencyName,
                Margin = "8 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold
            };
            text5 = new TextBlock 
            {
                Text = "Position Size:  " + "",
                Margin = "8 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold
            };
            text6 = new TextBlock 
            {
                Text = "Risk Reward Ratio: " + "",
                Margin = "8 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold
            };
            text7 = new TextBlock 
            {
                Text = "Position Type: ",
                Margin = "8 8 0 0",
                ForegroundColor = Color.White,
                FontWeight = FontWeight.DemiBold
            };
            panel.AddChild(text1);
            panel.AddChild(text2);
            panel.AddChild(text3);
            panel.AddChild(text4);
            panel.AddChild(text5);
            panel.AddChild(text6);
            panel.AddChild(text7);
            panelBorder = new Border 
            {
                Child = panel,
                BorderColor = Color.FromHex("FF999999"),
                BorderThickness = 1,
                Opacity = 0.8,
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = "20 150 0 0"
            };
        }

        void OnChartObjectRemoved(ChartObjectRemovedEventArgs obj)
        {
            if (obj.ChartObject.Name.Contains("Long Rectangle"))
            {
                var ObjName = obj.ChartObject.Name;
                var ObjId = ObjName.Substring(15, 32);
                Chart.RemoveObject("Bull Reward " + ObjId);
                Chart.RemoveObject("Bull Risk " + ObjId);
                Chart.RemoveObject("Long Line " + ObjId);
                Chart.RemoveObject("Long Target Text " + ObjId);
                Chart.RemoveObject("Long Stop Text " + ObjId);
            }
            else if (obj.ChartObject.Name.Contains("Short Rectangle"))
            {
                var ObjName = obj.ChartObject.Name;
                var ObjId = ObjName.Substring(16, 32);
                Chart.RemoveObject("Bear Reward " + ObjId);
                Chart.RemoveObject("Bear Risk " + ObjId);
                Chart.RemoveObject("Short Line " + ObjId);
                Chart.RemoveObject("Short Target Text " + ObjId);
                Chart.RemoveObject("Short Stop Text " + ObjId);
            }
            else if (obj.ChartObject.Name.Contains("Long Line"))
            {
                var ObjName = obj.ChartObject.Name;
                var ObjId = ObjName.Substring(10, 32);
                Chart.RemoveObject("Bull Reward " + ObjId);
                Chart.RemoveObject("Bull Risk " + ObjId);
                Chart.RemoveObject("Long Rectangle " + ObjId);
                Chart.RemoveObject("Long Target Text " + ObjId);
                Chart.RemoveObject("Long Stop Text " + ObjId);
            }
            else if (obj.ChartObject.Name.Contains("Short Line"))
            {
                var ObjName = obj.ChartObject.Name;
                var ObjId = ObjName.Substring(11, 32);
                Chart.RemoveObject("Bear Reward " + ObjId);
                Chart.RemoveObject("Bear Risk " + ObjId);
                Chart.RemoveObject("Short Rectangle " + ObjId);
                Chart.RemoveObject("Short Target Text " + ObjId);
                Chart.RemoveObject("Short Stop Text " + ObjId);
            }
        }

        public void getCostPerPip()
        {
            if (Symbol.LotSize == 100000)
            {
                costPerPip = (double)((int)(Symbol.PipValue * (Symbol.LotSize * 100000000))) / 100000000;
                costPerPip = costPerPip * Lots;
            }
            else
            {
                costPerPip = (double)((int)(Symbol.PipValue * (Symbol.LotSize * 100000000))) / 100000000;
                costPerPip = (costPerPip / Convert.ToDouble(Symbol.LotSize)) * Lots;
            }
        }

        void OnChartObjectUpdated(ChartObjectUpdatedEventArgs obj)
        {
            GetPixelsPrice();
            getCostPerPip();
            var ObjName = obj.ChartObject.Name;
            if (ObjName.Contains("Long Rectangle"))
            {
                var ObjId = ObjName.Substring(15, 32);
                UpdateBullishRectangle(ObjId, obj.ChartObject);
            }
            else if (ObjName.Contains("Short Rectangle"))
            {
                var ObjId = ObjName.Substring(16, 32);
                UpdateBearishRectangle(ObjId, obj.ChartObject);
            }
            else if (ObjName.Contains("Long Line"))
            {
                var ObjId = ObjName.Substring(10, 32);
                UpdateBullishRectangle(ObjId, obj.ChartObject);
            }
            else if (ObjName.Contains("Short Line"))
            {
                var ObjId = ObjName.Substring(11, 32);
                UpdateBearishRectangle(ObjId, obj.ChartObject);
            }
        }
        public void UpdateBullishRectangle(string objId, ChartObject obj)
        {
            if (obj.Name.Contains("Long Rectangle") && obj.ObjectType == ChartObjectType.Rectangle && obj.Name.Contains(objId))
            {
                BullRR = (ChartRectangle)Chart.FindObject("Long Rectangle " + objId);
                BullLine = (ChartHorizontalLine)Chart.FindObject("Long Line " + objId);
                lastObjName = BullRR.Name;
                if (lastObjRectY1 != BullRR.Y1 && lastObjRectY2 != BullRR.Y2)
                {
                    var NewHorizontalLineY = BullRR.Y1 + lastHLineToRiskDistance;
                    BullLine.Y = NewHorizontalLineY;
                }
                else if (lastObjRectY2 != BullRR.Y2 && lastObjRectY1 == BullRR.Y1)
                {
                }
                else if (lastObjRectY2 == BullRR.Y2 && lastObjRectY1 != BullRR.Y1)
                {
                }
            }
            else if (obj.Name.Contains("Long Line") && obj.ObjectType == ChartObjectType.HorizontalLine && obj.Name.Contains(objId))
            {
                BullLine = (ChartHorizontalLine)Chart.FindObject("Long Line " + objId);
                BullRR = (ChartRectangle)Chart.FindObject("Long Rectangle " + objId);
            }
            lastObjID = objId;
            lastObjDirection = "Buy";
            lastObjRectY1 = BullRR.Y1;
            lastObjRectY2 = BullRR.Y2;
            lastHLineToRiskDistance = BullLine.Y - BullRR.Y1;
            lastHLineToRewardDistance = BullRR.Y2 - BullLine.Y;
            Chart.DrawRectangle("Bull Reward " + objId, BullRR.Time1, BullLine.Y, BullRR.Time2, BullRR.Y2, RewardColorRect).IsFilled = true;
            Chart.DrawRectangle("Bull Risk " + objId, BullRR.Time1, BullRR.Y1, BullRR.Time2, BullLine.Y, RiskColorRect).IsFilled = true;
            var RewardText = CalculateRiskReward(BullRR, BullLine, "reward", "long");
            var TargetText = Chart.DrawText("Long Target Text " + objId, RewardText, BullRR.Time1, BullRR.Y2 + TargetRiskBoxPixels, Color.FromName(TextColor.ToString()));
            var RiskText = CalculateRiskReward(BullRR, BullLine, "risk", "long");
            var StopText = Chart.DrawText("Long Stop Text " + objId, RiskText, BullRR.Time1, BullRR.Y1, Color.FromName(TextColor.ToString()));
            var pips = Math.Round(Math.Abs((BullRR.Y1 - BullLine.Y) / Symbol.PipSize), 2);
            var PositionSize = (Account.Equity * PctRisk) / (pips * Symbol.PipValue);
            PositionSize = Symbol.NormalizeVolumeInUnits(PositionSize, RoundingMode.Down);
            PositionSize = Symbol.VolumeInUnitsToQuantity(PositionSize);
            PositionSizeData = PositionSize;
            text5.Text = "Position Size:  " + PositionSizeData;
            var reward = BullRR.Y2 - BullLine.Y;
            var risk = BullLine.Y - BullRR.Y1;
            var RRdata = RiskRewardRatio(reward, risk);
            text6.Text = RRdata;
            text7.Text = "Position Type: " + "Long/Buy";
        }
        public void UpdateBearishRectangle(string objId, ChartObject obj)
        {
            if (obj.Name.Contains("Short Rectangle") && obj.ObjectType == ChartObjectType.Rectangle && obj.Name.Contains(objId))
            {
                BearRR = (ChartRectangle)Chart.FindObject("Short Rectangle " + objId);
                BearLine = (ChartHorizontalLine)Chart.FindObject("Short Line " + objId);
                lastObjName = BearRR.Name;
                if (lastObjRectY1 != BearRR.Y1 && lastObjRectY2 != BearRR.Y2)
                {
                    var NewHorizontalLineY = BearRR.Y2 - lastHLineToRiskDistance;
                    BearLine.Y = NewHorizontalLineY;
                }
                else if (lastObjRectY2 != BearRR.Y2 && lastObjRectY1 == BearRR.Y1)
                {
                }
                else if (lastObjRectY2 == BearRR.Y2 && lastObjRectY1 != BearRR.Y1)
                {
                }
            }
            else if (obj.Name.Contains("Short Line") && obj.ObjectType == ChartObjectType.HorizontalLine && obj.Name.Contains(objId))
            {
                BearRR = (ChartRectangle)Chart.FindObject("Short Rectangle " + objId);
                BearLine = (ChartHorizontalLine)Chart.FindObject("Short Line " + objId);
            }
            lastObjID = objId;
            lastObjDirection = "Sell";
            lastObjRectY1 = BearRR.Y1;
            lastObjRectY2 = BearRR.Y2;
            lastHLineToRiskDistance = BearRR.Y2 - BearLine.Y;
            lastHLineToRewardDistance = BearLine.Y - BearRR.Y1;
            Chart.DrawRectangle("Bear Risk " + objId, BearRR.Time1, BearRR.Y2, BearRR.Time2, BearLine.Y, RiskColorRect).IsFilled = true;
            Chart.DrawRectangle("Bear Reward " + objId, BearRR.Time1, BearRR.Y1, BearRR.Time2, BearLine.Y, RewardColorRect).IsFilled = true;
            var RiskText = CalculateRiskReward(BearRR, BearLine, "risk", "short");
            var StopText = Chart.DrawText("Short Stop Text " + objId, RiskText, BearRR.Time1, BearRR.Y2 + TargetRiskBoxPixels, Color.FromName(TextColor.ToString()));
            var RewardText = CalculateRiskReward(BearRR, BearLine, "reward", "short");
            var TargetText = Chart.DrawText("Short Target Text " + objId, RewardText, BearRR.Time1, BearRR.Y1, Color.FromName(TextColor.ToString()));
            var pips = Math.Round(Math.Abs((BearLine.Y - BearRR.Y2) / Symbol.PipSize), 2);
            var PositionSize = (Account.Equity * PctRisk) / (pips * Symbol.PipValue);
            PositionSize = Symbol.NormalizeVolumeInUnits(PositionSize, RoundingMode.Down);
            PositionSize = Symbol.VolumeInUnitsToQuantity(PositionSize);
            PositionSizeData = PositionSize;
            text5.Text = "Position Size:  " + PositionSizeData;
            var reward = BearLine.Y - BearRR.Y1;
            var risk = BearRR.Y2 - BearLine.Y;
            var RRdata = RiskRewardRatio(reward, risk);
            text6.Text = RRdata;
            text7.Text = "Position Type: " + "Short/Sell";
        }
        public override void Calculate(int index)
        {
        }
        private string CalculateRiskReward(ChartRectangle rect, ChartHorizontalLine line, string type, string direction)
        {
            var pips = 0.0;
            var targetOrStop = 0.0;
            var PctrewardOrRisk = 0.0;
            var capitalLossOrGain = 0.0;
            var currency = Account.Asset.Name;
            var data = "";
            if (type == "reward" && direction == "long")
            {
                targetOrStop = Math.Round(rect.Y2, DecimalCount);
                pips = Math.Round(Math.Abs((rect.Y2 - line.Y) / Symbol.PipSize), 2);
                PctrewardOrRisk = Math.Round((((pips * costPerPip) / (Account.Balance)) * 100), 2);
                capitalLossOrGain = Math.Round((pips * costPerPip), 2);
                data += "  Target Price: " + targetOrStop + " - Pips: " + pips + "\n   Reward: " + PctrewardOrRisk + "% - Gain: " + CurrencyName + " " + capitalLossOrGain;
            }
            else if (type == "risk" && direction == "long")
            {
                targetOrStop = Math.Round(rect.Y1, DecimalCount);
                pips = Math.Round(Math.Abs((line.Y - rect.Y1) / Symbol.PipSize), 2);
                PctrewardOrRisk = Math.Round((((pips * costPerPip) / (Account.Balance)) * 100), 2);
                capitalLossOrGain = Math.Round((pips * costPerPip), 2);
                data += "  Stop Price: " + targetOrStop + " - Pips: " + pips + "\n   Risk: " + PctrewardOrRisk + "% - Loss: " + CurrencyName + " " + capitalLossOrGain;
            }
            else if (type == "reward" && direction == "short")
            {
                targetOrStop = Math.Round(rect.Y1, DecimalCount);
                pips = Math.Round(Math.Abs((line.Y - rect.Y1) / Symbol.PipSize), 2);
                PctrewardOrRisk = Math.Round((((pips * costPerPip) / (Account.Balance)) * 100), 2);
                capitalLossOrGain = Math.Round((pips * costPerPip), 2);
                data += "  Target Price: " + targetOrStop + " - Pips: " + pips + "\n   Reward: " + PctrewardOrRisk + "% - Gain: " + CurrencyName + " " + capitalLossOrGain;
            }
            else if (type == "risk" && direction == "short")
            {
                targetOrStop = Math.Round(rect.Y2, DecimalCount);
                pips = Math.Round(Math.Abs((rect.Y2 - line.Y) / Symbol.PipSize), 2);
                PctrewardOrRisk = Math.Round((((pips * costPerPip) / (Account.Balance)) * 100), 2);
                capitalLossOrGain = Math.Round((pips * costPerPip), 2);
                data += "  Stop Price: " + targetOrStop + " - Pips: " + pips + "\n   Risk: " + PctrewardOrRisk + "% - Loss: " + CurrencyName + " " + capitalLossOrGain;
            }
            return data;
        }
        public String RiskRewardRatio(double Reward, double Risk)
        {
            var RewardRatio = Reward / Risk;
            var Values = "";
            if (RewardRatio >= 1)
            {
                Values = "Risk Reward Ratio: ( 1 / " + Math.Round(RewardRatio, 2) + " )";
            }
            else if (RewardRatio < 1)
            {
                var ratio = Risk / Reward;
                Values = "Risk Reward Ratio: ( " + Math.Round(ratio, 2) + " / 1 )";
            }
            return Values;
        }
        public static string MD5Hash(string input)
        {
            StringBuilder hash = new StringBuilder();
            MD5CryptoServiceProvider md5provider = new MD5CryptoServiceProvider();
            byte[] bytes = md5provider.ComputeHash(new UTF8Encoding().GetBytes(input));
            for (int i = 0; i < bytes.Length; i++)
            {
                hash.Append(bytes[i].ToString("x2"));
            }
            return hash.ToString();
        }
        public void FindLongRectangles()
        {
            foreach (ChartObject o in Chart.Objects.ToList())
            {
                var ObjId = "";
                if (o.Name.Contains("Long Rectangle") && o.ObjectType == ChartObjectType.Rectangle)
                {
                    BullRR = (ChartRectangle)o;
                    ObjId = o.Name.Substring(15, 32);
                    var obj = Chart.FindObject("Long Line " + ObjId);
                    BullLine = (ChartHorizontalLine)obj;
                    var RRDrawer = new RRConstructor();
                    RRDrawer.DrawLongRiskReward(this, this, BullRR, BullLine, RewardColorRect, RiskColorRect);
                    boxes.Add(RRDrawer);
                }
            }
        }
        public void FindShortRectangles()
        {
            foreach (ChartObject o in Chart.Objects.ToList())
            {
                var ObjId = "";
                if (o.Name.Contains("Short Rectangle") && o.ObjectType == ChartObjectType.Rectangle)
                {
                    BearRR = (ChartRectangle)o;
                    ObjId = o.Name.Substring(16, 32);
                    var obj = Chart.FindObject("Short Line " + ObjId);
                    BearLine = (ChartHorizontalLine)obj;
                    var RRDrawer = new RRConstructor();
                    RRDrawer.DrawShortRiskReward(this, this, BearRR, BearLine, RewardColorRect, RiskColorRect);
                    boxes.Add(RRDrawer);
                }
            }
        }
        public void GetPixelsPrice()
        {
            PixelPrice = (Chart.TopY - Chart.BottomY) / Chart.Height;
            TargetRiskBoxPixels = PixelPrice * 40;
        }
        public class ToolBar : CustomControl
        {
            RiskReward RR;
            public ToolBar(RiskReward rr)
            {
                RR = rr;
                var AddButton = new Button 
                {
                    Text = "Add",
                    Style = new Style(DefaultStyles.ButtonStyle),
                    Height = 25,
                    BackgroundColor = Color.Green,
                    FontWeight = FontWeight.Bold
                };
                AddButton.Click += AddArea;
                AddChild(AddButton);
            }

            void AddArea(ButtonClickEventArgs e)
            {
                RR.GetPixelsPrice();
                var pixelSize = 220.0;
                var PixelBar = RR.Chart.Width / (RR.Chart.MaxVisibleBars);
                var barsNumbers = pixelSize / PixelBar;
                var BarsLength = (int)barsNumbers;
                double Y_Bottom = (RR.Chart.TopY - RR.Chart.BottomY) * 0.2 + RR.Chart.BottomY;
                double Y_Top = RR.Chart.TopY - (RR.Chart.TopY - RR.Chart.BottomY) * 0.2;
                double EntryLine = RR.Chart.BottomY + ((RR.Chart.TopY - RR.Chart.BottomY) / 2);
                double RewardTop = EntryLine + (RR.Chart.TopY - RR.Chart.BottomY) * 0.2;
                double RiskBottom = EntryLine - (RR.Chart.TopY - RR.Chart.BottomY) * 0.2;
                string id = RR.Time.ToString();
                string name = "Long Rectangle " + MD5Hash(id);
                var RRobj = RR.Chart.DrawRectangle(name, RR.Chart.LastVisibleBarIndex - BarsLength, RiskBottom, RR.Chart.LastVisibleBarIndex - 2, RewardTop, Color.Transparent);
                RRobj.IsInteractive = true;
                RRobj.IsFilled = true;
                var RewardObj = RR.Chart.DrawRectangle("Bull Reward " + MD5Hash(id), RR.Chart.LastVisibleBarIndex - BarsLength, EntryLine, RR.Chart.LastVisibleBarIndex - 2, RewardTop, RR.RewardColorRect);
                RewardObj.IsFilled = true;
                var RiskObj = RR.Chart.DrawRectangle("Bull Risk " + MD5Hash(id), RR.Chart.LastVisibleBarIndex - BarsLength, RiskBottom, RR.Chart.LastVisibleBarIndex - 2, EntryLine, RR.RiskColorRect);
                RiskObj.IsFilled = true;
                var LineObj = RR.Chart.DrawHorizontalLine("Long Line " + MD5Hash(id), EntryLine, Color.FromName(RR.LongLineColor.ToString()), RR.EntryLineSize);
                LineObj.LineStyle = RR.EntryLineStyle;
                LineObj.IsInteractive = true;
                var RewardText = RR.CalculateRiskReward(RRobj, LineObj, "reward", "long");
                var TargetText = RR.Chart.DrawText("Long Target Text " + MD5Hash(id), RewardText, RR.Chart.LastVisibleBarIndex - BarsLength, RewardTop + RR.TargetRiskBoxPixels, Color.FromName(RR.TextColor.ToString()));
                var RiskText = RR.CalculateRiskReward(RRobj, LineObj, "risk", "long");
                var StopText = RR.Chart.DrawText("Long Stop Text " + MD5Hash(id), RiskText, RR.Chart.LastVisibleBarIndex - BarsLength, RiskBottom, Color.FromName(RR.TextColor.ToString()));
                var pips = Math.Round(Math.Abs((RiskBottom - EntryLine) / RR.Symbol.PipSize), 2);
                var PositionSize = (RR.Account.Equity * RR.PctRisk) / (pips * RR.Symbol.PipValue);
                PositionSize = RR.Symbol.NormalizeVolumeInUnits(PositionSize, RoundingMode.Down);
                PositionSize = RR.Symbol.VolumeInUnitsToQuantity(PositionSize);
                RR.PositionSizeData = PositionSize;
                RR.text5.Text = "Position Size:  " + RR.PositionSizeData;
                var reward = RewardTop - EntryLine;
                var risk = EntryLine - RiskBottom;
                var RRdata = RR.RiskRewardRatio(reward, risk);
                RR.text6.Text = RRdata;
                RR.text7.Text = "Position Type: " + "Long/Buy";
            }
        }

        public class ToolBar2 : CustomControl
        {
            RiskReward RR;
            public ToolBar2(RiskReward rr)
            {
                RR = rr;

                var AddButton = new Button 
                {
                    Text = "Add",
                    Style = new Style(DefaultStyles.ButtonStyle),
                    Height = 25,
                    BackgroundColor = Color.Red,
                    FontWeight = FontWeight.Bold
                };

                AddButton.Click += AddArea;

                AddChild(AddButton);
            }
            void AddArea(ButtonClickEventArgs e)
            {
                RR.GetPixelsPrice();
                var pixelSize = 220.0;
                var PixelBar = RR.Chart.Width / (RR.Chart.MaxVisibleBars);
                var barsNumbers = pixelSize / PixelBar;
                var BarsLength = (int)barsNumbers;
                double Y_Bottom = (RR.Chart.TopY - RR.Chart.BottomY) * 0.2 + RR.Chart.BottomY;
                double Y_Top = RR.Chart.TopY - (RR.Chart.TopY - RR.Chart.BottomY) * 0.2;
                double EntryLine = RR.Chart.BottomY + ((RR.Chart.TopY - RR.Chart.BottomY) / 2);
                double RewardBottom = EntryLine - (RR.Chart.TopY - RR.Chart.BottomY) * 0.2;
                double RiskTop = EntryLine + (RR.Chart.TopY - RR.Chart.BottomY) * 0.2;
                string id = RR.Time.ToString();
                string name = "Short Rectangle " + MD5Hash(id);
                var RRobj = RR.Chart.DrawRectangle(name, RR.Chart.LastVisibleBarIndex - BarsLength, RewardBottom, RR.Chart.LastVisibleBarIndex - 2, RiskTop, Color.Transparent);
                RRobj.IsInteractive = true;
                RRobj.IsFilled = true;
                var RiskObj = RR.Chart.DrawRectangle("Bear Risk " + MD5Hash(id), RR.Chart.LastVisibleBarIndex - BarsLength, EntryLine, RR.Chart.LastVisibleBarIndex - 2, RiskTop, RR.RiskColorRect);
                RiskObj.IsFilled = true;
                var RewardObj = RR.Chart.DrawRectangle("Bear Reward " + MD5Hash(id), RR.Chart.LastVisibleBarIndex - BarsLength, RewardBottom, RR.Chart.LastVisibleBarIndex - 2, EntryLine, RR.RewardColorRect);
                RewardObj.IsFilled = true;
                var LineObj = RR.Chart.DrawHorizontalLine("Short Line " + MD5Hash(id), EntryLine, Color.FromName(RR.ShortLineColor.ToString()), RR.EntryLineSize);
                LineObj.LineStyle = RR.EntryLineStyle;
                LineObj.IsInteractive = true;
                var RiskText = RR.CalculateRiskReward(RRobj, LineObj, "risk", "short");
                var StopText = RR.Chart.DrawText("Short Target Text " + MD5Hash(id), RiskText, RR.Chart.LastVisibleBarIndex - BarsLength, RiskTop + RR.TargetRiskBoxPixels, Color.FromName(RR.TextColor.ToString()));
                var RewardText = RR.CalculateRiskReward(RRobj, LineObj, "reward", "short");
                var TargetText = RR.Chart.DrawText("Short Stop Text " + MD5Hash(id), RewardText, RR.Chart.LastVisibleBarIndex - BarsLength, RewardBottom, Color.FromName(RR.TextColor.ToString()));
                var pips = Math.Round(Math.Abs((EntryLine - RiskTop) / RR.Symbol.PipSize), 2);
                var PositionSize = (RR.Account.Equity * RR.PctRisk) / (pips * RR.Symbol.PipValue);
                PositionSize = RR.Symbol.NormalizeVolumeInUnits(PositionSize, RoundingMode.Down);
                PositionSize = RR.Symbol.VolumeInUnitsToQuantity(PositionSize);
                RR.PositionSizeData = PositionSize;
                RR.text5.Text = "Position Size:  " + RR.PositionSizeData;
                var reward = EntryLine - RewardBottom;
                var risk = RiskTop - EntryLine;
                var RRdata = RR.RiskRewardRatio(reward, risk);
                RR.text6.Text = RRdata;
                RR.text7.Text = "Position Type: " + "Short/Sell";
            }
        }
    }
    public class RRConstructor
    {
        Indicator Indi;
        RiskReward RR;
        public void DrawLongRiskReward(RiskReward rr, Indicator Indi, ChartRectangle rect, ChartHorizontalLine line, Color RewardColor, Color RiskColor)
        {
            this.Indi = Indi;
            RR = rr;
            var ObjId = rect.Name.Substring(15, 32);
            var reward = Indi.Chart.DrawRectangle("Bull Reward " + ObjId, rect.Time1, line.Y, rect.Time2, rect.Y2, RewardColor).IsFilled = true;
            var risk = Indi.Chart.DrawRectangle("Bull Risk " + ObjId, rect.Time1, rect.Y1, rect.Time2, line.Y, RiskColor).IsFilled = true;
        }

        public void DrawShortRiskReward(RiskReward rr, Indicator Indi, ChartRectangle rect, ChartHorizontalLine line, Color RewardColor, Color RiskColor)
        {
            this.Indi = Indi;
            RR = rr;
            var ObjId = rect.Name.Substring(16, 32);
            var risk = Indi.Chart.DrawRectangle("Bear Reward " + ObjId, rect.Time1, line.Y, rect.Time2, rect.Y1, RewardColor).IsFilled = true;
            var reward = Indi.Chart.DrawRectangle("Bear Risk " + ObjId, rect.Time1, rect.Y2, rect.Time2, line.Y, RiskColor).IsFilled = true;
        }
    }
}


TraderExperto's avatar
TraderExperto

Joined on 07.06.2019

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: Risk Reward Tool by Trader Experto.algo
  • Rating: 5
  • Installs: 9987
  • Modified: 14/01/2022 01:43
Comments
Log in to add a comment.
YE
YesOrNot · 1 year ago

Hello, do you take into consideration commissions and spreads in your risk and reward calculations? I've briefly reviewed your code, but it doesn't seem like you account for them. (If not, in a scalping strategy, the risk-reward ratio would be completely skewed.)

MO
monpolicina.fx · 2 years ago

This is a great free tool. I highly suggest adding the risk:reward ratio also on the information

Thank you!

FE
federicovenier.uk · 2 years ago

Once downloaded and installed, where I can find it?....a CTrader newbie :-) thanks!

MI
minnamusk · 2 years ago

Mentioned on StartupNoon  - Reward is an incentive plan to reinforce the desirable behavior of workers or employers and in return for their service to the organization.

MA
madelinerpresley · 2 years ago

This and similar encodings are quite successful, I think we are very lucky to be able to reach these encodings.  football legends

NA
nasatokoherbal · 2 years ago

Thanks a lot, It will be perfect if you add the RR ratio

NA
najwayaminah · 2 years ago

The Forum is really helpful for beginner developers who recently came into the development industry and they also need to learn this kind of algos to become professional developers. similarly, I have been started the development and now also developed lots of essay writing service websites in the UAE. As a professional developer, there are too many people who also want to learn this kind of algorithm to improve their creativity.

OK
Okaforsamuel007 · 2 years ago

Thanks. 

nh.zadeh's avatar
nh.zadeh · 2 years ago

Hi

Good job. As a suggestions:

1. entering stop loss and take profit amount as pip and price by user

2. entering risk/reward ratio entering by user.

 

at the moment it is possible to change risk/reward and amount of sl and tp by mouse which is hard to select exact numbers

 

yours