Hi,

OK, below is a complete system if you want to test yourself. If you have any 
other questions, let me know.

/************************************
 Strategy: Simple MACD
 Coded 20090611
************************************/

// Test Settings
tradeDelay = 1;
SetBarsRequired(1000,0);
SetFormulaName("Simple MACD"); 
SetTradeDelays( tradeDelay, tradeDelay, tradeDelay, tradeDelay ); 
SetOption( "InitialEquity", 10000 ); 
SetOption("FuturesMode", True);
SetPositionSize(1, spsShares); 
SetOption( "MaxOpenPositions", 1 ); 
SetOption( "CommissionMode", 3 ); 
SetOption( "CommissionAmount", 12.50 ); 
SetOption( "UsePrevBarEquityForPosSizing", False ); 

// Choose Optimizer Engine
OptimizerSetEngine("cmae");

// Variables to optimise
Longstop = Optimize("longstop", 1.0, 0.1, 4, 0.1);
Shortstop = Optimize("shortstop", 1.0, 0.1, 4, 0.1);
stopLevel = Optimize("stoplevel", 1.0, 0.1, 2, 0.1);

//Long Entry & Exit
Buy = Cross(MACD(), Signal());
Sell = 0;

//Short Entry & Exit
Short = Cross(Signal(), MACD());
Cover = 0;

//Trailing stop & Stop Loss
trailstop = 0;
priceatbuy = 0;
priceatshort = 0;
Sum1 = Sum2 = 0;
for( i = 1; i < BarCount; i++ )
{
// Calculate ATR inline using EMA (instead of Wilder's MA)
tr[i] = Max(H[i] - L[i], Max(H[i] - C[i-1], C[i-1] - L[i]));

// 34 bar EMA of True Range
fac = 2.0 / (1.0 + 34);
sum1 += (fac * (tr[i] - sum1));
sum2 += (fac * (1.0 - sum2));
etr[i] = Nz(sum1 / sum2);

// Trailing Stop
if( trailstop == 0 AND Buy[ i ] )
{
trailstop = High[ i ] - longstop * etr[i];
}
else Buy[ i ] = 0; // remove excess buy signals

if( trailstop == 0 AND Short[ i ] )
{
trailstop = Low[ i ] + shortstop * etr[i];
}
else Short[ i ] = 0; // remove excess short signals

if( trailstop > 0 AND Low[ i ] < trailstop )
{
Sell[ i ] = 1;
SellPrice[ i ] = trailstop;
trailstop = 0;
}

if( trailstop > 0 AND High[ i ] > trailstop )
{
Cover[ i ] = 1;
CoverPrice[ i ] = trailstop;
trailstop = 0;
}

// Stoploss
if( priceatbuy == 0 AND Buy[ i ] ) priceatbuy = BuyPrice[ i ];
if( priceatshort == 0 AND Short[ i ] ) priceatshort = ShortPrice[ i
];

if( priceatbuy > 0 AND SellPrice[ i ] < (priceatbuy - stopLevel *
etr[i]))
{
Sell[ i ] = 1;
SellPrice[ i ] = priceatbuy - stopLevel * etr[i];
priceatbuy = 0;
}
else Sell[ i ] = 0;

if( priceatshort > 0 AND CoverPrice[ i ] > (priceatbuy + stopLevel *
etr[i]))
{
Cover[ i ] = 1;
CoverPrice[ i ] = priceatshort + stopLevel * etr[i];
priceatshort = 0;
}
else Cover[ i ] = 0;

}

// Plot Entries and Exits
Plot(C, "Price", 1, styleCandle);
PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeHollowDownArrow,colorRed,0,High);
PlotShapes(Cover*shapeHollowUpArrow,colorGreen,0,Low);
PlotShapes(Short*shapeDownArrow,colorRed,0,High);

Reply via email to