Params
Numeric Lots (1);
Numeric LengthMA (20);
Numeric LengthCCI (14);
Numeric ATRMultiplier (2);
Vars
Series<Numeric> MA;
Series<Numeric> CCI;
Numeric longEntry;
Numeric shortEntry;
Events
onBar(ArrayRef<Integer> indexs)
{
// Calculate indicators
MA = AverageFC(Close, LengthMA);
CCI = CCI(Close, High, Low, LengthCCI);
// Long entry condition
if(MA > MA[1] && CCI > 100)
{
longEntry = TrueRange(High, Low, Close)[1] * ATRMultiplier;
Buy(Lots, High + longEntry);
}
// Short entry condition
if(MA < MA[1] && CCI < -100)
{
shortEntry = TrueRange(High, Low, Close)[1] * ATRMultiplier;
SellShort(Lots, Low - shortEntry);
}
// Clear position condition
Numeric currentPos = Positions.GetPositionVolume();
if(currentPos > 0 && Positions.UnrealizedPnl() / currentPos < -0.02)
{
Sell(currentPos, Close);
}
else if(currentPos < 0 && Positions.UnrealizedPnl() / -currentPos < -0.02)
{
BuyToCover(-currentPos, Close);
}
}