Quantcast
Channel: MQL5: MetaTrader 5 trading, automated systems and strategy testing forum
Viewing all 75046 articles
Browse latest View live

New to MQL5: EA Invalid stops, error 4756

$
0
0

Hello forum, good day.

 

I'm an MQL5 newbie and I have started with the Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners  tutorial, but when I run the code I get a message about Invalid stops and an error 4756. I started to modify it but still continue to get the same errors. Could someone with more experience in MQL5 point me in the right direction or help me with a couple freelance classes/jobs in order to complete this EA please? Help will be much appreciated. 

 

What I'm trying to do in my first EA is: 

1. Check ADX indicator values when a new bar is created (right at 00:00 hours).

2. If +DI > -DI it should be Buy position, else, if +DI < -DI should be a Sell position.

3. Once determined if it is a Buy or Sell position:

    3.1. If it is a Buy position and the previous bar is black (Bear), the order should be placed as a pending order (Buy Stop) with the Opening price of the previous bar; Stop Loss should be placed at the Lowest price from previous bar - 0.1 cents. If the previous bar is not black, then the order shuld not be placed.

    3.2. If it is a Sell position and the previous bar is white (Bull), the order should be placed as a pending order (Sell Stop) with the Opening price of the previous bar; Stop Loss should be placed at the Highest price from previous bar + 0.1 cents. If the previous bar is not white, then the order will not be placed.

4. Stop Loss should be moved every day.

5. When the latest price of the product (ask/buy, or bid/sell) reaches Stop Loss, the position is closed. 


For now I'm trying to do this with a Market order, but I need to do it with a Pending order. Here is the code I'm using:

 

//--- Input variables
input double Lots     = 0.1;    // Lots to trade / Trade volume
input int StopLoss    = 1000;   // Stop Loss should be in $
input int ADX_Period  = 14;     // ADX Period

//--- Global Variables
bool BuyOpened, SellOpened;     // Variables to check for Opened positions
int ADX_Handle;                 // Handle for our ADX indicator
int SL;                         // To be used for Stop Loss value

double ADX_Val[],               // Dynamic arrays to hold the values of ADX,
       Plus_DI[],               // +DI and
       Minus_DI[];              // -DI for each bar

double p_Open,                  // Dynamic arrays to hold the opening,
       p_High,                  // highest,
       p_Low,                   // lowest
       p_Close;                 // and closing prices of each bar

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit () {

    //--- Get handle for ADX indicator
    ADX_Handle = iADX(NULL, 0, ADX_Period);

    //--- What if ADX_Handle returns invalid handle?
    if ( ADX_Handle < 0 ) {
        Alert("Error creating ADX_Handle for indicators - error: ", GetLastError(), "!");
    }

    //--- Assign StopLoss value to SL variable
    SL = StopLoss;

    //--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
    if ( _Digits == 5 || _Digits == 3 ) {
        SL *= 10;
    }

    //--- Check that everything is running correctly
    return(0);

} // end OnInit()

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit (const int reason) {

    //--- Release our indicator handles
    IndicatorRelease(ADX_Handle);

} // end OnDeinit()

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick () {

    /**
     * Check for new bars
     */
    //--- Do we have enough bars to work with?
    if ( Bars(_Symbol, _Period) < 60 ) {
        Alert("We have less than 60 bars, EA will not exist!!");
        return;
    }

    //--- We will use the static Old_Time variable to serve the bar time.
    //--- At each OnTick execution we will check the current bar time with the saved one.
    //--- If the bar time isn't equal to the saved time, it indicates that we have a new tick.
    static datetime Old_Time;
    datetime New_Time[1];
    bool IsNewBar = false;

    //--- Copying the last bar time to the element New_Time[0]
    int copied = CopyTime(_Symbol, _Period, 0, 1, New_Time);

    if ( copied > 0 ) { // ok, the data has been copied successfully
        if ( Old_Time != New_Time[0] ) { // if old time isn't equal to new bar time
            IsNewBar = true; // if it isn't a first call, the new bar has appeared

            if ( MQL5InfoInteger(MQL5_DEBUGGING) ) {
                Print( "We have new bar here ", New_Time[0], " old time was ", Old_Time );
            }

            Old_Time = New_Time[0];
        }
    } else {
        Alert("Error in copying historical times data, error: ", GetLastError(), "!!");
        ResetLastError();
        return;
    }

    //--- EA should only check for new trade if we have a new bar
    if ( IsNewBar == false ) {
        return;
    }

    //--- Do we have enough bars to work with?
    int Mybars = Bars(_Symbol, _Period);

    if ( Mybars < 60 ) { // if total bars is less than 60 bars
        Alert("We have less than 60 bars, EA will now exist!!");
        return;
    }

    //--- Define some MQL5 structures we will use for our trade
    MqlTradeRequest request;    // To be used for sending our trade requests
    MqlTradeResult result;      // To be used to get our trade results
    MqlRates rates[];           // To be used to store prices, volumes and spread of each bar
    ZeroMemory(request);        // Initialization of request structure

    /**
     * Reverse the time series ... 3 2 1 0
     */
    //--- The rates array
    ArraySetAsSeries(rates, true);

    //--- The ADX values arrays
    ArraySetAsSeries(ADX_Val, true);

    //--- The ADX +DI values array
    ArraySetAsSeries(Plus_DI, true);

    //--- The ADX -DI values array
    ArraySetAsSeries(Minus_DI, true);

    //--- Copy the new values of our indicators to buffers (arrays) using the handle
    CopyBuffer(ADX_Handle, 0, 1, 3, ADX_Val);
    CopyBuffer(ADX_Handle, 1, 1, 3, Plus_DI);
    CopyBuffer(ADX_Handle, 2, 1, 3, Minus_DI);

    //--- Get the details of the last 3 bars
    int copied_rates = CopyRates(_Symbol, _Period, 0, 3, rates);

    // CopyOpen(_Symbol, Period(), 0, 3, p_Open);
    // CopyHigh(_Symbol, Period(), 0, 3, p_High);
    // CopyLow(_Symbol, Period(), 0, 3, p_Low);
    // CopyClose(_Symbol, Period(), 0, 3, p_Close);

    //--- Do we have positions opened already?
    BuyOpened = false;  // Variable to hold the result of Buy opened position
    SellOpened = false; // Variable to hold the result of Sell opened position

    if ( PositionSelect(_Symbol) == true ) { // We have an opened position
        if ( PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ) {
            BuyOpened = true;  // It's a buy
        } else if ( PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL ) {
            SellOpened = true; // It's a sell
        }
    }

    //--- Current position information
    // bool open_position = PositionSelect(_Symbol);
    // long position_type = PositionGetInteger(POSITION_TYPE);

    // Copy the previous bar prices prior to the current bar, that is Bar 1
    p_Open  = rates[1].open;    // Bar 1 opening price
    p_High  = rates[1].high;    // Bar 1 highest price
    p_Low   = rates[1].low;     // Bar 1 lowest price
    p_Close = rates[1].close;   // Bar 1 closing price

    //--- Declare variables to hold our Buy and Sell conditions
    bool Buy_Condition  = (Plus_DI[0] > Minus_DI[0]) && (p_Close < p_Open);     // Buy condition
    bool Sell_Condition = (Plus_DI[0] < Minus_DI[0]) && (p_Close > p_Open);     // Sell condition

    /**
     * Check for long/Buy, or a short/Sell
     */
    if ( Buy_Condition ) { //--- Open Buy order
        //--- Any opened Buy position?
        if ( BuyOpened ) {
            Alert("We already have a Buy position!");
            return;     // Don't open a new buy position
        }

        ZeroMemory(request);
        ZeroMemory(result);

        request.action       = TRADE_ACTION_DEAL;
        request.type         = ORDER_TYPE_BUY;
        request.symbol       = _Symbol;
        request.volume       = Lots;
        request.price        = NormalizeDouble(p_Open, _Digits);
        request.sl           = NormalizeDouble(p_High - SL * _Point, _Digits);
        request.type_filling = ORDER_FILLING_FOK;
        request.deviation    = 50;

        //--- Send Buy order
        int trade_order_1 = OrderSend(request, result);

        //--- Get the result code
        if ( result.retcode == TRADE_RETCODE_PLACED || result.retcode == TRADE_RETCODE_DONE ) {
            Alert("A buy order has been successfully placed with Ticket #", result.order, "!");
        } else {
            Alert("The buy order request could not be completed - error: ", GetLastError(), "!");
            ResetLastError();
            return;
        }
    } else if ( Sell_Condition ) { //--- Open Sell order
        //--- Any opened Sell position?
        if ( SellOpened ) {
            Alert("We already have a Sell position !");
            return;     // Don't open a new Sell position
        }

        ZeroMemory(request);
        ZeroMemory(result);

        request.action       = TRADE_ACTION_DEAL;
        request.type         = ORDER_TYPE_SELL;
        request.symbol       = _Symbol;
        request.volume       = Lots;
        request.price        = NormalizeDouble(p_Open, _Digits);
        request.sl           = NormalizeDouble(p_Low + SL * _Point, _Digits);
        request.type_filling = ORDER_FILLING_FOK;
        request.deviation    = 50;

        //--- Send Sell order
        int trade_order_2 = OrderSend(request, result);

        //--- Get the result code
        if ( result.retcode == TRADE_RETCODE_PLACED || result.retcode == TRADE_RETCODE_DONE ) {
            Alert("A sell order has been successfully placed with Ticket #", result.order, "!");
        } else {
            Alert("The sell order request could not be completed - error: ", GetLastError(), "!");
            ResetLastError();
            return;
        }
    }

} // end OnTick()

//+------------------------------------------------------------------+

 

Regards and thank you in advance,

codeMolecules 


data gold

$
0
0
newdigital:
I think - it depends on the broker (some brokers do not have gold/xauusd for example).
Hello my friend I talked more brokers who were unaware of their
If a friend is someone who knows what 1970 gold broker data please help me thanks

Filling types

$
0
0

On the specification window, the filling type of a pair is designated as "all" with my broker.

But, on the "new order" window, there are only two options: FOK and IOC.

Can I use "return" in this case?


Additionally, if available, with which function I can see the used filling type for an opened position ... I could not find such a function?

Is the Canadian Dollar ready to change its direction

$
0
0
bermaui314:

On a Monthly graph it seems that the USDCAD have an old resistance around 1.1850 back to 2004.


Also it have been rising for five consecutive months including January 2015.

On a daily graph it seems also that the currency pair had been moving inside a channel for several months and as it hit its resistance area it also touch the upper line of its rising channel.


By adding evidence it seems to me that USDCAD is in a Key zone that might lead it to reverse its trend or jump to a new level.

Good analyze. Now we can wait for a confirmation in one direction or an other.

Functionalizing my sending order code

$
0
0

When I put the following code in the OnTick() event handler, it is working:

   MqlTradeRequest request;
   MqlTradeResult result;
   
   request.action = TRADE_ACTION_DEAL;
   request.symbol = _Symbol;
   request.volume = 1;
   request.type = ORDER_TYPE_BUY;
   request.type_filling = ORDER_FILLING_IOC;
   request.price = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
   request.sl = 0;
   request.tp = 0;
   request.magic = 123;
   
   OrderSend(request,result);
   Print(result.retcode);


But, when I place the exactly same code in a function, it does not work and gives the error 10013 - invalid request:

//+------------------------------------------------------------------+
//|                                                            1.mq5 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"

void Trade()
{
   MqlTradeRequest request;
   MqlTradeResult result;
   
   request.action = TRADE_ACTION_DEAL;
   request.symbol = _Symbol;
   request.volume = 1;
   request.type = ORDER_TYPE_BUY;
   request.type_filling = ORDER_FILLING_IOC;
   request.price = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
   request.sl = 0;
   request.tp = 0;
   request.magic = 123;
   
   OrderSend(request,result);
   Print(result.retcode);
}
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
     
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(PositionSelect(_Symbol))
     {
      return;
     }
     
   Trade();

  }
//+------------------------------------------------------------------+


What is the problem with this functionalized code?

Thanks a lot.

Toolbox and magic number

A little help with coding

$
0
0

Hi all

i need a little help with this part of a code

At the moment with this code my ea opens maximum two orders each time but the problem is that if there is a second order it could be either a second buy either a second sell and i only need it to be able to open one sell and one buy .I'm not a programmer so please answer me as simple as possible

bool TradeNotPlacedYet()
{
   int total = OrdersTotal();
   if (total > 1)
   {
      for(int cnt=total-1;cnt>=0;cnt--)
      {
         if(OrderSelect(cnt,SELECT_BY_POS))
         {
            if(OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber)
            {
               return (false);
            }
         }
      }
   }
   int histotal = OrdersHistoryTotal();
   if (histotal > 1)
   {
      for(cnt=histotal-1;cnt>=0;cnt--)
      {
         if(OrderSelect(cnt,SELECT_BY_POS,MODE_HISTORY))
         {
            if(OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber)
            {
               if (OrderOpenTime() >= Time[0])
               {
                  return (false);
               }
            }
         }
      }
   }
   return (true);


Traders Joking


mt5 signals: not connected, select from the signals database

$
0
0
lemmi:

Hello Community

I have the following problem when i try to join a signal:

i have internet connection, and my login credentials are typed in Tools->Community

but in Tools->Signals there is the message "not connected, select from the signals database". Does anyone have the same problem or know how to solve it?

Thanks in advance

Same issue here. Anyone has a solution?

Discussion of article "How to Access the MySQL Database from MQL5 (MQL4)"

$
0
0

Hi.

Like the concept. Should be a great help

But I run into some problem. I am using 64 bit nd I have downloaded them and started out on a test script to see how it works.

but crashes in MySQLGetFieldAsxxxxx

2015.01.09 21:32:09.535    testsql (AUDNZD,H1)                  000000013F81347A 488BF2            mov        rsi, rdx
2015.01.09 21:32:09.535    testsql (AUDNZD,H1)                  000000013F813476 4883EC20          sub        rsp, 0x20
2015.01.09 21:32:09.535    testsql (AUDNZD,H1)                  000000013F813475 57                push       rdi
2015.01.09 21:32:09.535    testsql (AUDNZD,H1)                  000000013F813470 4889742418        mov        [rsp+0x18], rsi
2015.01.09 21:32:09.535    testsql (AUDNZD,H1)    Access violation at 0x000000013F8134B3 read to 0x0000000000000001
2015.01.09 21:32:09.535    testsql (AUDNZD,H1)    +++++++++++++0
2015.01.09 21:32:09.535    testsql (AUDNZD,H1)    2 row(s) selected.
2015.01.09 21:32:09.425    testsql (AUDNZD,H1)    Connected
2015.01.09 21:31:18.135    testsql (AUDNZD,H1)    x  0  y


Sorce:

#include <FXCM\PairsInfo.mqh>
#include <FXCM\MQLMySQL.mqh>

//--- input parameters
input string   MySQLURL="yyyyyyyyyyyyyy";
input string   MySQLDB = "forex";
input string   MySQLParms = "tradeparms";
input string   MySQLUser="Ingvar";
input string   MySQLPW="xxxxxxxxxxxx";
input int      MySQLPort=3306;
input string   GroupID= "Groupxxx";

PairsInfo prms;

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
  string SQLString = "";
  string Q;
  string C = ",";
  StringSetCharacter(Q,0,34);
  
  string query;
  int Cursor;
  int DB;
  int rows;
  
  DB = MySqlConnect(MySQLURL, MySQLUser, MySQLPW, MySQLDB, MySQLPort, "0", 0);
  if (DB == -1) 
    {
      Print ("Connection failed! Error: "+MySqlErrorDescription); 
      return;
    }

    Print ("Connected");
    
  //  query = "Select * From tradeparms";
    
  //  query = "Select * FROM tradeparms WHERE TradeType = 2";
    
    query = "SELECT Pair, TradeType, SetupID FROM tradeparms WHERE TradeType = 2 AND Pair = 'USDJPY'";
     
     
   Cursor = MySqlCursorOpen(DB,query);
   if(Cursor <  0)
    {
      Print("Cursor error");
      return;
    }


   string pair= "x";
   int tradetype = 0;
   string setupid = "y";
   
   rows = MySqlCursorRows(Cursor);
   Print (rows, " row(s) selected.");
   
   for(int i=0;i<rows;i++)
    {
     if (MySqlCursorFetchRow(Cursor))  
       {
        Print("+++++++++++++" + i);
        pair = MySqlGetFieldAsString(Cursor, 0);                    << crashes here.   
   //     tradetype = MySqlGetFieldAsInt(Cursor,1);
   //      setupid = MySqlGetFieldAsString(Cursor,2);
       }
     }  
      
   Print(pair + "  " + DoubleToString(tradetype,0) + "  " + setupid);
   
   MySqlCursorClose(Cursor);
 
  
 } 

demo signal and suscribtion fees

$
0
0
Tradingstat:

Hello,

I developed a good strategy and i would like to know if I can trade with a demo account and set fees for my signal.

I am a student so i don't have enough money to trade with a live account :)

Regards,

Henry

Why not just open a micro live account? There are numerous brokers where you can open a live account and trade for less than $10.00 USD.

If your strategy is profitable, then you should have no problem showing it works on a smaller account.

Check your private messages, I sent you some information.

Indicators: Labtrend1_v2

$
0
0

Hi igorad, corrected an error :

 else      UpTrendSignal[shift]=EMPTY_VALUE;

for :

 else      UpTrendSignal[shift]=0.0;

Traders Joking

MT4 and Raspberry PI b+

$
0
0

Hello,  does anyone know of a way to get MT4 working on raspberry pi b+  to test an EA out live (on demo) and if it is even possible?

Cheers, Sam. 

Discussion of article "How to Test a Program Before Buying it from MQL5 Market"

$
0
0

I believe that this article can be improved with the following points to minimize curve fitting and to reject poor EAs.

 

1) It is important to back test a system over 10 years with at least 1,000 trades. Why? Two to three years trading results are prone to curve fitting. Less than 1,000 trades do not provide a large enough statistical sample.

2) It is important to used fix 0.1 lot for testing over the entire period. This will unmask any manipulation of money management to hide poor drawdown. Fixed 0.1 lot testing will show the true reward and risk of a trading system.

3) For MT5 EAs checking, it is important to utilize MT5's MOST ADVANCE and HIGHLY ACCURATE "Every Tick" setting. If an EA can generate a positive result with "Every Tick" setting, then it will have a good chance to survive in the real market. 


Getting enumaration expressions from Print()

$
0
0

As a newbie in C++ and MQL, sometimes, I can not be sure that I'm writing the code as it should be :)

Help needed

How to make free signal on real account.

$
0
0
kashif6331:
Dear, can any one guide How to make free signal on real account. When i make this signal for free, moderate converts to @ $20. How can i make free signal from real account.
You can't sorry. Demo account = free signal, real account = paid signal.

What Is The Best Using Of The MA To Detect The Trend Direction ?

$
0
0
I Use 200 EMA to tell me the main trend..Most of the time that is where the price direction is heading.. for quick trend direction I use 20 ema, price above 20 ema= uptrend, below 20 ema= downtrend

Agents always stopped

$
0
0
widhie75:

well i think it works now... changing from 'fermato' to 'funzionando'.

just like angevoyageur said, be patient.....

Traffic in/out should increase slowly, It takes about more than a week for me to see my PC system displayed on "Setting > Agents" (MQL5.com profile/setting forum)

Don't forget to 'check' "Sell computing resource via MQL5 Community account" (under MQL5 Cloud Network tab)

Ok, after 8 hours now I have a movement in IN/OUT but after one hour steps are still 0.. As you can see on the new screen. Is it something I need to wait to I guess, right?

 

 

About the "Sell" I think I did it right, as you can see from the other screen but under the name the window shows "The account must be valid otherwise you will offer your  agents for free" Is this meaning my account is not correct or is it a normal message? 

 Thank you for all help!

 

 

Viewing all 75046 articles
Browse latest View live