A Script Challenge - but Maybe Too Easy

 
Hi Friends,

I have written a few EAs in the past, but never a script (which I am not even totally clear on the distinction, except that an EA enters and closes trades, and a script usually does a single function (I think)).

Anyway, I need a script that will Close all open orders if the total profit of the open trades hits either a Profit Total or a Loss Total.

Now maybe such a script already exists and I just haven't found it.

Is this something easy for you wizards?

If so I would Soooo much appreciate getting it.

Thanks in advance.

Mike
 
It would be better to include that into the EA.

-The EA runs once every tick
-The script runs regardless of ticks, from starting it til removed
 
Here's a pencil sketch:
// The limits are user inputs
extern double GAIN = 25.8;
extern double LOSS = 2.3;

// Returns the profit of a trade or 0 on any sort of trouble
double getProfit(int index) {
    if ( OrderSelect( index, SELECT_BY_POS ) ) {
        if ( OrderType() == OP_BUY || OrderType() == OP_SELL )
            return( OrderProfit() );
    }
    return( 0 );
}

// Closes a trade at current price and returns true, or
// returns false on any trouble
bool closeOrder(int index) {
    if ( ! OrderSelect( index, SELECT_BY_POS ) )
        return( false );
    double price = Buy;
    if ( OrderType() == OP_BUY ) {
        price = Ask;
    } else if ( OrderType() != OP_SELL ) {
        return( false );
    }
    return( OrderClose( OrderTicket(), OrderLots(), price, 0 ) ) );
}
 
int start()
{
    double total = 0;
    int i = 0;
 
    // Determine the current P/L of orders
    for ( i = 0; i < OrdersTotal(); i++ ) {
        total += getProfit( i );
    }
 
    // Check if outside of limits
    if ( total > LOSS && total < GAIN )
        return( 0 );
 
    // When so, close all trades at current price
    for ( i = 0; i < OrdersTotal(); i++ ) {
        if ( closeOrder( i ) )
            i--; // Note that closing trade i makes it go away
    }

    return( 0 );
}