First of all, sorry because I didn't response to last post... I was involved in other trading topics.
I have just returned to this topic after studying Custom Backtester Interface in deep.
Trying to put into practice what I was reading I have written next code, but I didn't get what I am looking for.
It is a very simple trading system (just to see if my needs are getting). I don't want to trade symbols with high correlationa at the same time, so I want to check if the new signals have high correlation with trades already open.
// TESTING SISTEM
// Coding by Santiago Vázquez 22/08/2018
SystemName="TESTING";
SetChartOptions(0, chartShowDates|chartWrapTitle);
//#include <optimizar_montecarlo.afl>
#include <Multiplicadores ESIGNAL.afl>
OptimizerSetEngine("spso");
SetOption("ActivateStopsImmediately",False);
SetOption("ReverseSignalForcesExit",1);
_SECTION_BEGIN("CBI");
SetCustomBacktestProc( "" );
if ( Status( "action" ) == actionPortfolio )
{
bo = GetBacktesterObject();
bo.Backtest( True ); // run default backtest procedure without generating the trade list
bo.PreProcess(); // Do pre-processing (always required)
for (i=0; i < BarCount; i++) // Loop through all bars
{
for ( trade = bo.GetFirstOpenPos(i); trade; trade = bo.GetNextOpenPos(i) ) // iterate through open positions at this bar
{
// Get symbols
Symboltrade = trade.symbol;
SymbolTradeClose = Foreign(Symboltrade, "Close");
}
for(sig = bo.getfirstsignal(i); sig; sig = bo.GetNextSignal(i)) // Loop through all signals at this bar
{
// Get symbols
Symbolcheck = sig.symbol; // Do I need to call the symbol or Can I just use C to calculate correlation and not using this line?
SymbolcheckClose = Foreign(Symbolcheck, "Close");
if(Correlation(SymbolTradeClose, SymbolcheckClose, termCorrelation) > CorrelationLevel)
sig.PosSize = 0;
}
bo.ProcessTradeSignals(i); //Process trades at bar (always required)
}
bo.PostProcess();
// generate trade list
bo.ListTrades( );
}
_SECTION_END();
_SECTION_BEGIN("Variables");
Risk = Param("System Risk ", 3000, 1000, 6000, 1000);
maxpositions = Param("Max. Open Positions", 3, 1, 50);
SetOption("MaxOpenPositions", maxpositions);
_SECTION_END();
// OPERATIVA
_SECTION_BEGIN("Trend");
periodoMT = Param("Trend term", 220, 90, 300, 10);
TrendAverage = MA(C, periodoMT);
CondUpTrend = C >= TrendAverage;
CondDownTrend = C < TrendAverage;
// PLOTTING TREND
PlotAv = ParamToggle("Plotting Trend","No|Yes", 0);
if(PlotAv==1)
{
Plot(TrendAverage, "Trend term", colorBlue, styleNoTitle + styleline);
}
_SECTION_END();
_SECTION_BEGIN("OSCILATOR");
// OSCILATOR CONDITION
OverSold = Param("Oversold", 30, 5, 45, 5);
Overbought = Param("Overbought", 70, 55, 95, 5);
lengthRSI = Param("Length RSI", 20, 5, 20, 5);
RSIwork = RSI(lengthRSI);
CondOverSold = RSIwork < OverSold;
CondOverbought = RSIwork > Overbought;
//PLOTTING RSI
pintarRSI = ParamToggle("Plot RSI","No|Yes", 0);
if(pintarRSI==1)
{
Plot(OverSold, "Oversold", colorgreen, styleLine + styleThick + styleLeftAxisScale + styledashed);
Plot(Overbought, "Overbougth", colorred, styleLine + styleThick + styleLeftAxisScale + styledashed);
Plot(RSIwork, "RSI", colororange, styleLine + styleThick + styleLeftAxisScale);
}
_SECTION_END();
_SECTION_BEGIN("STOP LOSS");
STP = ParamToggle("Stop", "Fix|Trailing", 1);
pintarSTOP = ParamToggle("Plotting Stop","No|Yes", 0);
nSTOP = Param("nStop", 3, 4, 5.5, 0.5);
STOP= nSTOP*ATR(20); //stop loss multiplier
_SECTION_END();
_SECTION_BEGIN("Limitations");
// NO HIGH VOLATILITY TRADES
porcentVolati = Param("Lim Volatility (%)", 10, 0, 50, 1);
CriterioVol = STOP * PointValue <= Risk*(porcentVolati/100 + 1);
termCorrelation = Param("Correlation Term", 90, 20, 300, 10);
CorrelationLevel = Param("Correlation Level", .8, 0, 1, 0.1);
_SECTION_END();
// ACTIVACIONES
Buy = CondUpTrend AND CondOverSold AND CriterioVol;
Sell = CondOverbought;
Short = CondDownTrend AND CondOverbought AND CriterioVol;
Cover = CondOverSold;
// DELETING EXTRASIGNAL
Buy = ExRem(Buy, Sell OR Short);
Short = ExRem(Short, Cover OR Buy);
Sell = ExRem(Sell, Buy);
Cover = ExRem(Cover, Short);
// STOP LOSS
if(STP==0)
{
// FIXING STOP
ApplyStop(stopTypeloss, stopModePoint, STOP, True, false);
}
else
{
// TRAILING STOP
ApplyStop(stopTypeTrailing, stopModePoint, Ref(STOP, -1), True, True);
}
Equity(1);
SetOption("EveryBarNullCheck", True);
intradeLong = Flip(Buy, Sell OR Short);
intradeshort = Flip(Short, Cover OR Buy);
if(STP==0)
{
stoplineLONG = IIf(intradeLong, (valuewhen(Buy, BuyPrice - STOP)), Null);
stoplineSHORT = IIf(intradeshort, (valuewhen(Short, shortprice + STOP)), Null);
}
else
{
stoplineLONG = IIf(intradeLong ,(HighestSince(Buy, H) - STOP), Null);
stoplineSHORT = IIf(intradeshort,(LowestSince(Short, L) + STOP), Null);
}
// SYSTEM RISK AND CONTRACTS PER TRADE
if(STP==0)
{
MarketRisk = IIf(intradelong, (C-(valuewhen(Buy, buyprice - STOP)))*PointValue, IIf(intradeshort, ((valuewhen(Short, shortprice + STOP))- C)*PointValue, STOP*PointValue));
}
else
{
MarketRisk = IIf(intradelong, (C-(HighestSince(Buy, H)-STOP))*PointValue, IIf(intradeshort, ((LowestSince(Short, L) +STOP)- C)*PointValue, STOP*PointValue));
}
NumFut = Max(1,int(Nz(Risk/MarketRisk)));
MarginDeposit = 1; PositionSize = NumFut;
// PLOTTING STOP
if(pintarSTOP==1)
{
Plot( stoplineLONG, "trailing stop line", colorLightGrey, styleLine+styleDashed+styleThick );
Plot( stoplineSHORT, "trailing stop line", colorLightGrey, styleLine+styleDashed+styleThick );
}
// PLOTTING CHART
Plot(C, "Price", colorBlack, styleThick | styleNoTitle | styleBar);
// TITLE
Title1 = StrFormat(EncodeColor( colorBlue ) + SystemName + " " + Date() + EncodeColor( colorRed )
+"\n" + EncodeColor( colorBlue ) + Name() + " Open %g, Hi %g, Lo %g, Close %g (%.1f%%)", O, H, L, C, SelectedValue( ROC( C, 1 )))
+"\n"+ EncodeColor(colorGrey40)+"ATR(20) = "+WriteVal(ATR(20),1.4)+" Pts"
+"\n"+"Volatility = "+WriteVal(PointValue*ATR(20),1.2)+"$";
Title2 = "\n" + "Contracts = " + NumFut + " Risk = " + Prec(Risk, 2) +"$"+ " Stop Risk = " + Prec(MarketRisk, 2) +"$";
if(STP==0)
{
Title3 = "\n" + EncodeColor(colorRed) + WriteIf (intradeLong OR intradeshort,"SL = ", "")
+ WriteIf(intradeLong, WriteVal((valuewhen(Buy, buyprice - STOP))),"")
+ WriteIf(intradeshort, WriteVal((valuewhen(Short, shortprice + STOP))),"");
}
else
{
Title3 = "\n" + EncodeColor(colorRed) + WriteIf (intradeLong OR intradeshort,"SL = ", "")
+ WriteIf(intradeLong, WriteIf(IsEmpty(Ref(stoplineLONG, -1)), WriteVal(stoplineLONG), WriteVal(Ref(stoplineLONG, -1))),"")
+ WriteIf(intradeshort, WriteIf(IsEmpty(Ref(stoplineSHORT, -1)), WriteVal(stoplineSHORT), WriteVal(Ref(stoplineSHORT, -1))),"");
}
Title = Title1 + Title2 + Title3;
// PLOTTING ACTIVATION SIGNALS
distancia = 3*ATR(14);
for(i=0; i<BarCount; i++)
{
if(Buy[i]) PlotText("buy\n" + BuyPrice[i], i, H[i]-distancia[i], colorGreen);
if(Sell[i] AND !Short[i]) PlotText("sell\n" + SellPrice[i], i, L[i]+distancia[i], colorRed);
if(Short[i]) PlotText("short\n" + ShortPrice[i], i, L[i]+distancia[i], colorRed);
if(Cover[i] AND !Buy[i]) PlotText("cover\n" + CoverPrice[i], i, H[i]-distancia[i], colorGreen);
}
//PLOTTIN SHAPES//
PlotShapes(IIf(Buy,shapeUpArrow,shapeNone),colorGreen,0,L,-15);
PlotShapes(IIf(Buy,shapeHollowCircle,shapeNone),colorGreen,0,BuyPrice,0);
PlotShapes(IIf(Sell AND !Short,shapeDownArrow,shapeNone),colorRed,0,H,-15);
PlotShapes(IIf(Sell AND !Short ,shapeHollowCircle,shapeNone),colorRed,0,SellPrice,0);
PlotShapes(IIf(Short,shapeDownArrow,shapeNone),colorBrown,0,H,-15);
PlotShapes(IIf(Short,shapeHollowCircle,shapeNone),colorBrown,0,ShortPrice,0);
PlotShapes(IIf(Cover AND !Buy,shapeUpArrow,shapeNone),colorDarkGreen,0,L,-15);
PlotShapes(IIf(Cover AND !Buy,shapeHollowCircle,shapeNone),colorDarkGreen,0,CoverPrice,0);
In addition to that, I got an error

It seem that the loop through all bars doesn't work properly....
Anybody could help me, please?