// trade when the RSI goes above or below a level
int start()
{
string algo = "RSI"
int rsi_period = 12;
double rsi_buy_level = 75.0;
double rsi_sell_level = 25.0;
// get the rsi value
double rsi_value = iRSI(Symbol(), Period(), rsi_period,
PRICE_CLOSE, 1); // mind the '1' - the candle 0 can be incomplete
// set up stop / profit levels
int stoploss = 200*Point;
int takeprofit = 200*Point;
int magic_number = 12345;
// number of open trades for this EA
int num_long_trades = 0;
int num_short_trades = 0;
// total number of trades for the entire account
int all_trades = OrdersTotal();
// cycle through all open trades
int i;
for(i = 0; i < all_trades; i++)
{
// use OrderSelect to get the info for each trade
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false)
continue;
// Trades not belonging to our EA are also found, so it's necessary to
// compare the EA magic_number with the order's magic number
if(magic_number != OrderMagicNumber())
continue;
if(OrderType() == OP_BUY)
{
// if rsi is below sell level, exit long trades
if(rsi_value < rsi_sell_level)
OrderClose(OrderTicket(), OrderLots(),
Bid, 3, Green);
else
// otherwise count the trades
num_long_trades++;
}
if(OrderType() == OP_SELL)
{
// if rsi is above buy level, exit short trades
if(rsi_value > rsi_buy_level))
OrderClose(OrderTicket(), OrderLots(),
Ask, 3, Green);
else
// otherwise count the trades
num_short_trades++;
}
}
// if rsi is above buy level, enter long
if((rsi_value > rsi_buy_level)
&& (num_long_trades == 0)) {
OrderSend(Symbol(), OP_BUY,
1.0, Ask, 3,
Ask - stoploss, Bid + takeprofit,
algo, magic_number,
0, Green);
}
// if rsi is below sell level, enter short
if((rsi_value < rsi_sell_level)
&& (num_short_trades == 0)) {
OrderSend(Symbol(), OP_SELL,
1.0, Bid, 3,
Bid + stoploss, Ask - takeprofit,
algo, magic_number,
0, Green);
}
return(0);
}