// -------------------------------------------------------------------------------------------------
//
//    This code is a cAlgo API sample.
//
//    This robot is intended to be used as a sample and does not guarantee any particular 
//    outcome or
//    profit of any kind. Use it at your own risk
//
// -------------------------------------------------------------------------------------------------
//Please do not change the following 3 lines.
using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Robots
{
    [Robot("Sample Buy Trailing Robot")]
    public class SampleSellTrailing : Robot//Declaration of the Robot's name class
    {
        //The parameters of the robot
        //Parameters like period, volume
        //stoploss and takeprofit
        [Parameter(DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 50)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 50)]
        public int TakeProfit { get; set; }

        [Parameter("Trigger (pips)", DefaultValue = 20)]
        public int Trigger { get; set; }

        [Parameter("Trailing Stop (pips)", DefaultValue = 10)]
        public int TrailingStop { get; set; }


        private Position position;
        //This method is called onstart of the robot, once
        protected override void OnStart()
        {
            //We create a sell market order
            Trade.CreateSellMarketOrder(Symbol, Volume);
        }
        //This method is called whenever a new position is being opened
        protected override void OnPositionOpened(Position openedPosition)
        {
            position = openedPosition;

            double? stopLossPrice = null;
            double? takeProfitSize = null;

            if (StopLoss != 0)
                stopLossPrice = position.EntryPrice + StopLoss * Symbol.PipSize;

            if (TakeProfit != 0)
                takeProfitSize = position.EntryPrice - TakeProfit * Symbol.PipSize;

            Trade.ModifyPosition(openedPosition, stopLossPrice, takeProfitSize);
        }
        //This method is called on each incoming Tick
        protected override void OnTick()
        {
            if (position == null) return;

            double distance = position.EntryPrice - Symbol.Ask;

            if (distance >= Trigger * Symbol.PipSize)
            {
                double newStopLossPrice = Symbol.Ask + TrailingStop * Symbol.PipSize;
                if (position.StopLoss == null || newStopLossPrice < position.StopLoss)
                {
                    Trade.ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                }
            }
        }
        //This method is called whenever a position is closed
        protected override void OnPositionClosed(Position closedPosition)
        {
            Stop();
        }
    }
}