Topics
20 Jul 2018, 22:20
 1183
 1
02 Jul 2018, 12:25
 2529
 4
22 Mar 2018, 17:18
 1375
 5
06 Jan 2018, 13:53
 2088
 4
05 Jul 2016, 18:57
 2860
 3
09 Mar 2016, 17:25
 3008
 3
01 Aug 2015, 15:06
 3061
 3
Replies

tradermatrix
29 Oct 2014, 12:14

hello 
on a robot has multiple indicators, can you give me a formula for spacing trades. 
eg > 30 pips buy and  > 30 pips sell
it will not deal nearly identical trades. 
kind regards


@tradermatrix

tradermatrix
14 Oct 2014, 23:59

I have added "Delay Entry (Pips)" adjustable. 
to optimizer 
good trade 
kind regards 

 

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

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MyRobot : Robot
    {
        [Parameter("MA Type")]
        public MovingAverageType MAType { get; set; }

        [Parameter()]
        public DataSeries SourceSeries { get; set; }

        [Parameter("Slow Periods", DefaultValue = 100)]
        public int SlowPeriods { get; set; }

        [Parameter("Fast Periods", DefaultValue = 14)]
        public int FastPeriods { get; set; }

        [Parameter("Delay Entry (Pips)", DefaultValue = 5)]
        public double DelayEntry { get; set; }

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

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

        [Parameter(DefaultValue = 160)]
        public int TakeProfit { get; set; }

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

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

        private MovingAverage slowMa;
        private MovingAverage fastMa;
        private const string label = "Sample Trend Robot";

        protected override void OnStart()
        {
            fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
            slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
        }

        protected override void OnTick()
        {
            TRAILING();
            {
                var longPosition = Positions.Find(label, Symbol, TradeType.Buy);
                var shortPosition = Positions.Find(label, Symbol, TradeType.Sell);

                var SlowMa = slowMa.Result.Last(0);
                var FastMa = fastMa.Result.Last(0);


                if (FastMa < SlowMa - DelayEntry * Symbol.TickSize && longPosition == null)
                {
                    if (shortPosition != null)
                        ClosePosition(shortPosition);
                    ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, label, StopLoss, TakeProfit);
                }
                else if (SlowMa < FastMa - DelayEntry * Symbol.TickSize && shortPosition == null)
                {
                    if (longPosition != null)
                        ClosePosition(longPosition);
                    ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, label, StopLoss, TakeProfit);
                }
            }
        }

        private void TRAILING()
        {
            if (TrailingStop > 0 && Trigger > 0)
            {

                Position[] positions = Positions.FindAll(label, Symbol);



                foreach (Position position in positions)
                {


                    if (position.TradeType == TradeType.Sell)
                    {

                        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)
                            {

                                ModifyPosition(position, newStopLossPrice, position.TakeProfit);

                            }
                        }
                    }


                    else
                    {

                        double distance = Symbol.Bid - position.EntryPrice;


                        if (distance >= Trigger * Symbol.PipSize)
                        {

                            double newStopLossPrice = Symbol.Bid - TrailingStop * Symbol.PipSize;


                            if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                            {

                                ModifyPosition(position, newStopLossPrice, position.TakeProfit);

                            }
                        }
                    }
                }
            }
        }
    }
}

 


@tradermatrix

tradermatrix
04 Oct 2014, 16:03

RE:

Pannekoek said:

In your OnStart method, you create a new variable  (rsi_m5) and assign the RSI indicator to it. Instead you should have used the "rsi" variable.

yes, thank you
the solution;

 

   protected override void OnStart()
        {
            var _m5_series = MarketData.GetSeries(TimeFrame.Minute5);
            rsi = Indicators.RelativeStrengthIndex(_m5_series.Close, 14);

}

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

several indicators;

   protected override void OnStart()
{

var _m5_series = MarketData.GetSeries(TimeFrame.Minute5);

rsi = Indicators.RelativeStrengthIndex(_m5_series.Close, 14);

 

var m3_series = MarketData.GetSeries(TimeFrame.Minute3);

var sma_m3 = Indicators.SimpleMovingAverage(m3_series.Close, 54);

 

var m30_series = MarketData.GetSeries(TimeFrame.Minute30);

var aroon_m30 = Indicators.Aroon(m30_series, 21);

}

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

very advantageous method (with optimization)
++ Can choose a different period for the chart

cordialement

 


@tradermatrix

tradermatrix
04 Oct 2014, 13:05

RE:

Spotware said:

When you create an indicator you can pass DataSeries or MarketSeries object:

        protected override void OnStart()
        {
            var m1_series = MarketData.GetSeries(TimeFrame.Minute);
            var sma_m1 = Indicators.SimpleMovingAverage(m1_series.Close, 14);

            var m5_series = MarketData.GetSeries(TimeFrame.Minute5);
            var aroon_m5 = Indicators.Aroon(m5_series, 21);
        }

 

hello
I Experienced the method on simple robots.
I always found the same error
example;

sample RSI cBot

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 SampleRSIcBot : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

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

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

        [Parameter("Volume", DefaultValue = 10000, MinValue = 1000)]
        public int Volume { get; set; }

        private RelativeStrengthIndex rsi;

        protected override void OnStart()
        {
            rsi = Indicators.RelativeStrengthIndex(Source, Periods);
        }

        protected override void OnTick()
        {
            if (rsi.Result.LastValue < 30)
            {
                Close(TradeType.Sell);
                Open(TradeType.Buy);
            }
            else if (rsi.Result.LastValue > 70)
            {
                Close(TradeType.Buy);
                Open(TradeType.Sell);
            }
        }

        private void Close(TradeType tradeType)
        {
            foreach (var position in Positions.FindAll("SampleRSI", Symbol, tradeType))
                ClosePosition(position);
        }

        private void Open(TradeType tradeType)
        {
            var position = Positions.Find("SampleRSI", Symbol, tradeType);

            if (position == null)
                ExecuteMarketOrder(tradeType, Symbol, Volume, "SampleRSI");
        }
    }
}

corrected robot;

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 SampleRSIcBot : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

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

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

        [Parameter("Volume", DefaultValue = 10000, MinValue = 1000)]
        public int Volume { get; set; }

        private RelativeStrengthIndex rsi;   //message d erreur : Error CS0649: Field 'cAlgo.SampleRSIcBot.rsi' is never assigned to, and will always have its default value null.
//04/09/2014 03:01:00.000 | Crashed in OnTick with NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet.
        protected override void OnStart()
        {
            var m5_series = MarketData.GetSeries(TimeFrame.Minute5);
            var rsi_m5 = Indicators.RelativeStrengthIndex(m5_series.Close, 14);



        }


        protected override void OnTick()
        {
            if (rsi.Result.LastValue < 30)
            {
                Close(TradeType.Sell);
                Open(TradeType.Buy);
            }
            else if (rsi.Result.LastValue > 70)
            {
                Close(TradeType.Buy);
                Open(TradeType.Sell);
            }
        }

        private void Close(TradeType tradeType)
        {
            foreach (var position in Positions.FindAll("SampleRSI", Symbol, tradeType))
                ClosePosition(position);
        }

        private void Open(TradeType tradeType)
        {
            var position = Positions.Find("SampleRSI", Symbol, tradeType);

            if (position == null)
                ExecuteMarketOrder(tradeType, Symbol, Volume, "SampleRSI");
        }
    }
}

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

can you help me to correct the error.
in order to  set various indicators (in the same robot) with different time.
cordially


@tradermatrix

tradermatrix
25 Jul 2014, 11:31

   protected override void OnStart()
        {
            ichimoku = Indicators.GetIndicator<IchimokuCloud>(periodFast, periodMedium, periodSlow, DisplacementCloud);
        }


@tradermatrix

tradermatrix
14 May 2014, 13:20

hello 
here is my problem 
when the indicator of my robot execute a position (buy or sell), it also poses pending orders. 
for example; 
initial buy (indicator): 1.3800 
pending order: 1.3750 ... if execution: pendingorder: 1.3700 .... etc 


and can be later 
initial sell (indicator) 1.39 
pending order: 1.3950 ... if execution: pendingorder 1.4000 .... etc 

TakeProfit then changes (as robotforex) 

I would like a formula to remove pending orders when the robot execute TakeProfit. 
the robot execute the buy and sell positions: I would like the formula to make the difference, and eliminates the pending buy orders or sell, and vice versa 

cordially.

 


@tradermatrix

tradermatrix
03 Apr 2014, 19:32

your robot; the trailing stop works with OnTick or OnBar?


@tradermatrix

tradermatrix
19 Dec 2013, 17:46

thank you for these explanations
I will try to apply your method on my robots
cordially


@tradermatrix

tradermatrix
18 Dec 2013, 12:40

thank you
in this formula;
    BuyVolume =BuyVolume *  2;
                  MartingaleLevel + +;
the formula doubles the volume to infinity (up to get gain)
I would like to double that once.(even if the trade is a loser)
can you help me.

cordially


@tradermatrix

tradermatrix
20 Oct 2013, 12:50

erreur de volume ;1

 volume :10000


@tradermatrix

tradermatrix
30 Aug 2013, 10:51

RE:

stoko said:

How can I get all closed orders?

I guess Positions will only give me open positions?

Is there some class that I can use?

        foreach (var openedPosition in Account.Positions)
       
        {

        Trade.Close(openedPosition);

        }

        foreach (var pendingOrder in Account.PendingOrders)
       
        {

        Trade.DeletePendingOrder(pendingOrder);

        }


@tradermatrix

tradermatrix
22 Aug 2013, 17:16

excusez moi ,mais il me semble que cette méthode est plus juste:

   protected override void OnTick()
        {
            var netProfit = 0.0;
            foreach (var openedPosition in Account.Positions)
            {
                netProfit += openedPosition.NetProfit + openedPosition.Commissions;
            }
            ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomLeft);
            {
                if (Account.Equity - Account.Balance > 300 || Account.Equity - Account.Balance < - 200)
                {
                    foreach (var position in Account.Positions)
                    {
                        Trade.Close(position);
                    }
                }
            }
        }
    }
}
 

 


@tradermatrix

tradermatrix
22 Aug 2013, 16:32 ( Updated at: 21 Dec 2023, 09:20 )

RE: RE:

coolutm said:

cAlgo_Fanatic said:

When the number circled in red, which is equal to the net profit minus the commission (23.16 -15 =11.16) will be greater than 300 or less than -300, then the position will close.

protected override void OnTick()
{
    var netProfit = 0.0;
    foreach (var openedPosition in Account.Positions)
    {
        netProfit += openedPosition.NetProfit + openedPosition.Commissions;
    }
    ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomLeft);
    if (Math.Abs(netProfit) >= 300.0)
    {
        foreach (var openedPosition in Account.Positions)
        {
            Trade.Close(openedPosition);
        }
    }
}

 

Hi cAlgo Support,

Thank you for the reply. This one works perfect.

Just one more question (or request), what if I want to set up different amount for the profit side and stop loss side?

I simply added one more if phrase....if (NetProfit <= -200) but didn't work.

Please help me.

{
            var netProfit = 0.0;
            foreach (var openedPosition in Account.Positions)
            {
                netProfit += openedPosition.NetProfit + openedPosition.Commissions;
            }
            ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomLeft);
            if ((Math.Abs(netProfit) >= 200.0) || (Math.Abs(netProfit) <= -200))
            {
                foreach (var openedPosition in Account.Positions)
                {
                    Trade.Close(openedPosition);
                }
            }
        }


@tradermatrix

tradermatrix
13 Aug 2013, 17:46

EUREKA.....!!!

j ai trouvé la solution.

 


@tradermatrix

tradermatrix
13 Aug 2013, 14:58

hello
I have changed my code. (trail)
it works well.
except for breakeven Buy.
it always changes its position to "0". (entry price)
for example:
stoploss: 40
breakeven 30:
trigger: 40

when the currency reaches trigger: 40
the stop loss moves to the price of entry ...?
it does not position 30 above the entry price ...

But it works with "shell".

( you can see the error more easily by removing "ClosePosition ();
of "protected override void OnBar ()" )

thank you for your help

 

//#reference: ..\Indicators\ZigZag.algo
using System;
using cAlgo.API;
using cAlgo.Indicators;
using cAlgo.API.Requests;
namespace cAlgo.Robots

        {
        
        [Robot]
        public class ZiGZaG : Robot
        
        {
       
        [Parameter(DefaultValue = 12)]
        public int ZzDepth { get; set;}
 
        [Parameter(DefaultValue = 5)]
        public int ZzDeviation { get; set;}
 
        [Parameter(DefaultValue = 3)]
        public int ZzBackStep { get; set;}
 
        [Parameter(DefaultValue = 100000)]
        public int Volume { get; set;}
 
        [Parameter(DefaultValue = 40)]
        public int StopLoss { get; set;}
        
        [Parameter(DefaultValue = 80)]   
        public int TakeProfit { get; set;} 

        [Parameter(DefaultValue = 40)]
        public double Trigger { get; set;}
 
        [Parameter(DefaultValue = 0)]
        public double TrailingStop { get; set;}
        
        [Parameter("Breakeven", DefaultValue = 30)]
        public double Breakeven { get; set;}
       
           
           
       
 
//////////////////////////////////////////////////////////////        
 
        private Position _position;
        private ZigZag _zigZag;
        private double prevValue;
        private MovingAverageType _matype;
         
/////////////////////////////////////////////////////////////

       
        protected override void OnTick()
        
        {
             
        Trail();
        
        }
               
        protected override void OnStart() 
        
        {
        
        _matype = MovingAverageType.Simple;
        _zigZag = Indicators.GetIndicator<ZigZag>(ZzDepth, ZzDeviation, ZzBackStep);
        
        }
        
        protected override void OnBar()
        
        {
        
        if (Trade.IsExecuting)
                return;
 
        bool isLongPositionOpen = _position != null && _position.TradeType == TradeType.Buy;
        bool isShortPositionOpen = _position != null && _position.TradeType == TradeType.Sell;
 
                         double lastValue = _zigZag.Result.LastValue;
 
        if (!double.IsNaN(lastValue))
        
        {
 
        if (lastValue < prevValue && !isLongPositionOpen)
        
        {
                         ClosePosition();

                              Buy();
                             
        }
               
        else if (lastValue > prevValue && prevValue > 0.0 && !isShortPositionOpen)
        
        {
                         ClosePosition();

                              Sell();
        }
        
        prevValue = lastValue; 
        
        }         
        }
  
        private void ClosePosition()
        
        {
        
        if (_position == null) return;
        
        Trade.Close(_position);
      
        _position = null;
        
        }
 
        private void Buy()
        
        {
        
        Request request = new MarketOrderRequest(TradeType.Buy, Volume)
        
        { 
                                 Label = "ZIGZAG",
                                 
        StopLossPips = StopLoss > 0 ? (int?)StopLoss : null,
        TakeProfitPips = TakeProfit > 0 ? (int?)TakeProfit : null
        
        };
        
                                Trade.Send(request);
                                
        }
 
        private void Sell()
        
        {
        
        Request request = new MarketOrderRequest(TradeType.Sell, Volume)
        
        {
                                 Label = "ZIGZAG",
                                
        StopLossPips = StopLoss > 0 ? (int?)StopLoss : null,
        TakeProfitPips = TakeProfit > 0 ? (int?)TakeProfit : null
       
        };
        
                               Trade.Send(request);
        }
 
       
 
        private void Trail()
        
        {
          
        foreach (Position _position in base.Account.Positions)
        
        {
        {
        
        if (_position.TradeType == TradeType.Sell)
        
        {
        
        if (_position.Pips >= (double)this.Trigger && this.Breakeven > 0)
        
        {
        
        double N2 = _position.EntryPrice - (double)this.Breakeven * base.Symbol.PipSize;
        double N3 = N2;
        double? stopLoss = _position.StopLoss;
        
        if (N3 < stopLoss.GetValueOrDefault() && stopLoss.HasValue)
        
        {
        
        base.Trade.ModifyPosition(_position, new double?(N3), _position.TakeProfit);
        
        }
        }
        
        if (_position.Pips >= (double)this.Trigger && this.Breakeven < 1)
        
        {
        
        double N2 = base.Symbol.Ask + (double)this.TrailingStop * base.Symbol.PipSize;
        double N3 = N2;
        double? stopLoss = _position.StopLoss;
        
        if (N3 < stopLoss.GetValueOrDefault() && stopLoss.HasValue)
        
        {
        
        base.Trade.ModifyPosition(_position, new double?(N3),_position.TakeProfit);
        
        }
           }
        }
        
        else
        
        {
        
        if (_position.Pips >= (double)this.Trigger && this.Breakeven > 0)
        
        {
        
        double entryPrice = _position.EntryPrice;
        double? stopLoss = _position.StopLoss;
        double N2 = entryPrice;
        
        if (stopLoss.GetValueOrDefault() < N2 && stopLoss.HasValue)
        
        {
        
        base.Trade.ModifyPosition(_position, new double?(entryPrice), _position.TakeProfit);
        
        }
        }
        
        if (_position.Pips >= (double)this.Trigger && this.Breakeven < 1)
        
                        {
        double N2 = base.Symbol.Bid - (double)this.TrailingStop * base.Symbol.PipSize;
        double? stopLoss = _position.StopLoss;
        double N3 = N2;
        
        if (stopLoss.GetValueOrDefault() < N3 && stopLoss.HasValue)
        
        {
        
        base.Trade.ModifyPosition(_position, new double?(N2), _position.TakeProfit);
        
        }
          }
            }
              }
                }
                  }
                  
        protected override void OnPositionOpened(Position openedPosition)
        
        {
        
        _position = openedPosition;
           
        }
          }
        }


@tradermatrix

tradermatrix
25 Jun 2013, 22:01

using System.Collections.Generic;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Robots
{
    [Robot]
    public class SampleMultiplePositions : Robot
    {
        private readonly List<Position> _listPosition = new List<Position>();

        [Parameter]
        public DataSeries SourceSeries { get; set; }

        [Parameter("MA Type")]
        public MovingAverageType MAType { get; set; }

        [Parameter("Slow Periods", DefaultValue = 10)]
        public int SlowPeriods { get; set; }

        [Parameter("Fast Periods", DefaultValue = 5)]
        public int FastPeriods { get; set; }

        [Parameter(DefaultValue = 100000)]
        public int Volume { get; set; }

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

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

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

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


        [Parameter("MinBalance", DefaultValue = 40000)]
        public double MinBalance { get; set; }

        [Parameter("MinLoss", DefaultValue = -200.0)]
        public double MinLoss { get; set; }
        

        private MovingAverage _slowMa;
        private MovingAverage _fastMa;
        

        ///
        /// Initialize Indicators
        ///
        protected override void OnStart()
        {
            _fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType);
            _slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType);
        }
        protected override void OnBar()
        {

            if (Trade.IsExecuting) return;
            
            int lastIndex = _slowMa.Result.Count - 2;
            int prevIndex = _slowMa.Result.Count - 3;

            double currentSlowMa = _slowMa.Result[lastIndex];
            double currentFastMa = _fastMa.Result[lastIndex];

            double previousSlowMa = _slowMa.Result[prevIndex];
            double previousFastMa = _fastMa.Result[prevIndex];

            // Condition to Buy
            if (previousSlowMa > previousFastMa && currentSlowMa <= currentFastMa )
            {
                if(_listPosition.Count < 3)
                    Buy();
            }

            // Condition to Sell
            if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa )
            {
                if (_listPosition.Count < 3)
                    Sell();
            }
            
            // Trailing Stop for all positions
            SetTrailingStop();

            // Some condition to close all positions
            if (Account.Balance < MinBalance)
            {
                CloseAllPositions();
            }

            // Some condition to close one position
            foreach (Position position in _listPosition)
            {
                if (position.GrossProfit < MinLoss)
                {
                    ClosePosition(position);
                }                
            }

        }

        ///
        /// Add newly opened position to list and set stop loss and take profit
        ///
        ///
        protected override void OnPositionOpened(Position openedPosition)
        {
            _listPosition.Add(openedPosition);

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

            if (StopLoss != 0)
            {
                if (openedPosition.TradeType == TradeType.Buy)
                {
                    stopLossPrice = openedPosition.EntryPrice - StopLoss*Symbol.PipSize;
                }
                else
                {
                    stopLossPrice = openedPosition.EntryPrice + StopLoss*Symbol.PipSize;
                }
            }

            if (TakeProfit != 0)
            {
                if (openedPosition.TradeType == TradeType.Buy)
                {
                    takeProfitSize = openedPosition.EntryPrice + TakeProfit*Symbol.PipSize;
                }
                else
                {
                    takeProfitSize = openedPosition.EntryPrice - TakeProfit * Symbol.PipSize;
                }
            }

            Trade.ModifyPosition(openedPosition, stopLossPrice, takeProfitSize);

        }

        ///
        /// Remove closed position from list
        ///
        ///
        protected override void OnPositionClosed(Position closedPosition)
        {
            if (_listPosition.Contains(closedPosition))
            {
                _listPosition.Remove(closedPosition);
            }
        }

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

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

        ///
        ///  When the profit in pips is above or equal to Trigger the stop loss will start trailing the spot price.
        //   TrailingStop defines the number of pips the Stop Loss trails the spot price by. If Trigger is 0 trailing will begin immediately. 
        ///
        private void SetTrailingStop()
        {
            foreach (Position position in _listPosition)
            {

                if (position.TradeType == TradeType.Sell)
                {
                    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);
                        }
                    }
                }
                else
                {
                    double distance = Symbol.Bid - position.EntryPrice;

                    if (distance >= Trigger * Symbol.PipSize)
                    {
                        double newStopLossPrice = Symbol.Bid - TrailingStop * Symbol.PipSize;
                        if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                        {
                            Trade.ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                        }
                    }
                }
            }
        }

        ///
        /// Close all position in list
        ///
        private void CloseAllPositions()
        {
            foreach (Position position in _listPosition)
            {
                ClosePosition(position);
            }
        }

        ///
        /// Close Position
        ///
        ///
        private void ClosePosition(Position pos)
        {
            if (pos == null) 
                return;
            
            Trade.Close(pos);

        }

    }
}

 


@tradermatrix

tradermatrix
26 May 2013, 15:27

hello
thank you very much
but I have not managed to install two Trailling stop.
malgres several formulas.
there is always a Trailling stop which takes precedence over the other.
My robot is presented as follows:


       [Parameter(DefaultValue = 100000)]
        public int Volume1 { get; set; }
       
        [Parameter("TakeProfit1", DefaultValue = 200)]
        public int TakeProfit1 { get; set; }
       
        [Parameter("StopLoss1 (pips)", DefaultValue = 36)]
        public int StopLoss1 { get; set; }

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

        [Parameter("Trigger1 (pips)", DefaultValue = 80)]
        public int Trigger1 { get; set; }
//////////////////////////////////////////////////////////////////////////////////////////////////


  [Parameter("Volume2", DefaultValue = 50000, MinValue = 0)]
        public int Volume2 { get; set; }
        
        [Parameter("StopLoss2", DefaultValue =30)]
        public int StopLoss2 { get; set; }

        [Parameter("TakeProfit2", DefaultValue = 180)]
        public int TakeProfit2 { get; set; }
       
        [Parameter("Trailing Stop2 (pips)", DefaultValue = 20)]
        public int TrailingStop2 { get; set; }

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

I think that I did not understand the implementation of the second Trailling stop.
there is something that m escapes.
can you say more
cordially

 

{

foreach (var position in Account.Positions)

 

            {
               double trigger = position.Volume == Volume1 ? Trigger1 : Trigger2;
                double trailingStop = position.Volume == Volume1 ? TrailingStop1 : TrailingStop2;
               
 

               
                {
                   
                    if (position.TradeType == TradeType.Buy)
                    {
                        double distance = Symbol.Bid - position.EntryPrice;

                        if (distance >= trigger*Symbol.PipSize)
                        {
                            if (!_isTrigerred)
                            {
                                _isTrigerred = true;
                                Print("Trailing Stop Loss triggered...");
                            }

                            double newStopLossPrice = Math.Round(Symbol.Bid - trailingStop*Symbol.PipSize, Symbol.Digits);

                            if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                            {
                                Trade.ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                            }
                        }
                    }
                    else
                    {
                    
                double Trigger = position.Volume == Volume1 ? Trigger1 : Trigger2;
                double TrailingStop = position.Volume == Volume1 ? TrailingStop1 : TrailingStop2;
                {
                   
                    if (position.TradeType == TradeType.Buy)
                    {
                        double distance = Symbol.Ask - position.EntryPrice;

                        if (distance >= trigger*Symbol.PipSize)
                        {
                            if (!_isTrigerred)
                            {
                                _isTrigerred = true;
                                Print("Trailing Stop Loss triggered...");
                            }

                            double newStopLossPrice = Math.Round(Symbol.Ask - trailingStop*Symbol.PipSize, Symbol.Digits);

                            if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                            {
                                Trade.ModifyPosition(position, newStopLossPrice, position.TakeProfit);
                           
                        }
                        }}
                        }}}}
                        }}
                        }
                       

 


 


@tradermatrix

tradermatrix
22 May 2013, 11:56

hello
is it possible to adjust two Trailling stop on the same robot?
1 for each volume.
volume1(100000)= trigger1: 80 pips / traillingstop1: 20 pips
Volume2(50000)=  trigger2: 40 pips / traillingstop2: 10 pips
cordially


@tradermatrix

tradermatrix
16 May 2013, 20:44

RE:
Balena said:

thanks support...

but that's not what I'm seeing...

my profit target of 100 is reached (10,000 starting equity + 100) ; see equity column

but when the position is closed at 10,100...  I end up with only 10, 089

what is causing this difference from desired target to ending result?

notice all closing prices are the same...

does you equity calculation not include commissions maybe?

please see pic

 

hello
I have the same problem
c is the commission of the closing of the order.
because the commission is not taken into account in the equity or p & l
c is boring for algorithms to several orders.
we believe to be positive, but net of fees is going negative.
I would like équity and p & l displayed with the deduction of commissions.

 


@tradermatrix

tradermatrix
16 May 2013, 13:06

  protected override void OnPositionClosed(Position closedPosition)
        {
       if (closedPosition <InitialVolume*4)

ExecuteOrder((int) position.Volume * 2, position.TradeType);

else 

ExecuteOrder((int) position.Volume, position.TradeType);
}

thank you
but the robot does not work

I have added if (closedPosition.GrossProfit <InitialVolume*4)

but the martingale does not work.
may be that I did not understand your method.
cordially


@tradermatrix