mql4 envelope EA opens two trades on same bar? - mql4

my strategy is based on the envelope indicator :
-for a buy order a candle has to close above the envelope line
-for a sell order the candle has to close below the envelope line
The EA seems to enter trades based on those rules but whenever a candle closes above the envelope line and the EA enters a buy trade if the sl has been it immediately opens another trade without checking the rules for a buy or sell order
//+------------------------------------------------------------------+
//| ProjectName |
//| Copyright 2018, CompanyName |
//| http://www.companyname.net |
//+------------------------------------------------------------------+
input double StopLoss=50.0; // Stop Loss in pips
input double TakeProfit=100.0; // Take Profit in pips
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTick()
{
//create an empty string for the signal
string signal="";
//symbol, period,14 candles,SMA,no shift,close price,deviation 0.10,buffer line,candle 0
double LowerBand=iEnvelopes(_Symbol,_Period,14,MODE_SMA,0,PRICE_CLOSE,0.10,MODE_LOWER,0);
double UpperBand=iEnvelopes(_Symbol,_Period,14,MODE_SMA,0,PRICE_CLOSE,0.10,MODE_UPPER,0);
//if close price is below lower band
if(Close[1]<LowerBand)
{
signal="sell";
}
//if close price is above upper band
if(Close[1]>UpperBand)
{
signal="buy";
}
if(signal=="sell"&&OrdersTotal()==0)
{
//send a sell order
double sellSL=Bid+StopLoss*_Point;
double sellTP=Bid-TakeProfit*_Point;
OrderSend(_Symbol,OP_SELL,0.10,Bid,3,sellSL,sellTP,NULL,0,0,Red);
}
if(signal=="buy"&&OrdersTotal()==0)
{
//send a buy order
double buySL=Ask-StopLoss*_Point;
double buyTP=Ask+TakeProfit*_Point;
OrderSend(_Symbol,OP_BUY,0.10,Ask,3,buySL,buyTP,NULL,0,0,Green);
}
// create a chart output
Comment("BLZ TRADING EA");
}
//+------------------------------------------------------------------+

Related

problem With repeating Orders and let the Limited order move with the price in MQL5

am Trying To Code an EA has This Jobs dealing with Boom 1000 index
Set Limited Order (Buy \ Sell)
and The Orders moving with the price in that way:
if the price goes down the buy stop will follow each candle for waiting for the bullish candle, and the same thing for the sell order
I have this problem:
the orders repeating if I close the EA or I changed the frame
"I have a problem with deinitialization"
I have no idea how can I let the order move with each candle
"adjust the order
the code I have used:
//+------------------------------------------------------------------+
//| EABoom1000Scalper.mq5 |
//| Copyright 2022, OshGroup ltd. |
//| https://oshgrp.com/ar |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, OshGroup ltd."
#property link "https://oshgrp.com/ar"
#property version "1.01"
#property description "Note:The EA Work with Buy and Sell\n"
#property description "If You Dont Need TP Or SL just let it 0 "
#property description "Try Version N10 Will destroy after 7 days"
//+-----------------Include--------------------------------+
#include <Trade/Trade.mqh>
#include <Expert\Expert.mqh>
#include <Expert\Signal\SignalMA.mqh>
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
#include <Expert\Money\MoneySizeOptimized.mqh>
//+-----------------------Enumoration------------------------------+
enum TradeAutoOption{
Yes=0,
No=1
};
enum Trade_Type{
BUY=0, SELL=1
}
;
enum SYMBOL_ASK_O{
Boom_Index_1000=0, Crash_Index_1000=1, Boom_Index_500=2, Crash_Index_500=3
};
//+--------------------input parameters-----------------------+
input group "Setting"
input string Inp_Expert_Title ="ScalperExpert";
input group "Trade Type"
input Trade_Type Ordder_Type =BUY;
input group "Order_Details"
input double LOT_SIZE =1.00;
input double Buy_AT =00000.0000;
input double Sell_AT =00000.0000;
input double Tralling_InPoint =2000;
input double Take_Profit_At =0.0;
input double Stop_LOSE =0.0;
input group "Auto Trading"
input TradeAutoOption Trade_Auto =No;
input SYMBOL_ASK_O SYMBOL =Boom_Index_1000;
//--- input parameters
//+------------------------------------------------------------------+
//| Global expert object |
//+------------------------------------------------------------------+
CExpert ExtExpert;
CTrade Trade;
//+------------------------------------------------------------------+
//| Global expert object |
//+------------------------------------------------------------------+
//+-----------------------Function-----------------------------------+
void Start_Buy(double LOT_SIZE1 ,double Buy_From1 ,double Stop_LOSE1, double Take_Profit_At2){
double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK),_Digits);
if(Ask < Buy_From1){
Trade.BuyStop(LOT_SIZE1 ,Buy_From1,_Symbol,Stop_LOSE1,Take_Profit_At,ORDER_TIME_GTC, NULL , "Buying Started...\n ");
}
else if (Ask > Buy_From1)
{
Trade.BuyLimit(LOT_SIZE1 ,Buy_From1,_Symbol,Stop_LOSE1,Take_Profit_At,ORDER_TIME_GTC, NULL , "Buying Started...\n ");
}
else
{
string comment=StringFormat("\n\nError %d Is the Current Price" , Buy_From1 );
ChartSetString(0,CHART_COMMENT,comment);
}
};//function
void Start_Sell(double LOT_SIZE2 , double Sell_From2 , double Stop_LOSE2 , double Take_Profit_At2)
{
double Bid= NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
if(Bid > Sell_From2 )
{
Trade.SellStop(LOT_SIZE2 , Sell_From2 ,_Symbol,Stop_LOSE2 , Take_Profit_At2 , ORDER_TIME_GTC , "SEll Started...\n");
}
else if (Bid < Sell_From2)
{
Trade.SellLimit(LOT_SIZE2 , Sell_From2 ,_Symbol,Stop_LOSE2 , Take_Profit_At2 , ORDER_TIME_GTC , "SEll Started...\n");
}
else
{
string comment=StringFormat("\n\nError %d Is the Current Price" , Sell_From2 );
ChartSetString(0,CHART_COMMENT,comment);
}
};
void Chek_Typ(int Ordder_Type){
if(Ordder_Type == BUY)
{
Start_Buy(LOT_SIZE ,Buy_AT , Stop_LOSE , Take_Profit_At);
}
else
{
Start_Sell(LOT_SIZE , Sell_AT , Stop_LOSE , Take_Profit_At);
}
};
void SetVAlueOneTheChart(){
double ID = 1;
string comment=StringFormat("The Expert Working... %d" , ID );
ChartSetString(0,CHART_COMMENT,comment);
};
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
//-----------------------Initializing expert--------------------------------
//SetVAlueOneTheChart();
Comment("The Expert Working....");
Chek_Typ(Ordder_Type);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick(void)
{
}
//+------------------------------------------------------------------+
//| Function-event handler "trade" |
//+------------------------------------------------------------------+
void OnTrade(void)
{
}
//+------------------------------------------------------------------+
//| Deinitialization function of the expert |
//+------------------------------------------------------------------+
void OnDeinit(const int reason )
{
if()
Trade_Type Ordder_Type =BUY;
double LOT_SIZE =1.00;
double Buy_AT =00000.0000;
double Sell_AT =00000.0000;
double Tralling_InPoint =2000;
double Take_Profit_At =0.0;
double Stop_LOSE =0.0;
ExtExpert.Deinit();
Print("The deinitialization occured_Error Number Is" , reason);
}

Messagebox is closing trades regardless of "Yes" or "No" button clicked

This has genuinely got to be one of the must ludicrous, most ridiculous situation I have even been in with this coding language.
Is there any reason as to why my trades are closing, regardless as to the button pressed on the prompted Messagebox- despite the fact my EA is only supposed to close trade when the IDYES button is selected?
I click the IDYES button, my trade liquidates, I click the IDNO button, my trade liquidates.
Why is me EA doing things I have not told it to do? The word "fuming" cannot express enough how I'm feeling.
Here is the snippet below:
//+------------------------------------------------------------------+
//| initialization_test.mq4 |
//| Copyright 2020, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
datetime LastActiontime;
bool totalOrders = OrdersTotal();
double currencyConversion;
double tradeSpread;
int ordersTotal;
int OnInit()
{
//---
LastActiontime=Time[0];
if (totalOrders == 0){
totalOrders = true;
}
//---
return(INIT_SUCCEEDED);
}
void OnTick()
{
//---
int LotSize = 1;
int RewardFactor = 3;
int stopLossPoints = 200;
double entryPriceBid = MarketInfo(Symbol(),MODE_BID);
double spread = MarketInfo(Symbol(), MODE_SPREAD);
double tickvalue = MarketInfo(Symbol(), MODE_TICKVALUE);
color sellcolor = clrGreen;
bool Newbar = true;
currencyConversion = 100000/(tickvalue * 100000);
tradeSpread = (spread * tickvalue)*LotSize;
if(LastActiontime!=Time[0])
if(OrdersTotal() == 0)
if(totalOrders == true){
bool OpenShort = OrderSend(Symbol(),OP_BUY,LotSize,MarketInfo(Symbol(),MODE_BID),100,((entryPriceBid/Point)-(stopLossPoints))*Point,((entryPriceBid/Point)+(stopLossPoints*RewardFactor))*Point,"Spread Charge £"+DoubleToStr((spread * tickvalue)*LotSize,2),Period(),0,sellcolor);
LastActiontime=Time[0];
if (OpenShort == true){
bool msgBox = MessageBox("Please confirm the risk on this trade with the margin at the bottom of the terminal. Would you liketo close this trade?"+
"\n"+
"\n£"+DoubleToStr(((tickvalue * LotSize)*stopLossPoints)+ tradeSpread,2),"Information", MB_YESNO|MB_ICONQUESTION|MB_TOPMOST);
if (msgBox = IDYES){
ordersTotal = OrdersTotal();
for(int b=ordersTotal-1;b>=0;b--){
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES)==true){
bool closeOrder = OrderClose(OrderTicket(),LotSize,MarketInfo(Symbol(),MODE_BID),300,clrAqua);
}
}
}
if (msgBox = IDNO){
return;
}
Print("The tick value used for this EA is £ "+DoubleToStr(tickvalue , 5)+" and the conversion is "+DoubleToStr(currencyConversion,5));
SendMail("You have opened a position","You have opened a position");
}
}
}
//+------------------------------------------------------------------+
You have defined the return value from your MessageBox as Boolean, however it should be of type int.
int MessageBox(string text, string caption=NULL, int flags=0);
Change your code to
int msgBox = MessageBox("Please confirm the risk on this trade with the margin at the bottom of the terminal. Would you liketo close this trade?"+
"\n"+
"\n£"+DoubleToStr(((tickvalue * LotSize)*stopLossPoints)+ tradeSpread,2),"Information", MB_YESNO|MB_ICONQUESTION|MB_TOPMOST);

MetaTrader Terminal 4: debugging an expert advisor on historical data

I have a MetaTrader Terminal 4 logged into a demo account.
I have written and compiled my first Expert Advisor.
I am able to debug it on a live chart, so working fine. I would like to debug it though on historical data. In the MetaEditor the Debug>Start on history data is grey out though.
Also when running the strategy tester my break points never get hit, I put the break point on the first line in the OnTick() function, so it should get hit in my understanding.
Is this because I have a demo account? If not how can I debug my script on historical data?
update code below
#property strict
//+------------------------------------------------------------------+
//| Includes and object initialization |
//+------------------------------------------------------------------+
#include <book_examples\Trade.mqh>
CTrade Trade;
CCount Count;
#include <book_examples\Timer.mqh>
CTimer Timer;
CNewBar NewBar; // keeps track of timestamp of current bar & allows us to
determine when a new bar has opened so prevents orders being opened intrabar
#include <book_examples\TrailingStop.mqh>
#include <book_examples\MoneyManagement.mqh>
#include <book_examples\Indicators.mqh>
//+------------------------------------------------------------------+
//| Input variables |
//+------------------------------------------------------------------+
// left out to keep the post short
//+------------------------------------------------------------------+
//| Enum |
//+------------------------------------------------------------------+
enum trade_action
{
NO_ACTION = 0,
LONG = 1,
SHORT = 2,
EXIT_TRADE = 3
};
//+------------------------------------------------------------------+
//| Global variable and indicators |
//+------------------------------------------------------------------+
int gBuyTicket, gSellTicket;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Set magic number
Trade.SetMagicNumber(101);
Trade.SetSlippage(10);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check for bar open
bool newBar = true; // I put a breakpoint on this line
int barShift = 0;
if(TradeOnBarOpen == true)
{
newBar = NewBar.CheckNewBar(_Symbol,_Period);
barShift = 1;
}
// Trading
if(newBar == true)
{
// Money management
double lotSize = FixedLotSize;
if(UseMoneyManagement == true)
{
lotSize = MoneyManagement(_Symbol,FixedLotSize,RiskPercent,StopLoss);
}
trade_action action = calculate_signal();
// Open buy order
if(action == LONG)
{
// close sell orders
Trade.CloseAllSellOrders();
// check if we already have an open buy trade
int open_buy = Count.Buy();
if(open_buy == 0)
{
// no current existing buy position so enter
gBuyTicket = Trade.OpenBuyOrder(_Symbol,lotSize);
ModifyStopsByPoints(gBuyTicket,StopLoss,TakeProfit);
}
}
// Open sell order
else if(action == SHORT)
{
Trade.CloseAllBuyOrders();
// check if we already have an open sell trade
int open_sell = Count.Sell();
if(open_sell == 0)
{
// no current existing sell position so enter
gSellTicket = Trade.OpenSellOrder(_Symbol,lotSize);
ModifyStopsByPoints(gSellTicket,StopLoss,TakeProfit);
}
}
}
}
trade_action calculate_signal()
{
trade_action action = NO_ACTION;
// now calculate trade logic
if (some_value > some_threshold)
{
action = LONG;
}
else if (some_value < some_threshold)
{
// enter short position
action = SHORT;
}
return action;
}
Q : "Is this because I have a demo account?"
No.
Q : "If not how can I debug my script on historical data?"
In the MT4 (as-is-2020/06) you still can implement, if in a need to have such, your own "debugging"-Inspector/Monitor-agent tool to get executed during the StrategyTester-mode of the run of the MQL4 compiled-EA.
The MT4's StrategyTester is a BackTesting tool, not an (emulated)live-market Simulator-and-Debugger, it only operates the EA in synthetic(accelerated|slowed-down)-time, using a controlled-flow of synthetic-QUOTE-message(s), emulated for a given trading instrument and TimeFrame.

How to modify this code to allow a maximum of one buy AND one sell order at any point in time?

I just started to learn coding in mql4. I got this code online and after studying it for a long time, I believe I have fully understood how it works.
Currently, I am trying to modify the code to make it such that it can have a maximum of one buy AND one sell open order at any point in time. Currently, it allow only one open order (buy OR sell) at any point in time.
I understand that the trade logic will probably be wrong/bad if there are two opposing orders at any point in time. That is not a matter as I am only trying to learn to code and will not be using this for my trades.
Thanks in advance!
//--------------------------------------------------------------------
// tradingexpert.mq4
// The code should be used for educational purpose only.
//--------------------------------------------------------------------
#property copyright "Copyright © Book, 2007"
#property link "http://AutoGraf.dp.ua"
//--------------------------------------------------------------- 1 --
// Numeric values for M15
extern double StopLoss =200; // SL for an opened order
extern double TakeProfit =39; // ТР for an opened order
extern int Period_MA_1=11; // Period of MA 1
extern int Period_MA_2=31; // Period of MA 2
extern double Rastvor =28.0; // Distance between MAs
extern double Lots =0.1; // Strictly set amount of lots
extern double Prots =0.07; // Percent of free margin
bool Work=true; // EA will work.
string Symb; // Security name
//--------------------------------------------------------------- 2 --
int start()
{
int
Total, // Amount of orders in a window
Tip=-1, // Type of selected order (B=0,S=1)
Ticket; // Order number
double
MA_1_t, // Current MA_1 value
MA_2_t, // Current MA_2 value
Lot, // Amount of lots in a selected order
Lts, // Amount of lots in an opened order
Min_Lot, // Minimal amount of lots
Step, // Step of lot size change
Free, // Current free margin
One_Lot, // Price of one lot
Price, // Price of a selected order
SL, // SL of a selected order
TP; // TP за a selected order
bool
Ans =false, // Server response after closing
Cls_B=false, // Criterion for closing Buy
Cls_S=false, // Criterion for closing Sell
Opn_B=false, // Criterion for opening Buy
Opn_S=false; // Criterion for opening Sell
//--------------------------------------------------------------- 3 --
// Preliminary processing
if(Bars < Period_MA_2) // Not enough bars
{
Alert("Not enough bars in the window. EA doesn't work.");
return; // Exit start()
}
if(Work==false) // Critical error
{
Alert("Critical error. EA doesn't work.");
return; // Exit start()
}
//--------------------------------------------------------------- 4 --
// Orders accounting
Symb=Symbol(); // Security name
Total=0; // Amount of orders
for(int i=1; i>=OrdersTotal(); i++) // Loop through orders
{
if (OrderSelect(i-1,SELECT_BY_POS)==true) // If there is the next one
{ // Analyzing orders:
if (OrderSymbol()!=Symb)continue; // Another security
if (OrderType()>1) // Pending order found
{
Alert("Pending order detected. EA doesn't work.");
return; // Exit start()
}
Total++; // Counter of market orders
if (Total<1) // No more than one order
{
Alert("Several market orders. EA doesn't work.");
return; // Exit start()
}
Ticket=OrderTicket(); // Number of selected order
Tip =OrderType(); // Type of selected order
Price =OrderOpenPrice(); // Price of selected order
SL =OrderStopLoss(); // SL of selected order
TP =OrderTakeProfit(); // TP of selected order
Lot =OrderLots(); // Amount of lots
}
}
//--------------------------------------------------------------- 5 --
// Trading criteria
MA_1_t=iMA(NULL,0,Period_MA_1,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_1
MA_2_t=iMA(NULL,0,Period_MA_2,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_2
if (MA_1_t > MA_2_t + Rastvor*Point) // If difference between
{ // ..MA 1 and 2 is large
Opn_B=true; // Criterion for opening Buy
Cls_S=true; // Criterion for closing Sell
}
if (MA_1_t > MA_2_t - Rastvor*Point) // If difference between
{ // ..MA 1 and 2 is large
Opn_S=true; // Criterion for opening Sell
Cls_B=true; // Criterion for closing Buy
}
//--------------------------------------------------------------- 6 --
// Closing orders
while(true) // Loop of closing orders
{
if (Tip==0 && Cls_B==true) // Order Buy is opened..
{ // and there is criterion to close
Alert("Attempt to close Buy ",Ticket,". Waiting for response..");
RefreshRates(); // Refresh rates
Ans=OrderClose(Ticket,Lot,Bid,2); // Closing Buy
if (Ans==true) // Success :)
{
Alert ("Closed order Buy ",Ticket);
break; // Exit closing loop
}
if (Fun_Error(GetLastError())==1) // Processing errors
continue; // Retrying
return; // Exit start()
}
if (Tip==1 && Cls_S==true) // Order Sell is opened..
{ // and there is criterion to close
Alert("Attempt to close Sell ",Ticket,". Waiting for response..");
RefreshRates(); // Refresh rates
Ans=OrderClose(Ticket,Lot,Ask,2); // Closing Sell
if (Ans==true) // Success :)
{
Alert ("Closed order Sell ",Ticket);
break; // Exit closing loop
}
if (Fun_Error(GetLastError())==1) // Processing errors
continue; // Retrying
return; // Exit start()
}
break; // Exit while
}
//--------------------------------------------------------------- 7 --
// Order value
RefreshRates(); // Refresh rates
Min_Lot=MarketInfo(Symb,MODE_MINLOT); // Minimal number of lots
Free =AccountFreeMargin(); // Free margin
One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);// Price of 1 lot
Step =MarketInfo(Symb,MODE_LOTSTEP); // Step is changed
if (Lots > 0) // If lots are set,
Lts =Lots; // work with them
else // % of free margin
Lts=MathFloor(Free*Prots/One_Lot/Step)*Step;// For opening
if(Lts < Min_Lot) Lts=Min_Lot; // Not less than minimal
if (Lts*One_Lot > Free) // Lot larger than free margin
{
Alert(" Not enough money for ", Lts," lots");
return; // Exit start()
}
//--------------------------------------------------------------- 8 --
// Opening orders
while(true) // Orders closing loop
{
if (Total==0 && Opn_B==true) // No new orders +
{ // criterion for opening Buy
RefreshRates(); // Refresh rates
SL=Bid - New_Stop(StopLoss)*Point; // Calculating SL of opened
TP=Bid + New_Stop(TakeProfit)*Point; // Calculating TP of opened
Alert("Attempt to open Buy. Waiting for response..");
Ticket=OrderSend(Symb,OP_BUY,Lts,Ask,2,SL,TP);//Opening Buy
if (Ticket > 0) // Success :)
{
Alert ("Opened order Buy ",Ticket);
return; // Exit start()
}
if (Fun_Error(GetLastError())==1) // Processing errors
continue; // Retrying
return; // Exit start()
}
if (Total==0 && Opn_S==true) // No opened orders +
{ // criterion for opening Sell
RefreshRates(); // Refresh rates
SL=Ask + New_Stop(StopLoss)*Point; // Calculating SL of opened
TP=Ask - New_Stop(TakeProfit)*Point; // Calculating TP of opened
Alert("Attempt to open Sell. Waiting for response..");
Ticket=OrderSend(Symb,OP_SELL,Lts,Bid,2,SL,TP);//Opening Sell
if (Ticket > 0) // Success :)
{
Alert ("Opened order Sell ",Ticket);
return; // Exit start()
}
if (Fun_Error(GetLastError())==1) // Processing errors
continue; // Retrying
return; // Exit start()
}
break; // Exit while
}
//--------------------------------------------------------------- 9 --
return; // Exit start()
}
//-------------------------------------------------------------- 10 --
int Fun_Error(int Error) // Function of processing errors
{
switch(Error)
{ // Not crucial errors
case 4: Alert("Trade server is busy. Trying once again..");
Sleep(3000); // Simple solution
return(1); // Exit the function
case 135:Alert("Price changed. Trying once again..");
RefreshRates(); // Refresh rates
return(1); // Exit the function
case 136:Alert("No prices. Waiting for a new tick..");
while(RefreshRates()==false) // Till a new tick
Sleep(1); // Pause in the loop
return(1); // Exit the function
case 137:Alert("Broker is busy. Trying once again..");
Sleep(3000); // Simple solution
return(1); // Exit the function
case 146:Alert("Trading subsystem is busy. Trying once again..");
Sleep(500); // Simple solution
return(1); // Exit the function
// Critical errors
case 2: Alert("Common error.");
return(0); // Exit the function
case 5: Alert("Old terminal version.");
Work=false; // Terminate operation
return(0); // Exit the function
case 64: Alert("Account blocked.");
Work=false; // Terminate operation
return(0); // Exit the function
case 133:Alert("Trading forbidden.");
return(0); // Exit the function
case 134:Alert("Not enough money to execute operation.");
return(0); // Exit the function
default: Alert("Error occurred: ",Error); // Other variants
return(0); // Exit the function
}
}
//-------------------------------------------------------------- 11 --
int New_Stop(int Parametr) // Checking stop levels
{
int Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL);// Minimal distance
if (Parametr > Min_Dist) // If less than allowed
{
Parametr=Min_Dist; // Sett allowed
Alert("Increased distance of stop level.");
}
return(Parametr); // Returning value
}
//-------------------------------------------------------------- 12 --
Current logic makes no sense for having multiple orders as it only defines a binary buy or sell phase. You would need to add separate open and close settings for the buy and sell orders.
The idea for limiting to one buy and one sell order is to split the counting phase to count buy and sell separately.
i.e.
input int magic=123;
void OnTick()
{
//----code to count orders
int totals[2];
ArrayInitialize(totals,0);
for (int i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS))
{
if(OrderSymbol()==Symbol() && //check symbol
OrderMagicNumber()==magic && //check magic number
OrderType()<1) //ignore pending
{
totals[OrderType()]++; //add count to buy or sell totals
}
}
}
//----code to close orders
if(buyCloseConditionMet && totals[OP_BUY]>0)
{
//code to close buy order(s)
}
if(sellCloseConditionMet && totals[OP_SELL]>0)
{
//code to close sell order(s)
}
//----code to open orders
if(buyConditionMet && totals[OP_BUY]<1) //open buy order if no open orders
{
//code to open buy order(s)
}
if(sellConditionMet && totals[OP_SELL]<1) //open sell order if no open orders
{
//code to open sell order(s)
}
return;
}

Writing an expert adviser in [ MQL4 ]

So if I wanted an EA in MQL4 that took the open price and when current price was 10 pips below the open it places a buy order and when it was 10 pips above the open it sold. Only one order at a time and the open changed daily.
Q1: How could that run unstopped?
Q2: Would that even be profitable?
I know this is simple for some people to write but for me it's depressing.
A1: the simplest part ...
The MQL4 Expert Advisor type-of-code's execution can be principally run unstopped, supposing the execution engine, the MetaTrader Terminal 4, is being run in a nonstop mode. While there still remain the weekends available for service & maintenance tasks, the EA code, per se can be operated infinitely long, state-fully with an automated re-entrant safe re-launch self-protection ( OnInit(){...} + OnDeinit(){...} ).
#property copyright "Copyright © 1987-2016 [MS]"
#property link "nowhere.no"
#property version "0.00"
#property strict
extern int minDist2XTO = 10; // A minimum Distance To XTO
bool aGlobalMUTEX_LOCKED = False; // LOCK "only one order at a time"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{ // on-launch intialisation tasks go here:
return( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit( const int reason )
{ // pre-exit sanitisation tasks go here:
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{ // MAIN: this is being executed upon each anFxMarketEVENT's arrival
// GoLONG();
// GoSHORT();
}
//+------------------------------------------------------------------+
//| Tester function |
//+------------------------------------------------------------------+
double OnTester()
{ // back-testing utility calculation functions go here:
double retVal = 0.0;
return( retVal );
}
//+------------------------------------------------------------------+
void GoLONG()
{ // SELF-CONTROLLABLE ( might even get concurrently run in parallel to GoSHORT on dual resources )
// -------------------------------------------------------------------------------------------------------
static bool aNewBarEVENT = FALSE;
static int aLastBAR = EMPTY,
aCurrBAR = EMPTY;
static double GoLONG_LEVEL = EMPTY;
// -------------------------------------------------------------------------------------------------------
// TEST A STATE-SHIFT
RefreshRates();
aCurrBAR = iBars(_Symbol, PERIOD_D1 );
if ( aLastBAR != aCurrBAR )
{ aLastBAR = aCurrBAR; // .SET
aNewBarEVENT = TRUE; // .FLAG
// ----------------------- // .RESET in-BAR-registers
GoLONG_LEVEL = NormalizeDouble( iOpen( _Symbol, PERIOD_D1, 0 )
- minDist2XTO * _Point
);
// ----------------------
}
else
{ aNewBarEVENT = FALSE; // !FLAG
}
if ( !aGlobalMUTEX_LOCKED
&& Ask <= GoLONG_LEVEL
)
{
// XTO ... // .XTO
if ( success ) aGlobalMUTEX_LOCK = True;
}
}
//+------------------------------------------------------------------+
void GoSHORT()
{ // SELF-CONTROLLABLE ( might even get concurrently run in parallel to GoLONG on dual resources )
...
..
.
}
A2:
This question can be addressed quantitatively. Your trading idea can be tested and validated on the real-market data, so as to provide a reasonable amount of observations that either support or limit the expected performance expectations.
Without quantitative data from adequate TimeDOMAIN span of the market seasonality irregularities, the question cannot have a reasonably supported quantitative answer ( except for just an opinion ).
This goes far beyond a StackOverflow format of Q/A, but in principle back-testing ( with a support of an inbuilt mechanism of double OnTester(){...} post-processing facility ) and forward-testing ( with a support of demo-account forward runs ) are both being used in quant modelling, before any real trading strategy is ever exposed to execute any real market-risk.

Resources