I didn't know how to write a proper subject for this post.

The thing is that I have a Zorro script which is a Pairs Trading Script. It uses R libraries for the ADF test.
In order to correctly store the histories in the R session I had to restrict the script to only run after LookBack bars. With a line like this:
Code:
if (Bar > StartBar) { /* .. ADF test.. */ }


This is ok in "Testing" mode, it works correctly. The first LookBack bars are not evaluated for the ADF test and everything's fine.

Now, the "problem": When in "Trading" mode, I have to wait for LookBack Bars to arrive, and until then, the ADF test is not evaluated. So if I'm working with daily bars and have a lookback of 1000 days, I'd have to wait... 1000 days!

¿Any ideas how to improve this code? Any help would be much appreciated

Another thing that happens in "Trading" mode and not in "Testing" mode with this script: when the script is run in Timeframes of M15 or bigger, the R session dies after arount 2-5 candles, possible because of some timeout. Now I have to work out how to deal with these "dead R sessions" in the Trading mode. ¿Anyone has suffered these issues? I must point out again that these glitches appear in "Trading" mode, not in "Testing" mode. And that I don't think they are in anyway related to a bug in Zorro platform. I think there must be a solution with some better code than mine, but I have not yet found it.

Here's the global idea of the script:

Code:
#include <r.h>

string asset1 = "EUR/USD";
string asset2 = "USD/CHF";
var rango = 10;	//pips de rango

bool checkIfOpenPosInRange(var Range, string asset) {
	for (open_trades){
		if (strstr(Asset,asset))
			if (TradePriceOpen < priceClose()+Range && TradePriceOpen > priceClose()-Range) {
				return(true);
			}
	}
	return(false);
}

void vendemosSpread(double hedgeRatio){
	asset(asset2);
	var pip2 = PIP;
	asset(asset1);
	if (checkIfOpenPosInRange(rango*PIP,asset1) && checkIfOpenPosInRange(rango*pip2,asset2))	return;
	asset(asset1);
	Margin = 10;
	//if (!TradeIsOpen)
	enterShort();
	
	asset(asset2);
	Margin=10*abs(hedgeRatio);
	enterLong();	
}

void compramosSpread(double hedgeRatio){
	asset(asset2);
	var pip2 = PIP;
	asset(asset1);
	if (checkIfOpenPosInRange(rango*PIP,asset1) && checkIfOpenPosInRange(rango*pip2,asset2))	return;
	asset(asset1);
	Margin=10;
	//if (!TradeIsOpen)
	enterLong();
	
	asset(asset2);
	Margin=10*abs(hedgeRatio);
	//if (!TradeIsOpen)
	enterShort();	
}

void cerramosTodo(){
	asset(asset1);
	exitLong();
	exitShort();
	
	asset(asset2);
	exitLong();
	exitShort();
}

function run()
{
	set(LOGFILE|PLOTNOW|MARGINLIMIT|BALANCE);
	int Periods[3] = {5,15,240};
	BarPeriod = Periods[optimize(0,0,1,1)];
	PlotWidth = 650;
	StartDate = 20120601; 
	EndDate = 20170125; 
	int lookBacks[3] = {30,4990,150};
	LookBack = lookBacks[optimize(1,0,1,1)];
	Capital = 0;
	vars pairRatio, priceClose1, priceClose2;
	//---------1 ----------//
	asset(asset1);
	Spread =	Slippage = RollShort = RollLong = 0; 
	priceClose1 = series(log(priceClose()) / log(10));
	//---------2 ----------//
	asset(asset2);
	Spread =	Slippage = RollShort = RollLong = 0; 
	priceClose2 = series(1/log(priceClose()) / log(10));
	pairRatio = series((priceClose1[0]) * (priceClose2[0]));
	
	int adfTest = 0;
		
	if(is(FIRSTINITRUN)) { // read the parameters only in the first run
		printf("nINICIO");
		Rstart("",2);
		Rx("library(tseries)");
		while(loop(asset1,asset2)) assetHistory(Loop1,1);
	}
	if(!RIsRunning(hR)) 	{
		printf("Error - R session aborted!");
	}
	
	int adfTest = 0;
	
	if (Bar > StartBar) {
		var criticalValue = -1;
		Rset("spread",pairRatio,LookBack);
		Rset("criticalValue",criticalValue);
		Rset("adfTest",adfTest);
		Rx("if(adf.test(spread[(length(spread)-30):(length(spread))], k=1)[1] <= criticalValue)
			if(adf.test(spread[(length(spread)-90):(length(spread))], k=1)[1] <= criticalValue)
			if(adf.test(spread[(length(spread)-60):(length(spread))], k=1)[1] <= criticalValue) adfTest <- 1 ");
		adfTest = Ri("adfTest");
	}
	
	int halfLife = LookBack;
	vars zScore = series((pairRatio[0] - SMA(pairRatio,halfLife)) / StdDev(pairRatio, halfLife));
	
	
	var trigger = 1.5;
	var close1 = 0;
	var close2 = 0.5;
	if (adfTest == 1){
		if (crossOver(zScore,trigger))
			vendemosSpread(pairRatio[0]);
		else if (crossUnder(zScore, -trigger))
			compramosSpread(pairRatio[0]);
		else if (crossOver(zScore,-close1) || crossUnder(zScore,close1) 
				    || crossOver(zScore,close1) || crossUnder(zScore,-close1)  
					|| crossOver(zScore,close2) || crossUnder(zScore,close2) 
				    || crossOver(zScore,-close2) || crossUnder(zScore,-close2)  
					)
			cerramosTodo();	
	}
	PlotHeight2 = 200;
	ColorUp = ColorDn = ColorWin = ColorLoss = 0;
	if (!is(TRAINMODE))
	plot("zScore", zScore, MAIN, RED);
}