1. Make sure vx is a global variable, i.e., in a line right above "function main(...){" should be the code "var vx = null;"
2. Add a second global variable there, like: "var vxLast = null;"
3. Add the following code below the code you posted: "vxLast = vx;"
4. Modify the trigger criteria to compare the last RSI value above/below the upper/lower levels and the current RSI crossing the levels to the other side.
5. Assumptions: enter long if oversold and RSI <30 then crosses above 30 and short if overbought and then crosses below 70. Longs exit when RSI crosses 70 (now overbought) and shorts exit when RSI crosses 30 (now oversold)
Sample follows:
PHP Code:
function premain(){
...
}
var vx = null;
var vxLast = null;
function main(){
//...(enter study code here)
//Close trade?
if(Strategy.isLong()) {
if(vx >= 70) {//exit longs when RSI is overbought
Strategy.doSell("Exit Long Signal", Strategy.CLOSE, Strategy.THISBAR,Strategy.ALL);
}
}
if(Strategy.isShort()) {
if(vx <= 30) {//exit shorts when RSI is oversold
Strategy.doCover("Exit Short Signal", Strategy.CLOSE, Strategy.THISBAR,Strategy.ALL);
}
}
//Open new position?
if(vxLast <= 30 && vx > 30) {//oversold then turns up through 30 to go long
if(!Strategy.isLong()) {
Strategy.doLong("RSI low",Strategy.CLOSE,Strategy.THISBAR,SharesToTrade);
}
}
if(vxLast >= 70 && vx < 70) {//overbought then turns down through 70 to go short
if(!Strategy.isShort()) {
Strategy.doShort("RSI high",Strategy.CLOSE,Strategy.THISBAR,SharesToTrade);
}
}
}
}
vxLast = vx;
Leave a comment: