#define Y "AUD/USD"
#define X "XAU/USD"
function run()
{
set(PLOTNOW,LOGFILE);
BarPeriod = 1440;
StartDate = 20100101;
EndDate = 20101231;
Capital = 100000;
LotAmount = 1;
int period = 6;
int ATRperiod = 20;
int RiskAllocation = 10000;
int MidUpper = 55;
int MidLower = 45;
int upperThreshold = 90;
int lowerThreshold = 10;
int maxOpen = 2;
LOOKBACK = max(ATRperiod,period);
asset(Y);
vars percntReturnsY = series(((priceClose(0)-priceClose(1))/priceClose(0))*100);
vars stocY = series((priceClose(period)- priceLow(period))/(priceHigh(period)-priceLow(period)));
var AtrY = ATR(ATRperiod);
asset(X);
vars percntReturnsX = series(((priceClose(0)-priceClose(1))/priceClose(0))*100);
vars stocX = series((priceClose(period)- priceLow(period))/(priceHigh(period)-priceLow(period)));
var AtrX = ATR(ATRperiod);
vars stocDiff = series(stocY[0] - stocX[0]);
vars ZScore = series(zscore(stocDiff[0], period));
vars stocNorm = series((normalize(stocDiff[0], period)*0.5)+50);
var yLots = max(round(RiskAllocation/(priceClose(0)*LotAmount)),1);
var xLots = max(round((RiskAllocation/(priceClose(0)*LotAmount))*(AtrY/AtrX)),1);
// -------------------------------
// Exit all trades on friday at 6pm
// -------------------------------
if(dow() == FRIDAY && hour() >= 18) { exitLong("*"); exitShort("*");}
// -------------------------------
// trade logic
// -------------------------------
// exit on cross midpoints
if(crossOver(stocNorm, MidLower) or crossUnder(stocNorm, MidUpper))
{
asset(X);
exitLong(); exitShort();
asset(Y);
exitLong(); exitShort();
}
if(NumOpenTotal < maxOpen) {
if(crossUnder(stocNorm, lowerThreshold)) // buying the spread (long Y, short X)
{
asset(Y);
Lots = yLots;
enterLong();
asset(X);
Lots = xLots;
enterShort();
}
if(crossOver(stocNorm, upperThreshold)) // shorting the spread (short Y, long X)
{
asset(Y);
Lots = yLots;
enterShort();
asset(X);
Lots = xLots;
enterLong();
}
}
}