# WealthScript Techniques | Creating a Stop-And-Reverse (SAR) system

Modified on 2011/05/30 05:16 by Eugene — Categorized as: Knowledge Base

## The problem

Let's imagine that you are trying to create a simple Strategy based on fast/slow moving averages crossing.
On crossunder, it must sell long position and turn short.
On crossover, short must be covered and a new long position established.

## Example code

It's a very basic question frequently asked by WealthScript rookies, and there's only one trick to learn: the very first trade should be processed individually by making a check for Positions.Count equal to zero.

```
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;namespace WealthLab.Strategies
{
public class SARStrategy : WealthScript
{
protected override void Execute()
{

DataSeries maFast = SMA.Series(Close, 50);
DataSeries maSlow = SMA.Series(Close, 200);			PlotSeries(PricePane,maFast,Color.Red,LineStyle.Solid,2);
PlotSeries(PricePane,maSlow,Color.Green,LineStyle.Solid,2);			for(int bar = 201; bar < Bars.Count; bar++)
{

// Detect crossover/crossunder and store state in a variable
bool maXo = CrossOver(bar, maFast, maSlow);
bool maXu = CrossUnder(bar, maFast, maSlow);

if (Positions.Count == 0){
if ( maXo )
else if( maXu )
ShortAtMarket( bar + 1 );
}
else
{
Position p = LastPosition;
if ( p.PositionType == PositionType.Long )
{
if ( maXu )
{
SellAtMarket( bar + 1, p );
ShortAtMarket( bar + 1 );
}
}
else if ( maXo )
{
CoverAtMarket( bar + 1, p );
}
}
}
}
}
}```

## Another example

Our previous example featured CrossOvers/CrossUnders and AtMarket orders. Here's how to create a SAR strategy working with AtStop orders breaching 100-bar High and Low prices:

```using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;namespace WealthLab.Strategies
{
public class SARStrategy : WealthScript
{
protected override void Execute()
{
DataSeries HH = Highest.Series(High, 100);
DataSeries LL = Lowest.Series(Low, 100);			PlotSeries(PricePane,HH,Color.Blue,LineStyle.Solid,1);
PlotSeries(PricePane,LL,Color.Red,LineStyle.Solid,1);			for(int bar = GetTradingLoopStartBar(100); bar < Bars.Count; bar++)
{
if (Positions.Count == 0){
if ( BuyAtStop( bar + 1, HH[bar] ) == null )
ShortAtStop( bar + 1, LL[bar] );
}
else
{
Position p = LastPosition;
if ( p.PositionType == PositionType.Long ) {
if ( SellAtStop( bar + 1, p, LL[bar] ) )
ShortAtStop( bar + 1, LL[bar] );
}
else {
if (CoverAtStop( bar + 1, p, HH[bar] ) )
BuyAtStop( bar + 1, HH[bar] );
}
}
}
}
}
}
```