Your interactive trading laboratory!
 • 
6 users online

Trailing Stops in C#
This is a Feature Request with 3 votes

I'm currently unable to figure out how I can implement a trailing stop in code. Is there a piece of code available? Thanks for your help...

Attachment

Cancel

Responses

Here's a rudimentary example. It involves using a local variable to save the stop level and test against the local variable to raise the stop if the new stop level is higher. I think Quantacula could use some attention to trailing stops, will consider beefing up the native support in a future release. And maybe create a trailing stop building block?

using QuantaculaBacktest;
using System;
using QuantaculaCore;
using QuantaculaIndicators;
using QuantaculaChart;
using System.Drawing;
using System.Collections.Generic;

namespace Quantacula
{
    public class MyModel : UserModelBase
    {
        //create indicators and other objects here, this is executed prior to the main trading loop
        public override void Initialize(BarHistory bars)
        {
			rsi = new RSI(bars.AveragePriceOHLC, 14);
			PlotIndicator(rsi);
			stops = new TimeSeries(bars.DateTimes);
			PlotTimeSeries(stops, "Trailing Stop Level", "Price", Color.Red, PlotStyles.Dots);
        }

        //execute the strategy rules here, this is executed once for each bar in the backtest history
        public override void Execute(BarHistory bars, int idx)
        {
            if (HasOpenPosition(bars, PositionType.Long))
            {
				double newStop = bars.Close[idx] * 0.95;
	            if (newStop > stopLevel)
					stopLevel = newStop;
				PlaceTrade(bars, TransactionType.Sell, OrderType.Stop, stopLevel);
				stops[idx] = stopLevel;
            }
            else
            {
				if (rsi.CrossesOver(32, idx))
				{
					PlaceTrade(bars, TransactionType.Buy, OrderType.Market);
					stopLevel = 0;
				}
            }
        }

		//declare private variables below
		private RSI rsi;
		private double stopLevel = 0;
		private TimeSeries stops;
    }
}
Here's a rudimentary example. It involves using a local variable to save the stop level and test against the local variable to raise the stop if the new stop level is higher. I think Quantacula could use some attention to trailing stops, will consider beefing up the native support in a future release. And maybe create a trailing stop building block? [CODE] using QuantaculaBacktest; using System; using QuantaculaCore; using QuantaculaIndicators; using QuantaculaChart; using System.Drawing; using System.Collections.Generic; namespace Quantacula { public class MyModel : UserModelBase { //create indicators and other objects here, this is executed prior to the main trading loop public override void Initialize(BarHistory bars) { rsi = new RSI(bars.AveragePriceOHLC, 14); PlotIndicator(rsi); stops = new TimeSeries(bars.DateTimes); PlotTimeSeries(stops, "Trailing Stop Level", "Price", Color.Red, PlotStyles.Dots); } //execute the strategy rules here, this is executed once for each bar in the backtest history public override void Execute(BarHistory bars, int idx) { if (HasOpenPosition(bars, PositionType.Long)) { double newStop = bars.Close[idx] * 0.95; if (newStop > stopLevel) stopLevel = newStop; PlaceTrade(bars, TransactionType.Sell, OrderType.Stop, stopLevel); stops[idx] = stopLevel; } else { if (rsi.CrossesOver(32, idx)) { PlaceTrade(bars, TransactionType.Buy, OrderType.Market); stopLevel = 0; } } } //declare private variables below private RSI rsi; private double stopLevel = 0; private TimeSeries stops; } } [/CODE]

Thanks. Looks like it must be calculated directly in the code. Would be great to have such a feature just as a simple method which can be called as a one liner ;-)

Thanks. Looks like it must be calculated directly in the code. Would be great to have such a feature just as a simple method which can be called as a one liner ;-)

Sounds like a new feature request? I'll flag this topics as a Request.

Sounds like a new feature request? I'll flag this topics as a Request.

Agreed, this should be simpler. My instinct was to set it as a new Transaction on the lines following where I placed the BUY order, set it and forget it.

Related: I tried your demo script from here and cannot get the stop loss red dots to appear on the chart. Does this plotting feature only work on the desktop Q-Studio, and not the web version?

Agreed, this should be simpler. My instinct was to set it as a new Transaction on the lines following where I placed the BUY order, set it and forget it. Related: I tried your demo script from here and cannot get the stop loss red dots to appear on the chart. Does this plotting feature only work on the desktop Q-Studio, and not the web version?

Hi Bitfool, plotting of user-calculated TimeSeries in the chart isn't yet supported here on the web site, only plotted indicators.

Hi Bitfool, plotting of user-calculated TimeSeries in the chart isn't yet supported here on the web site, only plotted indicators.
Forum Tips

Please sign in if you want to participate in our forum.

Our forum uses Markdown syntax to format posts.

To embed code snippets, enclose them in [CODE][/CODE] tags.