Category Other  Published on 10/04/2023

SK1 - EASY Khan GRID - v1

Description

Hi,

this is an old Grid bot, re-written by me to make it easy to understand with lot of comments.  This can act as a template to develop and build a more smarter cBOT on top of it.   Like you can add triggers like MA crossover, or any indicator of your choice to control BUY / SELL ORDERS.

Features :

1. SCALE IN :   This means that add positions to TREND only.

2. SCALE OUT : Add Positions against the TREND; in a ranging market it is helpful.

3. Average Take Profit : It re-arranges all the TAKE PROFIT at a single level.

4. Equity Manager : Any conditions you want to put regarding the Equity Amount

5. Margin Manager : Any condition you want to put if Margin % is falling beyond a certain level.

6. Buy/Sell  settings : If you want to turn off any one direction, set the First Volume and the increment and the max vol 

7. Other Settings : Max Spread, Slippage can be set.  A hard exit if Margin level falls below a certain %.

8. More Settings : Timer sets the time it will update the screen display values to put less load on the cpu, Display on/off, and #3. Force Buy/Sell: is right now acting to atleast always place an order. If you develop other trigger conditions for Buy/Sell, then you can set it to false. 

 

note : I haven't explained each and every settings as mostly are self explanatory. Like Grid-Pipstep is the gap in pips to keep between two Buy or Sell Orders. For Gold it can be 500 pips and for Forex it can be 20 pips.

 

I HOPE you guys like it.   do give feedback.

Cheers!

///S.Khan

skhan.projects@gmail.com


//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//|                                      Copyright: 2020 ///S.Khan   |
//|                                Email: skhan.projects@gmail.com   |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+


//// Basic SMART GRID Revised.  LAST UPDATED 10-Apr-23



using System.Globalization;
using System.IO;
using System.Threading;
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;


namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]

    public class Yr22_SKhan_Grid_v1 : Robot
    {

        ////////////////////////////////////////////////////////////////////////////
        ////----             USER INPUT            ----/////////////////////////////
        ////////////////////////////////////////////////////////////////////////////

        //[Parameter(">>>>>>>>  Grid PipStep Scale IN  <<<<<<<<")]

        [Parameter("1. use Scale IN", Group = "Scale IN Grid PipStep", DefaultValue = true)]
        public bool p_use_Scale_IN { get; set; }

        [Parameter("2. Def Grid Pipstep - Scale IN", Group = "Scale IN Grid PipStep", DefaultValue = 100, MinValue = 5, MaxValue = 3500, Step = 100)]
        public int p_Grid_PipStep_SI { get; set; }

        [Parameter("3. Max Buy or Sell Position Count", Group = "Scale IN Grid PipStep", DefaultValue = 10, MinValue = 2, Step = 1)]
        public int p_Max_BuySell_Positions_SI { get; set; }

        //[Parameter(">>>>>>>>  Grid PipStep Scale OUT  <<<<<<<<")]

        [Parameter("1. use Scale OUT", Group = "Scale OUT Grid", DefaultValue = false)]
        public bool p_use_Scale_OUT { get; set; }

        [Parameter("2. Def Grid Pipstep - Scale OUT", Group = "Scale OUT Grid", DefaultValue = 800, MinValue = 5, MaxValue = 3500, Step = 5)]
        public int p_Grid_PipStep_SO { get; set; }

        [Parameter("3. Max Buy or Sell Position Count", Group = "Scale OUT Grid", DefaultValue = 10, MinValue = 2, Step = 1)]
        public int p_Max_BuySell_Positions_SO { get; set; }


        //[Parameter(">>>>>>>>  Default Stop Loss and Take Profit <<<<<<<<")]

        [Parameter("8. Def Stop Loss", Group = "Def SL TP", DefaultValue = 0, MinValue = 0, MaxValue = 5000, Step = 5)]
        public int p_Def_SL { get; set; }

        [Parameter("8. Def Take Profit", Group = "Def SL TP", DefaultValue = 0, MinValue = 0, MaxValue = 5000, Step = 5)]
        public int p_Def_TP { get; set; }

        [Parameter("9. Average Take Profit in Pips", Group = "Def SL TP", DefaultValue = 800, MinValue = 10, Step = 4)]
        public int p_Avg_TakeProfit { get; set; }


        //[Parameter("#-------  EQUITY MANGER  -------#")]

        [Parameter("1. EQUITY Manager (0)No, (1)Yes", Group = "Equity Manager", DefaultValue = 0, MinValue = 0, MaxValue = 1)]
        public int p_Equity_Manager { get; set; }

        [Parameter("2. Close-All, if Starting Equity inc by; 0=ignore", Group = "Equity Manager", DefaultValue = 300, MinValue = 0)]
        public int p_NET_PL_inc_By { get; set; }

        [Parameter("3. Close-All, if Starting Equity dec by; 0=ignore", Group = "Equity Manager", DefaultValue = 50, MinValue = 0)]
        public int p_NET_PL_dec_By { get; set; }


        //[Parameter("#-------  "Margin Pip Manager"  -------#")]

        [Parameter("1. Margin Pip Manager (0)No, (1)Yes", Group = "Margin Pip Manager", DefaultValue = 0, MinValue = 0, MaxValue = 1)]
        public int p_Margin_Manager { get; set; }

        [Parameter("2. Close-All, if Margin % fall below; 0=ignore", Group = "Margin Pip Manager", DefaultValue = 1000, MinValue = 0)]
        public int p_Margin_dec_below { get; set; }

        [Parameter("3. Close-All, if (-)Pip Cost fall below; 0=ignore", Group = "Margin Pip Manager", DefaultValue = 0.4, MinValue = 0)]
        public double p_PipCost_dec_below { get; set; }


        //[Parameter(">>>>>>>>  BUY SELL  <<<<<<<<")]

        [Parameter("1. Buy : ON/OFF", Group = "BUY SELL VOL", DefaultValue = true)]
        public bool p_Flag_Buy { get; set; }

        [Parameter("2. Sell : ON/OFF", Group = "BUY SELL VOL", DefaultValue = true)]
        public bool p_Flag_Sell { get; set; }

        [Parameter("3. First Volume", Group = "BUY SELL VOL", DefaultValue = 2000, MinValue = 1, Step = 1)]
        public int p_FirstVolume { get; set; }

        [Parameter("4. Volume Increment", Group = "BUY SELL VOL", DefaultValue = 5000, MinValue = 1, Step = 1)]
        public int p_Volume_Increment { get; set; }

        [Parameter("5. Final Max Volume", Group = "BUY SELL VOL", DefaultValue = 200000, MinValue = 1, Step = 10)]
        public int p_Final_Max_Volume { get; set; }


        //[Parameter(">>>>>>>>  Other Settings  <<<<<<<<")]        

        [Parameter("1. Label", Group = "Other Settings", DefaultValue = "SK GRID")]
        public string p_Label { get; set; }

        [Parameter("2. Max Spread", Group = "Other Settings", DefaultValue = 30, MinValue = 0.1, Step = 0.1)]
        public double p_MaxSpread { get; set; }

        [Parameter("3. Max Slippage", Group = "Other Settings", DefaultValue = 10.0, MinValue = 0, Step = 1)]
        public double p_MaxSlippage { get; set; }

        [Parameter("4. Min. Margin Level %, Close_ALL; 0=ignore", Group = "Other Settings", DefaultValue = 200, MinValue = 0, Step = 50)]
        public double p_Min_Margin_Level { get; set; }

        [Parameter("")]
        public string t_Blan067 { get; set; }


        ///[Parameter("<----> More Settings <---->")]

        [Parameter("1. Timer Sec", Group = "More Settings", DefaultValue = 3, MinValue = 1, MaxValue = 500, Step = 1)]
        public int p_TimerSec { get; set; }

        [Parameter("2. Display On/Off", Group = "More Settings", DefaultValue = 1, MinValue = 0, MaxValue = 1, Step = 1)]
        public int p_Display_OnOff { get; set; }

        [Parameter("3. Force Buy Sell Signal", Group = "More Settings", DefaultValue = true)]
        public bool p_Test_Signal { get; set; }


        ////----   END OF USER INPUT   ----////


        ////////////////////////////////////////////////////////////////////////////
        ////----          GLOBAL VARIABLES          ----////////////////////////////
        ////////////////////////////////////////////////////////////////////////////

        ///-------------------------------------------------------------
        ///---   SYMBOL SPREAD   
        private double Current_Spread = 0;
        ///---  FOR VOLITALITY
        private double Current_Volitality = 0;
        ///---  TODAY's DATE
        private string Todays_Date = "";

        ///-------------------------------------------------------------
        ///---  METHOD CONTROL FLAGS
        private bool Flag_isExecuting_01 = false;
        private bool Flag_isExecuting_02 = false;
        private bool Flag_isExecuting_03 = false;
        private bool Flag_isExecuting_04 = false;
        private bool Flag_isExecuting_05 = false;
        private bool Flag_isExecuting_06 = false;
        private bool Flag_isExecuting_07 = false;
        private bool Flag_isExecuting_08 = false;

        ///---  ACCOUNT CONTROL FLAG
        private bool Flag_Account_Is_Out_Of_Money = false;

        ///---  SIGNAL CONTROL FLAG
        private bool Flag_Buy_Signal_01 = false;
        private bool Flag_Sell_Signal_01 = false;


        ////------------------------------------------------------------
        ////----   Account Details
        private double Start_Equity = 0;
        private double Highest_Equity = 0;
        private double Lowest_Equity = 0;
        private double Lowest_Margin = 100000;

        ////------------------------------------------------------------
        ////----   Positions Details
        // COUNT
        private int Count_Total_Positions = 0;
        private int Count_Buy_Positions = 0;
        private int Count_Sell_Positions = 0;
        private int Highest_Buy_Count = 1;
        private int Highest_Sell_Count = 1;
        // Pip Cost
        private double Pip_Cost = 0;
        private double Pip_Cost_Highest = 0;
        private double Pip_Cost_Lowest = 0;
        // Volume Detail
        private double Vol_Total = 0;
        private double Vol_Total_Buy = 0;
        private double Vol_Total_Sell = 0;
        private double Highest_Vol_Buy = 0;
        private double Highest_Vol_Sell = 0;
        // NET PROFIT AND LOSS
        private double NetPL_Total = 0;
        private double NetPL_Total_Buy = 0;
        private double NetPL_Total_Sell = 0;
        private double Highest_NetPL = 0;
        private double Lowest_NetPL = 0;

        ////------------------------------------------------------------
        ////----   LAST TIME OF BUY AND SELL
        private DateTime DT_Last_Buy;
        private DateTime DT_Last_Sell;



        ////-----------------------------------------------------------
        ////----   COLORS
        private Color Clr_Bk_1 = Color.DimGray;

        private Color Clr_Heading_1 = Color.LightPink;
        private Color Clr_Heading_2 = Color.LightSeaGreen;
        private Color Clr_Heading_3 = Color.Tomato;

        private Color Clr_PairListing = Color.DarkOrange;

        private Color Clr_Positive = Color.CornflowerBlue;
        private Color Clr_Negative = Color.IndianRed;

        private Color Clr_True = Color.LimeGreen;
        private Color Clr_False = Color.Crimson;

        private Color Clr_Signal_Buy = Color.CornflowerBlue;
        private Color Clr_Signal_Sell = Color.IndianRed;

        private Color Clr_Value_01 = Color.DimGray;
        private Color Clr_Value_02 = Color.White;

        private Color Clr_Signal_Hold = Color.OrangeRed;
        private Color Clr_Signal_Ntrl = Color.DimGray;

        ////----  END OF GLOBAL VARIABLES   ----////




        ////////////////////////////////////////////////////////////////////////////
        ////----            ON START                 ----///////////////////////////
        ////////////////////////////////////////////////////////////////////////////
        protected override void OnStart()
        {
            Print("");
            Print("cBOT Start Date & Time : " + Server.Time);

            ///--- TODAY's DATE      ------------------------------
            Todays_Date = string.Format("{0:d}", Server.Time);

            /// INITIALIZE TIMER ON EVERY x SECONDS
            /// USED IN METHOD Upate_Dynamic_Values
            Timer.Start(p_TimerSec);

            ///  EQUITY  DETAILS  ------------------
            Start_Equity = Account.Equity;
            Highest_Equity = Account.Equity;
            Lowest_Equity = Account.Equity;

            ///--- INITIALIZE "onPositionClosed"     --------------
            Positions.Closed += OnPositionsClosed;
            Positions.Opened += OnPositionsOpened;


            ///---   Display on Chart
            if (p_Display_OnOff == 1)
            {
                Display_on_Chart_TopLeft();
                Display_on_Chart_TopRight();
                Display_RowColumn();
            }
            //END IF

            if (p_Test_Signal == true)
            {
                Flag_Buy_Signal_01 = true;
                Flag_Sell_Signal_01 = true;
            }
            //END IF

        }
        //END METHOD OnStart()

        ////////////////////////////////////////////////////////////////////////////
        ////----              ON BAR                  ----//////////////////////////
        ////////////////////////////////////////////////////////////////////////////
        protected override void OnBar()
        {

            


        }
        //END METHOD OnBar()


        ////////////////////////////////////////////////////////////////////////////
        ////----             ON TICK                  ----//////////////////////////
        ////////////////////////////////////////////////////////////////////////////
        protected override void OnTick()
        {
            //Print("Inside ON_TICK METHOD");

            if (Flag_isExecuting_07 == false)
            {
                // SET THE FLAG TO TRUE
                Flag_isExecuting_07 = true;

                //--  Contains ENTRY, CONTROL, MANAGE, EXIT
                Main_Logic();

                // RESET THE FLAG TO FALSE
                Flag_isExecuting_07 = false;
            }
        }
        //END METHOD OnTick()

        ////////////////////////////////////////////////////////////////////////////
        ////----            ON   TIMER                 ----/////////////////////////
        ////////////////////////////////////////////////////////////////////////////
        protected override void OnTimer()
        {
            //Print("Inside ON_TIMER METHOD");

            //
            Upate_Dynamic_Values();
            

        }
        //End FUNCTION On_Timer

        ////////////////////////////////////////////////////////////////////////////
        ////----               ON STOP                  ----////////////////////////
        ////////////////////////////////////////////////////////////////////////////
        protected override void OnStop()
        {
            //CloseAll_Positions();

            // PRINT IN LOG FILE
            Print("Lowest Pip Cost : ", Pip_Cost_Lowest);
            Print("Highest Pip Cost : ", Pip_Cost_Highest);
            Print("Lowest Margin % : ", Lowest_Margin);
            
            //BLANK LINE
            Print("");
            Print("Method : OnStop() '':   Date & time : " + Server.Time);
        }
        //END METHOD OnStop()

        ////////////////////////////////////////////////////////////////////////////
        ////----               On Error                 ----////////////////////////
        ////////////////////////////////////////////////////////////////////////////
        protected override void OnError(Error error)
        {
            if (error.Code == ErrorCode.NoMoney)
            {
                Flag_Account_Is_Out_Of_Money = true;
                Print("Method onError : Due to NOT Enough MONEY !!!");
            }
        }
        // END METHOD OnError

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Test                                                ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Test()
        {

        }
        //END METHOD Test

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////                                    Main_Logic                                                    //////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void Main_Logic()
        {

            //--   01
            // ENTRY CRITERIA FOR FIRST BUY/SELL POSITION
            if (Current_Spread <= p_MaxSpread && Flag_Account_Is_Out_Of_Money == false)
                Entry_Strategies();

            //--   02
            Manage_Open_Trades();

            //--   03
            Control_Strategies();

            //--   04
            Exit_Strategies();
            
            // DISPLAY DATA ON CHARTS IF NOT BACKTESTING
            //if (!this.IsBacktesting)
            //{


            //}
            //END IF

        }
        //END METHOD Main_Logic

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Entry_Strategies                                    ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Entry_Strategies()
        {
            // ORIGNAL ENTRY LOGIC
            Trades_Entry_Logic_01();
        }
        //END METHOD Entry_Strategies

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Manage_Open_Trades                                  ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Manage_Open_Trades()
        {
            // MANAGE ALREADY OPEN TRADES - ADD TO WINNERS
            Trades_Manage_By_Scale_IN();

            // MANAGE ALREADY OPEN TRADES - ADD TO LOSES
            Trades_Manage_By_Scale_OUT();
        }
        // END METHOD Manage_Open_Trades

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Control_Strategies                                  ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Control_Strategies()
        {

        }
        // END METHOD Control_Strategies

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Exit_Strategies                                     ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Exit_Strategies()
        {
            // ADJUST ALL POSITIONS TAKE PROFIT
            //if (p_Avg_TP_On_Off == 1)
            //    Adjust_Average_STOP_LOSS();

            // EQ MANAGER
            Get_Equity_Manager();

            // MARGIN PIP_COST MANAGER
            Get_Margin_PipCost_Manager();

        }
        // END METHOD Exit_Strategies


        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Trades_Entry_Logic_01                               ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Trades_Entry_Logic_01()
        {
            // GET POS COUNTs
            int t_Count_Buy_Pos = Count_Buy_Positions;
            int t_Count_Sell_Pos = Count_Sell_Positions;

            // FIRST TIME BUY ENTRY -------------------------------------
            // ZERO BUY POSITION
            if (t_Count_Buy_Pos == 0 && Flag_Buy_Signal_01 == true)
            {
                //Print("01 inside Buy loop");

                // AND LAST BUY POS TIME IS NOT SAME WITH THE CURRENT TIME
                if (DT_Last_Buy != Bars.OpenTimes.Last(0))
                {
                    // PLACE MARKET ORDER
                    if (p_Flag_Buy)
                    {
                        Order_Send(TradeType.Buy, Limit_Volume(p_FirstVolume), p_Label, p_Def_SL, p_Def_TP);
                    }
                    //END IF
                }
                //END IF
            }
            //END IF BUY POSITION

            // FIRST TIME SELL ENTRY -------------------------------------
            // ZERO SELL POSITION
            if (t_Count_Sell_Pos == 0 && Flag_Sell_Signal_01 == true)
            {
                //Print("02 inside Sell loop");

                // AND LAST SELL POS TIME IS NOT SAME WITH THE CURRENT TIME
                if (DT_Last_Sell != Bars.OpenTimes.Last(0))
                {
                    // PLACE MARKET ORDER
                    if (p_Flag_Sell)
                    {
                        Order_Send(TradeType.Sell, Limit_Volume(p_FirstVolume), p_Label, p_Def_SL, p_Def_TP);
                    }
                    //END IF
                }
                //END IF
            }
            //END IF BUY POSITION

        }
        //END METHOD Trades_Entry_Logic_01

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Trades_Manage_By_Scale_IN                           ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Trades_Manage_By_Scale_IN()
        {

            ///-----------------------------------------------------------------------
            ///---    ADD MORE TRADES TO WINNING TRADES, ASSUMING TREND WILL CONTINUE
            ///-----------------------------------------------------------------------

            if (p_use_Scale_IN == true)
            {
                // BUY GRID ---------------------------------------------------
                // IF ATLEAST ONE POSITION IS OPENED
                if (Count_Buy_Positions >= 1 && Count_Buy_Positions < p_Max_BuySell_Positions_SI)
                {
                    double t_Current_Price = 0, t_Highest_Pos_Price = 0;

                    // SYMBOL ASK PRICE
                    t_Current_Price = Math.Round(Symbol.Ask, Symbol.Digits);

                    // SUBTRACT PIP STEP TO LOWEST BUY POS PRICE
                    t_Highest_Pos_Price = Math.Round(Find_HighestPosition_Price(TradeType.Buy) + (p_Grid_PipStep_SI * Symbol.PipSize), Symbol.Digits);

                    // Below code to be disabled if doing optimization
                    //Chart.DrawHorizontalLine("HighestPrice", t_Highest_Pos_Price, Clr_Positive);

                    // NOW IF 
                    if (t_Current_Price >= t_Highest_Pos_Price)
                    {
                        // AND LAST BUY POS TIME IS NOT SAME WITH THE CURRENT TIME
                        if (DT_Last_Buy != Bars.OpenTimes.Last(0))
                        {
                            ///---   NEXT TRADE VOLUME
                            var calculatedVolume = Calculate_Volume(TradeType.Buy);

                            //Print("BUY Manage Trades : Order Send");
                            ///---   PLACE MARKET ORDER
                            Order_Send(TradeType.Buy, Limit_Volume(calculatedVolume), p_Label, p_Def_SL, p_Def_TP);

                        }
                        //END IF
                    }
                    //END IF
                }
                //END IF BUY


                // SELL GRID ---------------------------------------------------
                // IF ATLEAST ONE POSITION IS OPENED
                if (Count_Sell_Positions >= 1 && Count_Sell_Positions < p_Max_BuySell_Positions_SI)
                {
                    double t_Current_Price = 0, t_Lowest_Pos_Price = 0;

                    // SYMBOL ASK PRICE
                    t_Current_Price = Math.Round(Symbol.Bid, Symbol.Digits);

                    // SUBTRACT PIP STEP TO LOWEST BUY POS PRICE
                    t_Lowest_Pos_Price = Math.Round(Find_LowestPosition_Price(TradeType.Sell) - (p_Grid_PipStep_SI * Symbol.PipSize), Symbol.Digits);

                    // Below code to be disabled if doing optimization
                    //Chart.DrawHorizontalLine("LowestPrice", t_Lowest_Pos_Price, Clr_Negative);

                    // NOW IF 
                    if (t_Current_Price <= t_Lowest_Pos_Price)
                    {
                        // AND LAST BUY POS TIME IS NOT SAME WITH THE CURRENT TIME
                        if (DT_Last_Sell != Bars.OpenTimes.Last(0))
                        {
                            ///---   NEXT TRADE VOLUME
                            var calculatedVolume = Calculate_Volume(TradeType.Sell);

                            //Print("SEll Manage Trades : Order Send");
                            ///---   PLACE MARKET ORDER
                            Order_Send(TradeType.Sell, Limit_Volume(calculatedVolume), p_Label, p_Def_SL, p_Def_TP);

                        }
                        //END IF
                    }
                    //END IF
                }
                //END IF SELL

            }
            //END IF (p_use_Scale_IN)

        }
        //END METHOD Trades_Manage_By_Scale_IN

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Trades_Manage_By_Scale_OUT                          ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Trades_Manage_By_Scale_OUT()
        {

            ///-----------------------------------------------------------------------
            ///---    ADD MORE TRADES TO Loosing TRADES: Averaging DOWN
            ///-----------------------------------------------------------------------

            if (p_use_Scale_OUT == true)
            {
                // BUY GRID ---------------------------------------------------
                // IF ATLEAST ONE POSITION IS OPENED
                if (Count_Buy_Positions >= 1 && Count_Buy_Positions < p_Max_BuySell_Positions_SO)
                {
                    double t_Current_Price = 0, t_Lowest_Pos_Price = 0;

                    // SYMBOL ASK PRICE
                    t_Current_Price = Math.Round(Symbol.Ask, Symbol.Digits);

                    // SUBTRACT PIP STEP TO LOWEST BUY POS PRICE
                    t_Lowest_Pos_Price = Math.Round(Find_LowestPosition_Price(TradeType.Buy) - (p_Grid_PipStep_SO * Symbol.PipSize), Symbol.Digits);

                    // Below code to be disabled if doing optimization
                    //Chart.DrawHorizontalLine("HighestPrice", t_Highest_Pos_Price, Clr_Positive);

                    // NOW IF 
                    if (t_Current_Price <= t_Lowest_Pos_Price)
                    {
                        // AND LAST BUY POS TIME IS NOT SAME WITH THE CURRENT TIME
                        if (DT_Last_Buy != Bars.OpenTimes.Last(0))
                        {
                            ///---   NEXT TRADE VOLUME
                            var calculatedVolume = Calculate_Volume(TradeType.Buy);

                            //Print("BUY Manage Trades : Order Send");
                            ///---   PLACE MARKET ORDER
                            Order_Send(TradeType.Buy, Limit_Volume(calculatedVolume), p_Label, p_Def_SL, p_Def_TP);

                        }
                        //END IF
                    }
                    //END IF
                }
                //END IF BUY


                // SELL GRID ---------------------------------------------------
                // IF ATLEAST ONE POSITION IS OPENED
                if (Count_Sell_Positions >= 1 && Count_Sell_Positions < p_Max_BuySell_Positions_SO)
                {
                    double t_Current_Price = 0, t_Highest_Pos_Price = 0;

                    // SYMBOL ASK PRICE
                    t_Current_Price = Math.Round(Symbol.Bid, Symbol.Digits);

                    // SUBTRACT PIP STEP TO LOWEST BUY POS PRICE
                    t_Highest_Pos_Price = Math.Round(Find_HighestPosition_Price(TradeType.Sell) + (p_Grid_PipStep_SO * Symbol.PipSize), Symbol.Digits);

                    // Below code to be disabled if doing optimization
                    //Chart.DrawHorizontalLine("LowestPrice", t_Lowest_Pos_Price, Clr_Negative);

                    // NOW IF 
                    if (t_Current_Price >= t_Highest_Pos_Price)
                    {
                        // AND LAST BUY POS TIME IS NOT SAME WITH THE CURRENT TIME
                        if (DT_Last_Sell != Bars.OpenTimes.Last(0))
                        {
                            ///---   NEXT TRADE VOLUME
                            var calculatedVolume = Calculate_Volume(TradeType.Sell);

                            //Print("SEll Manage Trades : Order Send");
                            ///---   PLACE MARKET ORDER
                            Order_Send(TradeType.Sell, Limit_Volume(calculatedVolume), p_Label, p_Def_SL, p_Def_TP);

                        }
                        //END IF
                    }
                    //END IF
                }
                //END IF SELL

            }
            //END IF (p_use_Scale_OUT)

        }
        //END METHOD Trades_Manage_By_Scale_OUT



        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Upate_Dynamic_Values                                ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        protected void Upate_Dynamic_Values()
        {
            if (Flag_isExecuting_01 == false)
            {
                // SET THE FLAG
                Flag_isExecuting_01 = true;

                // TEMP VARIABLES 
                double t_High = Bars.HighPrices.LastValue;
                double t_Low = Bars.LowPrices.LastValue;

                ///---   GET SYMBOL SPREAD-----------------------------------------
                Current_Spread = (Symbol.Ask - Symbol.Bid) / Symbol.PipSize;

                ///---   SYMBOL VOLITATLITY   ---------------------------------
                Current_Volitality = (t_High - t_Low) / Symbol.PipSize;

                ///---   HIGHEST AND LOWEST VALUES      --------
                Get_Highest_Lowest_Values();

                ///---   UPDATE NET P/L      ----------------------
                Get_NetPL_of_This_Pair_Only();


                ///---   DISPLAY   --------
                ///---   Display on Chart
                if (p_Display_OnOff == 1)
                {
                    Display_on_Chart_TopLeft();
                    Display_on_Chart_TopRight();
                    Display_RowColumn();
                }
                //END IF


                // RESET THE FLAG
                Flag_isExecuting_01 = false;
            }
            //END if
            
        }
        //END METHOD Upate_Dynamic_Values()

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    OnPositionsClosed                                   ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void OnPositionsClosed(PositionClosedEventArgs args)
        {
            ///---   UPDATE POSITIONS COUNT   --------
            Get_Positions_Count();

            ///---   Vol PipCost and Hi and Low values  --------
            Get_Volume_n_PipCost();


            //var pos = args.Position;

        }
        //END METHOD OnPositionsClosed

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    OnPositionsOpened                                   ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void OnPositionsOpened(PositionOpenedEventArgs args)
        {
            ///---   UPDATE POSITIONS COUNT   --------
            Get_Positions_Count();

            ///---   Vol PipCost and Hi and Low values  --------
            Get_Volume_n_PipCost();

            //UPDATE AVERAGE TAKE PROFIT
            Adjust_Buy_Pos_TakeProfits(Calculate_AveragePosition_Price(TradeType.Buy), p_Avg_TakeProfit);
            Adjust_Sell_Pos_TakeProfits(Calculate_AveragePosition_Price(TradeType.Sell), p_Avg_TakeProfit);

            
            
            //var pos = args.Position;

        }
        //END METHOD OnPositionsOpened

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Initialize_All_Array_OnStart                        ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Initialize_All_Array_OnStart()
        {

        }
        //END METHOD Initialize_All_Array_OnStart


        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Declare_All_Arrays                                  ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Declare_All_Arrays()
        {

        }
        //END METHOD Declare_All_Arrays

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Order_Send                                          ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Order_Send(TradeType tradeType, long volumeToUse, string label, double sl, double tp)
        {

            // METHOD EXCLUSIVE CONTROL FLAG
            if (Flag_isExecuting_04 == false)
            {
                // SET THE FLAG
                Flag_isExecuting_04 = true;


                // FIRST CHECK VOLUME
                if (volumeToUse > 0)
                {
                    //PLACE ORDER
                    var t_Result = ExecuteMarketOrder(tradeType, Symbol.Name, volumeToUse, label, sl, tp, "My Trade");

                    // RESULT OF MARKET ORDER
                    if (t_Result.IsSuccessful)
                    {
                        // STORE BUY TIME
                        if (tradeType == TradeType.Buy)
                        {
                            DT_Last_Buy = Bars.OpenTimes.Last(0);
                            //Print("#### BUY Position OPENED");
                        }

                        // STORE SELL TIME
                        if (tradeType == TradeType.Sell)
                        {
                            DT_Last_Sell = Bars.OpenTimes.Last(0);
                            //Print("#### SELL Position OPENED");
                        }
                    }
                    else
                    {
                        // PRINT ERROR IF BUY
                        if (tradeType == TradeType.Buy)
                            Print(tradeType, ", BUY Error : in Opening Position at = ", Symbol.Ask, ",  due to ", t_Result.Error);

                        // PRINT ERROR IF SELL
                        if (tradeType == TradeType.Sell)
                            Print(tradeType, ", SELL Error : in Opening Position at = ", Symbol.Bid, ",  due to ", t_Result.Error);

                    }
                    //END IF ELSE
                }
                else
                {
                    Print("Error : Volume = 0 OR LESS. Volume = ", volumeToUse);
                }
                //END IF ELSE


                // SET THE FLAG
                Flag_isExecuting_04 = false;
            }
            //END IF ELSE

        }
        // END METHOD Order_Send

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Get_Reset_Values_Manager                            ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Get_Reset_Values_Manager()
        {
            //-- RESEST THE BELOW VALUES ON CLOSE_ALL POSITIONS
            Start_Equity = Account.Balance;
            Highest_Equity = Start_Equity;
            Lowest_Equity = Start_Equity;
            Lowest_Margin = 100000.00;
            
            // RESET THE COUNT
            Get_Positions_Count();
            
        }
        //END METHOD Get_Reset_Values_Manager

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Get_Equity_Manager                                  ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Get_Equity_Manager()
        {
            // IF EQUITY MANGER IS ENABLED
            if (p_Equity_Manager == 1)
            {
                // EXCLUSIVE LOOP
                if (Flag_isExecuting_05 == false)
                {
                    Flag_isExecuting_05 = true;

                    int t_Equity = (int)Account.Equity;

                    // TO AVOID CLOSE-ALL BY MISTAKE IF DISCONECTION FROM C-SERVER
                    if (Account.Balance != Account.Equity)
                    {

                        if (t_Equity > (Start_Equity + p_NET_PL_inc_By) && (p_NET_PL_inc_By != 0))
                        {
                            Print("Condition # 001 : Start Equity INCREASED BY ", p_NET_PL_inc_By);

                            //-- CLOSE POSITION WITH SPECIFIC LABEL 
                            CloseAll_Positions();

                            //-- RESEST VALUES ON CLOSE ALL POSITIONS
                            Get_Reset_Values_Manager();
                        }
                        //END IF
                        
                        if (t_Equity < (Start_Equity - p_NET_PL_dec_By) && (p_NET_PL_dec_By != 0))
                        {
                            Print("Condition # 002 : Start Equity DECREASED BY ", p_NET_PL_dec_By);

                            // CLOSE POSITION WITH SPECIFIC LABEL 
                            CloseAll_Positions();

                            //-- RESEST VALUES ON CLOSE ALL POSITIONS
                            Get_Reset_Values_Manager();

                        }
                        //END IF
                        
                    }
                    //END IF

                    // RESET THE FLAG
                    Flag_isExecuting_05 = false;
                }
                //END IF
            }
            //END IF p_Equity_Manager
        }
        //END MEHTOD Get_Equity_Manager

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Get_Margin_PipCost_Manager                          ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Get_Margin_PipCost_Manager()
        {
            // IF EQUITY MANGER IS ENABLED
            if (p_Margin_Manager == 1)
            {
                // EXCLUSIVE LOOP
                if (Flag_isExecuting_08 == false)
                {
                    Flag_isExecuting_08 = true;
                                      
                    // UPDATE POSITION COUNT
                    Get_Positions_Count();
                    
                    double t_Margin = 0;
                    if(Count_Total_Positions > 0)
                        t_Margin = (double)Account.MarginLevel;
                                        
                    // TO AVOID CLOSE-ALL BY MISTAKE IF DISCONECTION FROM C-SERVER
                    if (Account.Balance != Account.Equity && Count_Total_Positions > 0)
                    {
                        // MARGIN % LEVEL CONTROL
                        if (t_Margin <= (p_Margin_dec_below) && (p_Margin_dec_below != 0))
                        {
                            Print("Condition # 003 : Account Margin fell below : ", p_Margin_dec_below);

                            //-- CLOSE POSITION WITH SPECIFIC LABEL 
                            CloseAll_Positions();

                            //-- RESEST VALUES ON CLOSE ALL POSITIONS
                            Get_Reset_Values_Manager();
                        }
                        //END IF
                        
                        // PIP COST CONTROL 
                        if (Pip_Cost < (p_PipCost_dec_below * -1) && (p_PipCost_dec_below != 0))
                        {
                            Print("Condition # 004 : Pip Cost has fall below : ", p_PipCost_dec_below);

                            // CLOSE POSITION WITH SPECIFIC LABEL 
                            CloseAll_Positions();

                            //-- RESEST VALUES ON CLOSE ALL POSITIONS
                            Get_Reset_Values_Manager();

                        }
                        //END IF

                        //HARD EXIT - CLOSE ALL POSITION ON MARGIN LEVEL FALLING BELOW 100%
                        if (t_Margin < (p_Min_Margin_Level) && (p_Min_Margin_Level != 0) && Count_Total_Positions > 0)
                        {
                            Print("Condition # 005 : Account Margin fell below min. Level: ", p_Min_Margin_Level);

                            //-- CLOSE POSITION WITH SPECIFIC LABEL 
                            CloseAll_Positions();

                            //-- RESEST VALUES ON CLOSE ALL POSITIONS
                            Get_Reset_Values_Manager();


                        }
                        //END IF
                       

                    }
                    //END IF

                    // RESET THE FLAG
                    Flag_isExecuting_08 = false;
                }
                //END IF
            }
            //END IF p_Equity_Manager
        }
        //END MEHTOD Get_Margin_PipCost_Manager

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Get_Positions_Count                                 ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private void Get_Positions_Count()
        {
            // METHOD EXCLUSIVE CONTROL FLAG
            if (Flag_isExecuting_06 == false)
            {
                // SET THE FLAG
                Flag_isExecuting_06 = true;

                int t_Any = 0, t_Total = 0, t_Buy = 0, t_Sell = 0;

                foreach (var pos in Positions)
                {
                    t_Any += 1;

                    if (pos.SymbolName == Symbol.Name)
                    {
                        // TOTAL SYMBOL POS COUNT
                        t_Total += 1;

                        // BUY COUNT
                        if (pos.TradeType == TradeType.Buy)
                            t_Buy += 1;

                        // SELL COUNT
                        if (pos.TradeType == TradeType.Sell)
                            t_Sell += 1;
                    }
                    //END IF
                }
                //END FOR-EACH

                ///--   RECORD HIGHEST AND LOWEST --------
                if (t_Buy > Highest_Buy_Count)
                    Highest_Buy_Count = t_Buy;

                if (t_Sell > Highest_Sell_Count)
                    Highest_Sell_Count = t_Sell;

                ///--   UPDATE THE GLOBAL VARIABLE -------
                Count_Total_Positions = t_Total;
                Count_Buy_Positions = t_Buy;
                Count_Sell_Positions = t_Sell;


                // RESET THE FLAG
                Flag_isExecuting_06 = false;
            }
            //END IF

        }
        //END METHOD Get_Positions_Count


        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Get_Highest_Lowest_Values                           ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////     
        private void Get_Highest_Lowest_Values()
        {

            
            double t_Equity = Account.Equity;
            double t_Balance = Account.Balance;
            double t_Margin = 100000;

            if (Count_Total_Positions > 0)
                t_Margin = (double)Account.MarginLevel;

            // CHECK IF DISCONNECTION FROM SERVER. 
            // AS IN cTRADER BOTH BECOMES EQUAL
            if (t_Equity != t_Balance)
            {
                // HIGH AND LOW VALUES      
                if (t_Equity > Highest_Equity)
                    Highest_Equity = t_Equity;

                if (t_Equity < Lowest_Equity)
                    Lowest_Equity = t_Equity;

                if (t_Margin < Lowest_Margin)
                    Lowest_Margin = t_Margin; 
            }
            //END IF
        }
        //END METHOD Get_Highest_Lowest_Values

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                        Get_Volume_n_PipCost                                        ////
        ////////////////////////////////////////////////////////////////////////////////////////////        
        private void Get_Volume_n_PipCost()
        {

            // METHOD EXCLUSIVE CONTROL FLAG
            if (Flag_isExecuting_02 == false)
            {
                // SET THE FLAG
                Flag_isExecuting_02 = true;

                double t_Buy_Vol = 0, t_Sell_Vol = 0, t_Net_Vol = 0;

                // GET VOLUME
                foreach (var pos in Positions)
                {
                    // BUY VOLUME
                    if (pos.Label == p_Label && pos.TradeType == TradeType.Buy)
                    {
                        t_Buy_Vol += pos.VolumeInUnits;
                    }
                    //END IF

                    // SELL VOLUME
                    if (pos.Label == p_Label && pos.TradeType == TradeType.Sell)
                    {
                        t_Sell_Vol += pos.VolumeInUnits;
                    }
                    //END IF
                }
                //END FOR EACH

                // NET VOLUME
                t_Net_Vol = t_Buy_Vol - t_Sell_Vol;

                // UPDATE VALUES
                Pip_Cost = t_Net_Vol * Symbol.PipValue;
                Vol_Total = t_Net_Vol;
                Vol_Total_Buy = t_Buy_Vol;
                Vol_Total_Sell = t_Sell_Vol;

                //RECORD HIGHEST AND LOWEST BUY SELL VOLUME
                if (Vol_Total_Buy > Highest_Vol_Buy)
                    Highest_Vol_Buy = Vol_Total_Buy;
                //RECORD HIGHEST AND LOWEST BUY SELL VOLUME
                if (Vol_Total_Sell > Highest_Vol_Sell)
                    Highest_Vol_Sell = Vol_Total_Sell;

                //RECORD HIGHEST & LOWEST PIP COST
                if (Pip_Cost > Pip_Cost_Highest)
                    Pip_Cost_Highest = Pip_Cost;
                if (Pip_Cost < Pip_Cost_Lowest)
                    Pip_Cost_Lowest = Pip_Cost;



                // RESET THE FLAG
                Flag_isExecuting_02 = false;
            }
            //END IF

        }
        //END FUNCTION Get_Volume_n_PipCost

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                        Get_NetPL_of_This_Pair_Only                                 ////
        ////////////////////////////////////////////////////////////////////////////////////////////        
        private void Get_NetPL_of_This_Pair_Only()
        {
            // METHOD EXCLUSIVE CONTROL FLAG
            if (Flag_isExecuting_03 == false)
            {
                // SET THE FLAG
                Flag_isExecuting_03 = true;

                double t_1 = 0, t_2 = 0, t_3 = 0;

                // FOR POSITIONS NET PL
                foreach (var pos in Positions)
                {
                    ///---   NET PL OF ALL POSITIONS    ------------------------------------------
                    if (pos.SymbolName == Symbol.Name)
                    {
                        t_1 += pos.NetProfit;
                    }
                    //END IF

                    ///---   BUY POSITIONS NET PL   ----------------------------------------------
                    if (pos.SymbolName == Symbol.Name && pos.TradeType == TradeType.Buy)
                    {
                        t_2 += pos.NetProfit;
                    }
                    //END IF

                    ///---   SELL  POSITIONS NET PL   ----------------------------------------------
                    if (pos.SymbolName == Symbol.Name && pos.TradeType == TradeType.Sell)
                    {
                        t_3 += pos.NetProfit;
                    }
                    //END IF
                }
                //END FOREACH

                NetPL_Total = t_1;
                NetPL_Total_Buy = t_2;
                NetPL_Total_Sell = t_3;

                // RECORD HIGHEST AND LOWEST NET PL  ---------------
                if (Highest_NetPL <= NetPL_Total)
                {
                    Highest_NetPL = NetPL_Total;
                }
                //END IF
                if (Lowest_NetPL > NetPL_Total)
                {
                    Lowest_NetPL = NetPL_Total;
                }
                // --------------------------------------------------

                // RESET THE FLAG
                Flag_isExecuting_03 = false;
            }
            //END IF

        }
        //END METHOD Get_NetPL_of_This_Pair_Only

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Limit_Volume                                        ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private long Limit_Volume(long volumeIn)
        {
            var symbolVolumeMin = Symbol.VolumeInUnitsMin;

            var symbolVolumeMax = (long)p_Final_Max_Volume;

            var result = volumeIn;

            if (result < symbolVolumeMin)
                result = (long)symbolVolumeMin;

            if (result > symbolVolumeMax)
                result = (long)symbolVolumeMax;

            return (result);
        }
        //END METHOD Limit_Volume

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////                                    Calculate_Volume                                              //////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private long Calculate_Volume(TradeType tradeType)
        {
            int t_no_Of_Positions = 0;

            // IF BUY
            if (tradeType == TradeType.Buy)
                t_no_Of_Positions = Count_Buy_Positions;

            // IF SELL
            if (tradeType == TradeType.Sell)
                t_no_Of_Positions = Count_Sell_Positions;

            //var calculatedVolume = Symbol.NormalizeVolume(p_FirstVolume * Math.Pow(t_Vol_Exp, t_no_Of_Positions));
            var calculatedVolume = (long)Symbol.NormalizeVolumeInUnits(p_FirstVolume + (p_Volume_Increment * t_no_Of_Positions));

            return (calculatedVolume);
        }
        // END METHOD CalculateVolume

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Find_HighestPosition_Price                          ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private double Find_HighestPosition_Price(TradeType tradeType)
        {
            double highestPrice = 0;

            foreach (var pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name && pos.TradeType == tradeType)
                {
                    if (highestPrice == 0)
                    {
                        highestPrice = pos.EntryPrice;
                        continue;
                    }
                    if (pos.EntryPrice > highestPrice)
                        highestPrice = pos.EntryPrice;
                }
            }
            ///---   END FOREACH

            return highestPrice;
        }
        // END METHOD Find_HighestPosition_Price

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    Find_LowestPosition_Price                           ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        private double Find_LowestPosition_Price(TradeType tradeType)
        {
            double lowestPrice = 0;

            foreach (var pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name && pos.TradeType == tradeType)
                {
                    if (lowestPrice == 0)
                    {
                        lowestPrice = pos.EntryPrice;
                        continue;
                    }
                    if (pos.EntryPrice < lowestPrice)
                        lowestPrice = pos.EntryPrice;
                }
                //END IF
            }
            //END FOR EACH

            return lowestPrice;
        }
        // END METHOD Find_LowestPosition_Price

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////                                    Adjust_Buy_Pos_TakeProfits                                    //////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void Adjust_Buy_Pos_TakeProfits(double average_Price, int averageTakeProfit)
        {
            foreach (var buyPosition in Positions)
            {
                if (buyPosition.Label == p_Label && buyPosition.SymbolName == Symbol.Name)
                {
                    if (buyPosition.TradeType == TradeType.Buy)
                    {
                        double? calculatedTakeProfit = Math.Round(average_Price + (averageTakeProfit * Symbol.PipSize), Symbol.Digits);

                        //if (buyPosition.NetProfit <= 0)
                            if (buyPosition.TakeProfit != calculatedTakeProfit)
                            {
                                ModifyPosition(buyPosition, buyPosition.StopLoss, calculatedTakeProfit);
                                Print("-------- Buy Position Take Profit Modified");
                            }
                        //END IF
                    }
                }
            }
        }
        // END METHOD Adjust_Buy_Pos_TakeProfits

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////                                    Adjust_Sell_Pos_TakeProfits                                   //////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void Adjust_Sell_Pos_TakeProfits(double average_Price, int averageTakeProfit)
        {
            foreach (var sellPosition in Positions)
            {
                if (sellPosition.Label == p_Label && sellPosition.SymbolName == Symbol.Name)
                {
                    if (sellPosition.TradeType == TradeType.Sell)
                    {
                        double? calculatedTakeProfit = Math.Round(average_Price - (averageTakeProfit * Symbol.PipSize), Symbol.Digits);

                        //if (sellPosition.NetProfit <= 0)
                            if (sellPosition.TakeProfit != calculatedTakeProfit)
                            {
                                ModifyPosition(sellPosition, sellPosition.StopLoss, calculatedTakeProfit);
                                Print("-------- SELL Position Take Profit Modified");
                            }
                        //END IF
                    }
                }
            }
            
        }
        // END METHOD Adjust_Sell_Pos_TakeProfits

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////                                    Calculate_AveragePosition_Price                               //////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private double Calculate_AveragePosition_Price(TradeType tradeType)
        {
            double average_Price = 0;
            double sum_of_Price_x_Vol = 0;
            double total_Volume = 0;


            foreach (var pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name)
                {
                    if (pos.TradeType == tradeType)
                    {
                        sum_of_Price_x_Vol += pos.EntryPrice * pos.VolumeInUnits;
                        total_Volume += pos.VolumeInUnits;
                    }
                }

            }

            if (sum_of_Price_x_Vol > 0 && total_Volume > 0)
                average_Price = Math.Round(sum_of_Price_x_Vol / total_Volume, Symbol.Digits);

            //Print("Average Price = " + average_Price);
            return average_Price;
        }
        // END METHOD Calculate_AveragePosition_Price

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                    CLOSE ALL  POSITIONS                                ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////        
        private void CloseAll_Positions()
        {
            foreach (var pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name)
                {
                    ClosePosition(pos);
                }
                //END IF
            }
            //END FOR-EACH
        }
        //END METHOD CloseAll_Positions

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                  Close All_Positions_with_Label                        ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////        
        private void CloseAll_Positions_with_Label(string label)
        {
            foreach (var pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name && pos.Label == label)
                {
                    ClosePosition(pos);
                }
                //END IF
            }
            //END FOR-EACH
        }
        //END METHOD CloseAll_Positions_with_Label

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                 Close All_Positions_with_Trade_Type                    ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////        
        private void CloseAll_Positions_with_Trade_Type(TradeType t_TradeType)
        {
            foreach (var pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name && pos.TradeType == t_TradeType)
                {
                    ClosePosition(pos);
                }
                //END IF
            }
            //END FOR-EACH
        }
        //END METHOD CloseAll_Positions_with_Trade_Type

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                 Display_on_Chart_TopLeft                               ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        protected void Display_on_Chart_TopLeft()
        {

            int Line_No = 1;

            Chart.DrawStaticText("DTL01", my_NL(Line_No + 0) + my_Tabs(1) + "cBOT Name : " + ToString(), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Heading_2);
            Chart.DrawStaticText("DTL02", my_NL(Line_No + 1) + my_Tabs(1) + "MADE   BY   ///S.KHAN    [skhan.projects@gmail.com]", VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Heading_2);
            Chart.DrawStaticText("DTL03", my_NL(Line_No + 2) + my_Tabs(1) + "Date and Time = " + Time, VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Heading_1);

            Chart.DrawStaticText("D104", my_NL(Line_No + 3) + my_Tabs(1) + "", VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Heading_1);

            Chart.DrawStaticText("D105", my_NL(Line_No + 4) + my_Tabs(1) + "Equity: " + "  Hi(" + Highest_Equity.ToString("##,###") + "),  Lo(" + Lowest_Equity.ToString("##,###") + ")" + " Lowest Margin (" + Lowest_Margin.ToString("##,###") + ")", VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);
            Chart.DrawStaticText("D106", my_NL(Line_No + 5) + my_Tabs(1) + "Pip Cost: " + Pip_Cost.ToString("f2") + ",  Hi(" + Pip_Cost_Highest.ToString("f2") + ")" + "),  Lo(" + Pip_Cost_Lowest.ToString("f2") + ")", VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);
            Chart.DrawStaticText("D107", my_NL(Line_No + 6) + my_Tabs(1) + "Total Volume: " + Vol_Total.ToString("##,###") + ",  Vol Buy: " + Vol_Total_Buy.ToString("##,###") + ",  Vol Sell:" + Vol_Total_Sell.ToString("##,###"), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);
            Chart.DrawStaticText("D108", my_NL(Line_No + 7) + my_Tabs(1) + "Highest Vol (Buy): " + Highest_Vol_Buy.ToString("##,###") + ",  (Sell): " + Highest_Vol_Sell.ToString("##,###") + ",  Vol Sell:" + Vol_Total_Sell.ToString("##,###"), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);

            Chart.DrawStaticText("D109", my_NL(Line_No + 8) + my_Tabs(1) + "", VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);

            Chart.DrawStaticText("D201", my_NL(Line_No + 9) + my_Tabs(1) + "Net PL: " + NetPL_Total.ToString("##,###") + ",  Buy PL: " + NetPL_Total_Buy.ToString("##,###") + ",  Sell PL:" + NetPL_Total_Sell.ToString("##,###"), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);
            Chart.DrawStaticText("D202", my_NL(Line_No + 10) + my_Tabs(1) + "Hi PL: " + Highest_NetPL.ToString("##,###") + ",  Low PL: " + Lowest_NetPL.ToString("##,###"), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);

            Chart.DrawStaticText("D203", my_NL(Line_No + 11) + my_Tabs(1) + "", VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);

            Chart.DrawStaticText("D204", my_NL(Line_No + 12) + my_Tabs(1) + "Total Count: " + Count_Total_Positions.ToString("##,###") + ",  Buy Count: " + Count_Buy_Positions.ToString("##,###") + ",  Sell Count:" + Count_Sell_Positions.ToString("##,###"), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);
            //Chart.DrawStaticText("D205", my_NL(Line_No + 13) + my_Tabs(1) + "Hi PL: " + Highest_NetPL.ToString("##,###") + ",  Low PL: " + Lowest_NetPL.ToString("##,###"), VerticalAlignment.Top, HorizontalAlignment.Left, Clr_Value_01);





        }
        //END METHOD Display_on_Chart_TopLeft()

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                 Display_on_Chart_TopRight                               ////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
        protected void Display_on_Chart_TopRight()
        {

            int Line_No = 2;

            Chart.DrawStaticText("DTR01", my_NL(Line_No + 1) + my_Tabs(1) + "Current Spread: " + Current_Spread.ToString("f2"), VerticalAlignment.Top, HorizontalAlignment.Right, Clr_Value_02);
            Chart.DrawStaticText("DTR02", my_NL(Line_No + 2) + my_Tabs(1) + "Volatility: " + Current_Volitality.ToString("f2"), VerticalAlignment.Top, HorizontalAlignment.Right, Clr_Value_02);

            Chart.DrawStaticText("DTR03", my_NL(Line_No + 3) + my_Tabs(1) + "", VerticalAlignment.Top, HorizontalAlignment.Right, Clr_Value_02);



        }
        //END METHOD Display_on_Chart_TopRight()

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////                 Display_RowColumn                                      ////////////////
        //////////////////////////////////////////////////////////

GoldnOil750's avatar
GoldnOil750

Joined on 07.04.2015

  • Distribution: Free
  • Language: C#
  • Trading platform: cTrader Automate
  • File name: Yr22_SKhan_Grid_v1.algo
  • Rating: 0
  • Installs: 965
  • Modified: 10/04/2023 05:45
Comments
Log in to add a comment.
FR
fredrioscava · 9 months ago

Is there a way to keep the takeprofit fixed, without it being fluctuating?

IA
ianmackers · 11 months ago

The source code seems be be snipped… Are you able to reupload or provide a link to it?

AL
algoprotocol · 1 year ago

Can you provide some information on the initial settings? Just to start playing around with the backtest a bit.