Gamestudio Links
Zorro Links
Newest Posts
Trading Journey
by 7th_zorro. 04/27/24 04:42
Help with plotting multiple ZigZag
by M_D. 04/26/24 20:03
Data from CSV not parsed correctly
by jcl. 04/26/24 11:18
M1 Oversampling
by jcl. 04/26/24 11:12
Why Zorro supports up to 72 cores?
by jcl. 04/26/24 11:09
Eigenwerbung
by jcl. 04/26/24 11:08
MT5 bridge not working on MT5 v. 5 build 4160
by EternallyCurious. 04/25/24 20:49
Zorro FIX plugin - Experimental
by flink. 04/21/24 07:12
AUM Magazine
Latest Screens
The Bible Game
A psychological thriller game
SHADOW (2014)
DEAD TASTE
Who's Online Now
4 registered members (Akow, 7th_zorro, VoroneTZ, PeroPero), 812 guests, and 6 spiders.
Key: Admin, Global Mod, Mod
Newest Members
wandaluciaia, Mega_Rod, EternallyCurious, howardR, 11honza11
19049 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Please help me improve this script #464292
02/02/17 15:52
02/02/17 15:52
Joined: Apr 2013
Posts: 35
J
Joaquin Offline OP
Newbie
Joaquin  Offline OP
Newbie
J

Joined: Apr 2013
Posts: 35
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);
}


Re: Please help me improve this script [Re: Joaquin] #464297
02/02/17 22:22
02/02/17 22:22
Joined: Apr 2013
Posts: 35
J
Joaquin Offline OP
Newbie
Joaquin  Offline OP
Newbie
J

Joined: Apr 2013
Posts: 35
When I first read the manual, I thought that one could access the history, even in the INITRUN section, if it was inside the LookBack candles.
Until now, if this is possible, I don't know how to do it.
The second time I read the manual (and the rest of the times after that) I thought that the manual said that "no trading orders would be opened if current Bar is less than LookBack".

Maybe what I need in my script is not LookBack, but another thing, as what I want is to be able to have the history of the latest N bars in the INITRUN section, so I could get rid of the "if (Bar > LookBack)"

I keep searching for the answer. Will post it here if I find it.

Re: Please help me improve this script [Re: Joaquin] #464299
02/02/17 23:29
02/02/17 23:29
Joined: Apr 2013
Posts: 35
J
Joaquin Offline OP
Newbie
Joaquin  Offline OP
Newbie
J

Joined: Apr 2013
Posts: 35
I think I know now why the problem is happening.
I was assuming that with this line
Code:
vars priceClose1 = series(priceClose());


I had in priceClose1 the same content, in the same moment, as in priceClose(N), being N the candle number I want to get.
But I must be missing something, because when running this code, you'll see that I don't have the same price with priceClose(3) and priceClose1[3] .

What am I missing here?
While I find a better answer, I will use a for loop in the 2nd run (as I can see that in the first run priceClose() doesn't have the full history) to fill my array of prices. I have run into memory problems with this approach, but I will give it a try again.

Here is the proof of concept if you want to test it yourself:
Code:
string asset1 = "EUR/USD";
string asset2 = "USD/CHF";

function run()
{
	StartDate = 20120701; 
	EndDate = 20170125; 
	
	BarPeriod = 5;
	LookBack = 4000;
	
	vars pairRatio, priceClose1, priceClose2;
	asset(asset1);
	priceClose1 = series(priceClose(),10);
	Spread =	Slippage = RollShort = RollLong = 0; 
	asset(asset2);
	priceClose2 = series(priceClose(),10);
	Spread =	Slippage = RollShort = RollLong = 0; 
		
	static int secondRun = 0;
	
	if(is(FIRSTINITRUN)) { // read the parameters only in the first run
		printf("nINICIO");
		while(loop(asset1,asset2)) assetHistory(Loop1,1);
		int i=0;
		for (i=1; i<=10;i++){
			printf("nFIRST RUN %i %f",i, priceClose(i));
		}
		
	}
	else {
		if (secondRun == 2) secondRun = 3;
		if (secondRun == 1) secondRun = 2;
		if (secondRun == 0) secondRun = 1;
	}
	if (secondRun == 1) {
		printf("nsecond run");
		
		int i=0;
		for (i=1; i<=10;i++){
			printf("nSECOND RUN %i %f %f",i, priceClose1[i],priceClose2[i]);
			printf("n2nd run p2: %f",priceClose(i));
		}
	}
	if (secondRun == 2) {
		printf("nthird run");
		
		int i=0;
		for (i=1; i<=10;i++){
			printf("nTHIRD RUN %i %f %f",i, priceClose1[i],priceClose2[i]);
			printf("n3rd run p2: %f",priceClose(i));
		}
	}
}


Last edited by Joaquin; 02/03/17 11:53.
Re: Please help me improve this script [Re: Joaquin] #464305
02/03/17 13:47
02/03/17 13:47
Joined: Apr 2013
Posts: 35
J
Joaquin Offline OP
Newbie
Joaquin  Offline OP
Newbie
J

Joined: Apr 2013
Posts: 35
Well. I think I had several misconceptions of Zorro's inner working.

I will try to explain my mistakes just in case it helps someone else understand Zorro's behaviour.

I noticed in my Pairs Trading script that in Trading mode, in the first candles I only received NULLs in the zScore variable. In my research I've seen that this is because series variables are not "immediatly seen".

Also, I thought that LookBack bars where bars that in Trade mode would be run after you press the "Trade" button, but the script would be doing nothing. That was my mistake. LookBack is run after INITRUN, and its purpose is to store in memory this LookBack number of candles, before a new candle arrives.
In Testing mode this is not really important, because it just runs so fast you would not notice any difference.

So, my initial code with
Code:
if (Bar > LookBack)  //ADF test


is ok.

What is not so ok is that zScore is another series variable, and the first candles I was encountering NULLs.
So I've just added an UnstablePeriod variable, and I've done this

Code:
vars zScore = series((pairRatio[0] - SMA(pairRatio,halfLife)) / StdDev(pairRatio, halfLife));
	if (Bar > LookBack+UnstablePeriod) printf("nzScore: %f",zScore[0]);


So now I see that I don't have any NULLs.
I've set UnstablePeriod to 20, just based in previous research doing printf every new run.
I don't know why it takes several runs to fully "charge" the zScore series, but that's another thing.

Well, if you've read this, thanks for reading, and sorry if I made you a mess with all my testing!


Moderated by  Petra 

Gamestudio download | chip programmers | Zorro platform | shop | Data Protection Policy

oP group Germany GmbH | Birkenstr. 25-27 | 63549 Ronneburg / Germany | info (at) opgroup.de

Powered by UBB.threads™ PHP Forum Software 7.7.1