C# StopLoss Help - Really simple coding

Created at 05 Dec 2013, 19:27
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
KE

Kevin

Joined 05.12.2013

C# StopLoss Help - Really simple coding
05 Dec 2013, 19:27


Hi, here is the end of my code, could someone please write in a stop loss of either pips or equity. Just use the number 50 for now and I can adjust it as I need it.

Thanks in advance.
 

My code ends:

        }
        private void ClosePosition()
        {
            if (_position != null)
            {
                Trade.Close(_position);
                _position = null;
            }
        }

        private void Buy()
        {
            Trade.CreateBuyMarketOrder(Symbol, Volume);
        }

        private void Sell()
        {
            Trade.CreateSellMarketOrder(Symbol, Volume);
        }

        protected override void OnTick()
        {
            foreach (var position in Account.Positions)
            {
                if (position.GrossProfit >= 90)
                {
                    Trade.Close(position);
                }

            }
        }
    }
}


@Kevin
Replies

Kevin
05 Dec 2013, 20:09

I saw that (or something similar) but don't know how to introduce that to my code:

 

        protected override void OnBar()
        {
            if (Trade.IsExecuting)
                return;

            bool isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
            bool isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;

            if (_macd.Histogram.LastValue > 0.0 && _macd.Signal.IsRising() && !isLongPositionOpen)
            {
                ClosePosition();
                Buy();
            }

            if (_macd.Histogram.LastValue < 0.0 && _macd.Signal.IsFalling() && !isShortPositionOpen)
            {
                ClosePosition();
                Sell();
            }
        }
        private void ClosePosition()
        {
            if (_position != null)
            {
                Trade.Close(_position);
                _position = null;
            }
        }

        private void Buy()
        {
            Trade.CreateBuyMarketOrder(Symbol, Volume);
        }

        private void Sell()
        {
            Trade.CreateSellMarketOrder(Symbol, Volume);
        }

        protected override void OnTick()
        {
            foreach (var position in Account.Positions)
            {
                if (position.GrossProfit >= 9)
                {
                    Trade.Close(position);
                }

            }
        }
    }
}


@Kevin

Cerunnos
05 Dec 2013, 20:15

With Trade.ModifyPosition(position, _stopLoss, _takeProfit) you can add SL & TP (see example above)


@Cerunnos

Kevin
05 Dec 2013, 22:08

C# is completely new to me (how i've managed to get this far is a wonder). So could you write this for me pleeeeeeease   :D

 

My total code at the moment is:

using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Robots
{
    [Robot()]
    public class 30k : Robot
    {
        private MacdHistogram _macd;
        private Position _position;

        [Parameter(DefaultValue = 30000, MinValue = 0)]
        public int Volume { get; set; }

        [Parameter("Period", DefaultValue = 12)]
        public int Period { get; set; }

        [Parameter("Long Cycle", DefaultValue = 22)]
        public int LongCycle { get; set; }

        [Parameter("Short Cycle", DefaultValue = 9)]
        public int ShortCycle { get; set; }

        protected override void OnStart()
        {
            _macd = Indicators.MacdHistogram(LongCycle, ShortCycle, Period);
        }

        protected override void OnBar()
        {
            if (Trade.IsExecuting)
                return;

            bool isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
            bool isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;

            if (_macd.Histogram.LastValue > 0.0 && _macd.Signal.IsRising() && !isLongPositionOpen)
            {
                ClosePosition();
                Buy();
            }

            if (_macd.Histogram.LastValue < 0.0 && _macd.Signal.IsFalling() && !isShortPositionOpen)
            {
                ClosePosition();
                Sell();
            }
        }
        private void ClosePosition()
        {
            if (_position != null)
            {
                Trade.Close(_position);
                _position = null;
            }
        }

        private void Buy()
        {
            Trade.CreateBuyMarketOrder(Symbol, Volume);
        }

        private void Sell()
        {
            Trade.CreateSellMarketOrder(Symbol, Volume);
        }

        protected override void OnTick()
        {
            foreach (var position in Account.Positions)
            {
                if (position.GrossProfit >= 24)
                {
                    Trade.Close(position);
                }

            }
        }
    }
}


@Kevin

Kevin
05 Dec 2013, 23:33

It's ok, I did it. Learning all the time!  :)

 

Thanks for your help.


@Kevin

Cerunnos
06 Dec 2013, 00:02

Hi! I have not tested the following code. It's just a basic framework with which you can start. You will undoubtedly need to make adjustments and for that you need the basics in C # and cAlgo API. The strategy also seems a bit too easy. Improvements are certainly necessary. Happy coding...

 

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;

 
     namespace cAlgo.Robots
    {
    [Robot(TimeZone = TimeZones.UTC)]
    public class _30K_Robot : Robot
    {
         private MacdHistogram _macd;
         private Position _position;
         private double startingBalance;
         private const double BalancePercent = 0.85;  // change the value = max. DrawDown

         [Parameter(DefaultValue = 30000, MinValue = 0)]
         public int Volume { get; set; }
         
         [Parameter("Inital Stop Loss (pips)", DefaultValue = 10.0)]
         //SL in pips
         public int init_StopLoss { get; set; }

         [Parameter("Period", DefaultValue = 12)]
         public int Period { get; set; }

         [Parameter("Long Cycle", DefaultValue = 22)]
         public int LongCycle { get; set; }

         [Parameter("Short Cycle", DefaultValue = 9)]
         public int ShortCycle { get; set; }

         protected override void OnStart()
         {
             _macd = Indicators.MacdHistogram(LongCycle, ShortCycle, Period);
             startingBalance = Account.Balance;
             
         }
         
         
        protected void CheckBalance()
         {
             if (Account.Equity <= startingBalance * BalancePercent)
             {
                 foreach (var pos in Account.Positions)
                 {
                     if(pos.Label == "my_FirstRobot")
                     Trade.Close(pos);
                 }
                 Stop();
                 Notifications.SendEmail("xy@domain.net", "xy@domain.net", "DrawDown!", "Robot was stopped! Check It!");
                 Print("DrawDown!");
             }
         }


         protected override void OnTick()
         {        
             if (Trade.IsExecuting)
                 return;
                 
              CheckBalance();
                 
             foreach (var position in Account.Positions)
             {
                 if (position.Label == "my_FirstRobot" && position.GrossProfit >= 24)
                 {
                     Trade.Close(position);
                 }

             }

             bool isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
             bool isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;

             if (_macd.Histogram.LastValue > 0.0 && _macd.Signal.IsRising() && !isLongPositionOpen)
             {
                 ClosePosition();
                 Buy();
             }

             if (_macd.Histogram.LastValue < 0.0 && _macd.Signal.IsFalling() && !isShortPositionOpen)
             {
                 ClosePosition();
                 Sell();
             }
         }
         private void ClosePosition()
         {
             if (_position != null)
             {
                 Trade.Close(_position);
                 _position = null;
             }
         }

         private void Buy()
         {
             var request = new MarketOrderRequest(TradeType.Buy, Volume)  
                        {                        
                        Label = "my_FirstRobot",
                        StopLossPips = init_StopLoss                     
                        };
                        Trade.Send(request);   
         }

         private void Sell()
         {
             var request = new MarketOrderRequest(TradeType.Sell, Volume)  
                        {                        
                        Label = "my_FirstRobot",
                        StopLossPips = init_StopLoss                     
                        };
                        Trade.Send(request);   
         }

        
         
         
        
     }
     
     }


@Cerunnos

Kevin
06 Dec 2013, 01:39

Hi, thanks for that   :)   Yes much adjustent needed *fingers-crossed*.

I also want a similar robot that places trades based on the crossover of MacD and Signal lines, relative to each other. If the histo crosses above signal, buy. If it crosses down, sell. Simples. But I can't find anything on here. I found the HasCrossedBelow function but am not having much luck with it   :(

Any help would be much appreciated and thanks again for the above.


@Kevin

Kevin
06 Dec 2013, 12:25

I've done it! Thanks again for your help, I have a much better understanding of C# now.


@Kevin