Skip to content

Instantly share code, notes, and snippets.

@currencysecrets
Last active October 31, 2016 07:58
Show Gist options
  • Save currencysecrets/9727393 to your computer and use it in GitHub Desktop.
Save currencysecrets/9727393 to your computer and use it in GitHub Desktop.
Exit at market strategy
// this function exits at market, but needs the following params:
// sym = currency symbol
// tkt = trades' ticket number
// lots = trades' lot size
// p = price to exit at
bool exitNow( string sym, int tkt, double lots, double p ) {
// check if it's okay to exit trade
int trade = checkIsTradeAllowed();
// place trade if ok to place order
if ( trade > 0 ) {
if ( OrderClose( tkt, lots, p, EXT_MAX_SLIP, 0 ) ) {
// trade has successfuly closed
EXIT_PRICE = 0;
GATE_ACTIVE = -1; // reset
// let's now loop through the historical trades and obtain some data to return
int t = OrdersHistoryTotal();
for ( int i = t; i >= 0; i -= 1 ) {
if ( OrderSelect( i, SELECT_BY_POS, MODE_HISTORY ) ) {
if ( OrderTicket() == tkt ) {
double op = OrderOpenPrice();
datetime ot = OrderOpenTime();
double sl = OrderStopLoss();
double pr = OrderProfit();
int typ = OrderType();
string d;
if ( typ == 0 ) d = "LONG";
if ( typ == 1 ) d = "SHORT";
double cp = OrderClosePrice();
datetime ct = OrderCloseTime();
int mag = OrderMagicNumber();
double comm = OrderCommission();
double swap = OrderSwap();
double slip;
if ( typ == OP_BUY ) slip = cp - p;
if ( typ == OP_SELL ) slip = p - cp;
break;
}
}
}
// Send alerts
SendMail( "EXIT of " + d + " for " + sym,
"PROFIT/LOSS = " + D( pr, 2 ) + "\n" +
"ALERT price = " + D( p ) + "\n" +
"CLOSE price = " + D( cp ) + "\n" +
"CLOSE time = " + TimeToStr( ct ) + "\n" +
"COMMISSION charged = " + D( comm, 2 ) + "\n" +
"SWAP charges = " + D( swap, 2 ) + "\n" +
"SLIPPAGE = " + D( slip ) + "\n" +
"\n" +
"OPEN price = " + D( op ) + "\n" +
"OPEN time = " + TimeToStr( ot ) + "\n" +
"MAGIC number = " + mag + "\n" +
"STOP LOSS = " + D( sl ) + "\n"
);
return( true );
} else {
// alert at the failure of closing the trade
SendMail("ERR EXIT of " + d + " for " + sym,
"ERR = " + GetLastError() + "\n" +
"ALERT price = " + D( p ) + "\n" +
"CLOSE price = " + D( cp ) + "\n" +
"CLOSE time = " + TimeToStr( ct ) + "\n"
);
}
}
return( false );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment