Range Trader sample

The source for Range Trader

Range Trader description

As prequisities you may want to check definition of Event-driven programming and Semaphore from Wikipedia

Range trading strategy consist of two parts. First we measure our range to get range high and range low. After that we enable trading and allow position opening if we get criteria fulfilled against range parameters.

During the trading day we can repeat this several times. There could be ranges defined for Europe morning and US morning. When all ranges are went through our algo is done for the day.


We start with variable introductions. _rangeHigh and _rangeLow are obviously used to store our range high and low. Note that we could fetch these values from previous bars but looping back is computationally more expensive operation than just updating variable when event occurs. _tradeAllowed is our semaphore to control that we do not trade until we have measurement done for our range. These can be made global variables and put anywhere they are accessible.


	double _rangeHigh = double.NaN; 
	double _rangeLow = double.NaN;
	bool _tradeAllowed = false;
	

Our system is running and receiving hourly bar events. When we receive hourly bar starting 11am we update range values and enable our semaphore to trade.


public override void NewHourlyBar(object sender, SingleBarEventArgs args)
{
	if ( args.Bars.Current.BarStartTime.Hour == 11) )
	{
		_rangeHigh = args.Bar.High;
		_rangeLow = args.Bar.Low;
		_tradeAllowed = true;
	}
}

Next we are allowed to trade and open position if tick time is after measurement range and we get tick price above/below our range. We trade first breakout from range and we trade only one breakout so _tradeAllowed is set false after sending order to broker.


public override void NewTick(BarData partialBar, TickData tick)
{
	if ( _tradeAllowed == true && 
		tick.time.Hour > 11 &&
		tick.price > _rangeHigh  )
	{			
		PositionSettings settings = new PositionSettings();
		settings.PositionType = PositionType.Long;
		OpenPosition(settings);
		_tradeAllowed = false;
	}
	else if ( _tradeAllowed == true && 
		tick.time.Hour > 11 &&
		tick.price < _rangeLow )
	{
		PositionSettings settings = new PositionSettings();
		settings.PositionType = PositionType.Short;
		OpenPosition(settings);
		_tradeAllowed = false;
	}
}

Now replace the fixed 11am value with your own range definition for Europe morning ranges and repeat same for US open range. Loop those through te day and you have automated range trades for all day.

In a case your range is 15min or 30min, you place your range measurements to the event of creation of new 15min or 30min bar.

Remember that conditions for opening the trade can also contain other filters like rate of change to verify price momentum is in line with your trade direction.

And finally when we get order confirmed we can set our profit target as fixed or trailing as described in previous articles TimeTrigger and AdaptiveTrail.