0

I'm trying to code this logic:

if no open orders and buy logic ( DayOpen - 10 * Point )
then buy

if bought
Sell when the one (and the only one) bought order reaches Take Profit price.


Here's what I have so far:

double DayOpen = iOpen( NULL, PERIOD_D1, 0 );
double TP      = 10.0;
int    ticket;

if ( OrdersTotal() == 0 && Bid == DayOpen - 10 * Point );
{    OrderSend( Symbol(),
                OP_BUY,
                1.0,
                Ask,
                0,
                0,
                Ask + TP * 10 * Point,
                NULL,
                12321,
                0,
                Blue
                );
}
Community
  • 1
  • 1
Rob
  • 69
  • 5

2 Answers2

1

Prologue
( would be fine to follow StackOverflow emphasis on posting a complete M.C.V.E. )

The code ought to read at least as syntactically-correct:

{                                                     // outer context missing
// .                                                  // outer context missing
// ..                                                 // outer context missing
// ...                                                // outer context missing
   RefreshRates();     // a life-saving jacket while  // outer context missing

   if (  OrdersTotal() == 0
      && Bid           <= iOpen( _Symbol, PERIOD_D1, 0 )
                        - ( 10 * _Point )
      )
   {  OrderSend( _Symbol,                            // <symbol>
                 OP_BUY,                             // <op> 
                 1.0,                                // <volume>
                 Ask,                                // <XTO_price>
                 0,                                  // <slippage_allowed>
                 0,                                  // <autoXTO_SL>
                 NormalizeDouble( Ask + 10 * _Point, // **ALWAYS**
                                  _Digits            // NORMALIZE XTO levels
                                  ),                 // <autoXTO_TP>
                 NULL,                               // <commentSTRING>
                 12321,                              // <MagNUM>
                 0,                                  // <expireSECONDs>
                 clrBlue                             // <arrowCOLOR>
                 );
   }

// ...
// ..
// .

}

Epilogue

There is no need to add any additional constructs for the given logic. MetaTrader Terminal 4 will dispatch the OrderSend() details to the remote MetaTrader 4 Server and if your values do meet the Broker-side Terms & Conditions, you will get such trading position opened ( exposed to Market Risk, while being fully backed & covered by your Equity ).

At the same time, the MetaTrader 4 Server will ensure, that no other code is required per-se for such position to become <autoXTO_TP>-terminated on the very moment the FX-Market reaches the predefined TP-termination level.

While the above is true, it is however fair to say that professional-grade algo-trading systems have many other utility-services, attached to the core trading logic. Just to have some idea, designs with about 80.000 ~ 100.000 SLOCs are common in production-grade systems.


Where to go from here?

It might be helpfull to re-read the MQL4 documentation ( let me put this a bit clearer -- the localhost-installed and updated release of the actual-release-of-New-MQL4 language ... not the static and "old" texts on web, as the syntax-rules & context-specific limits creep a lot ... still do, ref. below )
rather
than
to headbang again into another issues with "old"-MQL4 syntax code-snippets.

The MQL4 language evolves a lot during the last few years and lot of web-posted code-snippets have lost their explanatory value, due to many shifts in paradigm, that happened "inside the language" or due to code-execution platform changes.

Bitter? Yes.
Painfull? Yes.

This is the Life, nevertheless...

Community
  • 1
  • 1
user3666197
  • 1
  • 6
  • 50
  • 92
0

So, I assume that you've got the first part (opening a trade) of your logic right. Now you want all orders get closed when one of them reaches TP. Here is how you can do that.

Add this to start() function:

int total = OrdersHistoryTotal();
for (int i = total - 1; i >= 0; i--)
{
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) == false)
    {
        Print("Error selecting order from history: ", GetLastError());
        break;
    }
    if ((OrderSymbol() != Symbol()) || (OrderType() != OP_BUY) || (OrderClosePrice() < OrderTakeProfit())) continue;
    CloseAll();
    break;
}

And this outside the start() function:

void CloseAll()
{
   int total = OrdersTotal();
   for (int i = total - 1; i >= 0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS) == false) continue;
      if ((OrderSymbol() != Symbol()) || (OrderType() != OP_BUY)) continue;
      RefreshRates();
      OrderClose(OrderTicket(), OrderLots(), Bid, Slippage);
   }
}
Enivid
  • 210
  • 2
  • 9
  • You might want to update your answer, @Enivid. The code is wrong both in the first assumption on correctness of opening a position, and in the second part, about a code-driven closing of "all" trades } when there is **`{ 0 | 1 }`** trade position managed ( `0` effectively, until the syntax of the first part finally gets corrected ). – user3666197 Mar 28 '16 at 19:40
  • You might next time also better review your own code, so as to **avoid syntax errors from being posted in an education-motivated answer** and better reflect the OP context-of-use ( as an example, you have forgotten to include an explicit **`OrderMagicNumber()`** check in the copied snippet code-logic ). – user3666197 Mar 28 '16 at 19:49
  • Thanks for answering. I'm still lost though. I want it to only open one order at a time and close when the buy orders' take profit is reached and when the conditions are met again it opens another one order. I acknowledge that system might not be profitable but I want to test it. So can you show me what that would look like so I can test it in the strategy tester. Thanks again. – Rob Mar 28 '16 at 19:50
  • @Rob, you need not "add" anything in order to run an MT4 Back-tester. Read carefully through the other answer and just polish the syntax ( erase colon **`;`** inside an **`if(...){...}`** condition-part of the constructor ( *inside/right after the first pair of parentheses* ) and run the code inside `OnTick(){...}`. It is that simple. – user3666197 Mar 28 '16 at 19:55
  • @Rob you may already know, that MT4-code-IDE ( aka MetaEditor ) can help you lot with syntax-highlighting, parenthesis-matching and online-help access, if you configure it to become a bit more handy for the language exploration. **Did you try, Rob, to tweak it a bit to fit your preferences?** You will, after some practice, realise, there are a few errors even in the MQL4 Reference / Help, that do not work straight on copy/paste, but anyway **do not hesitate to experiment a lot with the code inside MetaEditor.** – user3666197 Mar 28 '16 at 20:00