I've been unsuccessfully trying to create a backtesting study that will trigger a BUY when the 50day MA crosses above the 200day MA and a SELL when the opposite takes place.
Below is the code that I've been using. It only seems to recognize when the PRICE crosses over the 50day MA not when the MA's cross above one another. Any suggestions would be greatly appreciated!
Code Below:
var vEMA50 = new MAStudy(50, 0, "Close", AStudy.EXPONENTIAL);
var vEMA200 = new MAStudy(200, 0, "Close", Study.EXPONENTIAL);
function preMain() {setPriceStudy(false); setStudyTitle("50-200 MA Crossover");}
function main() {if (Strategy.isLong() == false && vEMA50.getValue(MAStudy.MA) >= vEMA200.getValue(MAStudy.MA)) onAction1()
else if (Strategy.isLong() == true && vEMA50.getValue(MAStudy.MA) <= vEMA200.getValue(MAStudy.MA)) onAction2();
return new Array(null, null);}
function postMain() {}
function onAction1() {Strategy.doLong("", Strategy.CLOSE, Strategy.THISBAR, Strategy.Default, 0); vLastAlert = 1; }
function onAction2() {Strategy.doSell("", Strategy.CLOSE, Strategy.THISBAR, Strategy.Default, 0); vLastAlert = 2;}
Below is the code that I've been using. It only seems to recognize when the PRICE crosses over the 50day MA not when the MA's cross above one another. Any suggestions would be greatly appreciated!
Code Below:
var vEMA50 = new MAStudy(50, 0, "Close", AStudy.EXPONENTIAL);
var vEMA200 = new MAStudy(200, 0, "Close", Study.EXPONENTIAL);
function preMain() {setPriceStudy(false); setStudyTitle("50-200 MA Crossover");}
function main() {if (Strategy.isLong() == false && vEMA50.getValue(MAStudy.MA) >= vEMA200.getValue(MAStudy.MA)) onAction1()
else if (Strategy.isLong() == true && vEMA50.getValue(MAStudy.MA) <= vEMA200.getValue(MAStudy.MA)) onAction2();
return new Array(null, null);}
function postMain() {}
function onAction1() {Strategy.doLong("", Strategy.CLOSE, Strategy.THISBAR, Strategy.Default, 0); vLastAlert = 1; }
function onAction2() {Strategy.doSell("", Strategy.CLOSE, Strategy.THISBAR, Strategy.Default, 0); vLastAlert = 2;}
Comment