Please guide me regarding spread - page 2

 
GumRai:

I would think that you could get this coded for 20 or 30 $

Right.. thanks .. Let me see if I can first find something for free, if I dont find anything, I will post up a job.
 
GumRai:

I would think that you could get this coded for 20 or 30 $

Actually, as now you have CONFIRMED that order closing already considers the spread, I think the above script should work for me .. thanks .. All i have to set in that is 10 pips .. and it will auto close it as you say by using ASK value if its a short and using a BID value if its a long .. and sum total of that as total account profit and closes all open orders .. doesnt touch pending order so all good .. thanks a loads.. also, could you please explain me ..in above program it says slippage = 5 .. what it means for this script? how will that play out in when script closes an order? oh and also, is it a script or EA ? or how to differenciate between the two? [ HOW DO YOU GUYS LEARN SO MUCH OF STUFF >.< ]
 
tatyawinchu:

Thanks a loads.. very clear and very useful .. I wonder how much it would cost to post such a job? How difficult would u rate such code may be? The code I got off web which I have posted above looks HUGE .. I mean I really cant shell out thousands of dollars...


Hello again,

No need to be worried, The code for what you want shouldn't be so complicated and, just so you know if you ever need to post a job, you are the one in control, you offer how much you can afford and you think it's worth !

On the other hand, if you're like me, I would try the free option first. Nothing to lose, maybe gain a few friends and learn something in the process.

Cheers

 
tatyawinchu:

Actually, as now you have CONFIRMED that order closing already considers the spread, I think the above script should work for me .. thanks .. All i have to set in that is 10 pips .. and it will auto close it as you say by using ASK value if its a short and using a BID value if its a long .. and sum total of that as total account profit and closes all open orders .. doesnt touch pending order so all good .. thanks a loads.. also, could you please explain me ..in above program it says slippage = 5 .. what it means for this script? how will that play out in when script closes an order? oh and also, is it a script or EA ? or how to differenciate between the two? [ HOW DO YOU GUYS LEARN SO MUCH OF STUFF >.< ]


Hello again,

As always, there's a good news and a bad news. Want the bad news first or the good news ?

Here it is and if I don't explain it well enough please let me know : For an EA to exit trades based on Account profit, it needs to know what the account equity was before the trade was placed, to have a starting point. Does it make any sense ?

If you don't have a starting point to compare with or if there's no comparison, EA will never close your trade as long as your account profit is negative or will close all trades immediately if your account profit is positive and above 100 or whatever the limit is.

Does that make any sense?

Slippage is the max amount of deviation from price that you allow the broker to place or close the order without re quoting if you open or close at market price.As the Bid and Ask changes continuously, by the time your order reaches the server if the value of price (bid or ask) is within slippage limits, the order will be processed, else it will be re quoted.

Yes, your code is an EA. A script usually runs only once, you get a new tick, execute the code and exit. An EA runs continuously as long as you let it run.

How do you tell them apart ? Sometimes it is difficult since they work in a similar manner . When a new script is created, looks like this :

//+------------------------------------------------------------------+
//|                                                   TestScript.mq4 |
//|                             Copyright 2014, 3D@tm Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, 3D@tm Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   
  }
//+------------------------------------------------------------------+

You can see it only has OnStart function and it says : Script program start function.

Back to your problem, if you run an EA that checks the account the account equity when no orders are placed and takes that as a reference point, it can then close all orders when the desired profit per account is reached.

The value of a pip (money per pip ) is not the same for all currencies .A pip in AUDUSD pair is not the same value as in GBPJPY pair.

Are you looking for specific symbols for this EA or no mater what symbol, just to close all orders when the profit per account is reached ?

Also, the stop loss should be account equity related or order/pair related ?

I know it sounds complicated but it isn't quite that complicated. Our computers are so dumb that unless you specify exactly what you want, they're lost.

Was this of any help to you ? Hope it was.

Cheers

 

Thrdel

I'm pretty sure that AccountProfit() returns the total profit for current open trades. Not obvious from the documentation though.

 
GumRai:

Thrdel

I'm pretty sure that AccountProfit() returns the total profit for current open trades. Not obvious from the documentation though.


Hmm ...

 AccountProfit() 

Instead I use ...

double AccProfits=AccProfits+OrderProfit();

Depends on what you want to achieve.

 
GumRai:

Thrdel

I'm pretty sure that AccountProfit() returns the total profit for current open trades. Not obvious from the documentation though.


Hi GumRai,

You're right, not very obvious from the documentation but I tested it and again, you're right, it is the sum of the profit/loss on all orders open.

Nice catch. Thanks.

Still can't use Account Profit if only want to manage manually opened orders and need to select from other orders that may be placed by other EA's.

I guess selecting by magic number = 0 should do the trick. And then sum up the profits as deysmacro suggested.

I guess I see it this way. What do you guys think?

//+------------------------------------------------------------------+
//|                                       CloseOrdersOnProfit_v1.mq4 |
//|                             Copyright 2014, 3D@tm Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, 3D@tm Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//---
#include <stdlib.mqh>
//---
#define RETRYCOUNT    10
#define RETRYDELAY    500
#define LONG          1
#define SHORT         -1
#define ALL           0
//---
extern int     Slippage=3;
input  double  ProfitTarget=100.0;
input  double  StopLossLimit=50.0;
input  bool    WriteScreenshots=true;
//---
double StartEquity=0;
int    myOrders;
//===================================================================
/*
This EA will manage manually placed orders and skip the orders that
have a magic number different from zero.
If the Profit target - the sum of profit/loss on all orders (except
orders placed by other EA's ) is reached, all those orders are
closed.
If the maximum amount of money allowed for a loss is reached, EA
will close all those orders and an alert will pop up.
*/
//===================================================================
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   if(Digits==3 || Digits==5) Slippage*=10;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- count orders manually placed (no magic number)
   CountMyOrders();
//--- reset account equity / take a reference point
   if(myOrders<1)
     {
      StartEquity=AccountEquity();
      //--- no orders detected, wait for orders to be placed
      return;
     }
//--- calculate profit
   double myProfit=CalculateProfit();
//--- if profit target reached, exit all
   if(myProfit>=ProfitTarget)
     {
      ExitAll(ALL);
      Alert("Orders closed due to profit target reached");
     }
//--- exit if stop limit reached
   if(StartEquity-AccountEquity()>=StopLossLimit)
     {
      ExitAll(ALL);
      Alert("Orders closed due to stop loss limit reached");
     }

   return;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CountMyOrders()
  {
   myOrders=0;
   for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES)==false)
         Print("Failed to select order, error : "+ErrorDescription(GetLastError()));
      //skip orders placed by other EA's
      if(OrderMagicNumber()>0)continue;
      if(OrderType()==OP_BUY || OrderType()==OP_SELL)
        {
         myOrders++;
        }
     }
   return(myOrders);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CalculateProfit()
  {
   double Profit=0;
   for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES)==false)
         Print("Failed to select order, error : "+ErrorDescription(GetLastError()));
      //skip orders placed by other EA's
      if(OrderMagicNumber()>0)continue;
      if(OrderType()==OP_BUY || OrderType()==OP_SELL)
        {
         Profit=Profit+OrderProfit();
        }
     }
   return(Profit);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ExitAll(int direction)
  {

   string total=IntegerToString(OrdersTotal(),0,0);

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      Comment(StringConcatenate("Closing trade #",(i+1)));
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
         Print("Failed to select order, error : "+ErrorDescription(GetLastError()));
      //skip orders placed by other EA's
      if(OrderMagicNumber()>0)continue;
      //---
      if(OrderType()==OP_BUY &&(direction==LONG ||  direction==ALL)) { Exit(OrderSymbol(),OrderTicket(),LONG,OrderLots(),Blue); }
      if(OrderType()==OP_SELL &&(direction==SHORT|| direction==ALL)) { Exit(OrderSymbol(),OrderTicket(),SHORT,OrderLots(),Red); }
     }
   Comment(StringConcatenate(total," trades closed."));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool Exit(string symb ,int ticket,int dir,double volume,color clr,int t=0)
  {
   int i=0,j=0,cmd=0;
   double prc=0,sl=0,tp=0,lots=0;
   string cmt;
   double bid=MarketInfo(symb,MODE_BID);
   double ask=MarketInfo(symb,MODE_ASK);
   bool closed;

   Print("Exit("+IntegerToString(dir,0,0)+","+DoubleToStr(volume,3)+","+IntegerToString(t,0,0)+")");

   for(i=0; i<RETRYCOUNT; i++) 
     {
      for(j=0;(j<50) && IsTradeContextBusy(); j++)
         Sleep(100);
      RefreshRates();

      if(dir==LONG) 
        {
         prc=bid;
        }
      if(dir==SHORT) 
        {
         prc=ask;
        }
      Print("Exit: prc="+DoubleToStr(prc,Digits));

      closed=OrderClose(ticket,volume,prc,Slippage,clr);
      if(closed)
        {
         Print("Trade closed");
         Screenshot("Exit");

         return (true);
        }

      Print("Exit: error \'"+ErrorDescription(GetLastError())+"\' when exiting with "+DoubleToStr(volume,3)+" @"+DoubleToStr(prc,Digits));
      Sleep(RETRYDELAY);
     }

   Print("Exit: can\'t enter after "+IntegerToString(RETRYCOUNT,0,0)+" retries");
   return (false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Screenshot(string moment_name)
  {
   if(WriteScreenshots)
      WindowScreenShot(WindowExpertName()+"_"+Symbol()+"_M"+IntegerToString(Period(),0,0)+"_"+
                       IntegerToString(Year(),0,0)+"-"+two_digits(Month())+"-"+two_digits(Day())+"_"+
                       two_digits(Hour())+"-"+two_digits(Minute())+"-"+two_digits(Seconds())+"_"+
                       moment_name+".gif",1024,768);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string two_digits(int i)
  {
   if(i<10)
      return ("0"+IntegerToString(i,0,0));
   else
      return (""+IntegerToString(i,0,0));
  }
//+------------------------------------------------------------------+
 
thrdel:


Hi GumRai,

You're right, not very obvious from the documentation but I tested it and again, you're right, it is the sum of the profit/loss on all orders open.

Nice catch. Thanks.

Still can't use Account Profit if only want to manage manually opened orders and need to select from other orders that may be placed by other EA's.

I guess selecting by magic number = 0 should do the trick. And then sum up the profits as deysmacro suggested.

I guess I see it this way. What do you guys think?


this fails .....

for lot of trades prc is not the right price

also don't do

  if(Digits==3 || Digits==5) Slippage*=10;

if you change several times your timeframe ......

 
deVries:


this fails .....

for lot of trades prc is not the right price

also don't do

if you change several times your timeframe ......


Yes deVries,

everything fails and I shouldn't do that if you say so, but since I really don't see much help in you answer .....

You do understand that the code isn't a commercial EA intended for sale to a fussy customer, right We are trying to work something out and if you don't want to help, you should at least leave it alone.

You really reckon that if I change the time frame several times..... what? The Slippage will be 3000000 ? Not in my MT4 apparently. And if you don't believe me, run a test yourself.

My test says that when you change the time frames, the EA goes trough deinit/init cycle and since the code mentioned is in the OnInit, Slippage will be right at 30 point every time.

As anyone can see, changing time frames will not bring the Slippage to a million, if that's what you're suggesting.

And no, it isn't a fake picture, it's real, you can check the time of changing each time frame.

Hope it helps.

 
thrdel:


Hello again,

As always, there's a good news and a bad news. Want the bad news first or the good news ?

Here it is and if I don't explain it well enough please let me know : For an EA to exit trades based on Account profit, it needs to know what the account equity was before the trade was placed, to have a starting point. Does it make any sense ?

If you don't have a starting point to compare with or if there's no comparison, EA will never close your trade as long as your account profit is negative or will close all trades immediately if your account profit is positive and above 100 or whatever the limit is.

Does that make any sense?

Slippage is the max amount of deviation from price that you allow the broker to place or close the order without re quoting if you open or close at market price.As the Bid and Ask changes continuously, by the time your order reaches the server if the value of price (bid or ask) is within slippage limits, the order will be processed, else it will be re quoted.

Yes, your code is an EA. A script usually runs only once, you get a new tick, execute the code and exit. An EA runs continuously as long as you let it run.

How do you tell them apart ? Sometimes it is difficult since they work in a similar manner . When a new script is created, looks like this :

You can see it only has OnStart function and it says : Script program start function.

Back to your problem, if you run an EA that checks the account the account equity when no orders are placed and takes that as a reference point, it can then close all orders when the desired profit per account is reached.

The value of a pip (money per pip ) is not the same for all currencies .A pip in AUDUSD pair is not the same value as in GBPJPY pair.

Are you looking for specific symbols for this EA or no mater what symbol, just to close all orders when the profit per account is reached ?

Also, the stop loss should be account equity related or order/pair related ?

I know it sounds complicated but it isn't quite that complicated. Our computers are so dumb that unless you specify exactly what you want, they're lost.

Was this of any help to you ? Hope it was.

Cheers


thrdel:


Hello again,

As always, there's a good news and a bad news. Want the bad news first or the good news ?

Here it is and if I don't explain it well enough please let me know : For an EA to exit trades based on Account profit, it needs to know what the account equity was before the trade was placed, to have a starting point. Does it make any sense ?

If you don't have a starting point to compare with or if there's no comparison, EA will never close your trade as long as your account profit is negative or will close all trades immediately if your account profit is positive and above 100 or whatever the limit is.

Does that make any sense?

Slippage is the max amount of deviation from price that you allow the broker to place or close the order without re quoting if you open or close at market price.As the Bid and Ask changes continuously, by the time your order reaches the server if the value of price (bid or ask) is within slippage limits, the order will be processed, else it will be re quoted.

Yes, your code is an EA. A script usually runs only once, you get a new tick, execute the code and exit. An EA runs continuously as long as you let it run.

How do you tell them apart ? Sometimes it is difficult since they work in a similar manner . When a new script is created, looks like this :

You can see it only has OnStart function and it says : Script program start function.

Back to your problem, if you run an EA that checks the account the account equity when no orders are placed and takes that as a reference point, it can then close all orders when the desired profit per account is reached.

The value of a pip (money per pip ) is not the same for all currencies .A pip in AUDUSD pair is not the same value as in GBPJPY pair.

Are you looking for specific symbols for this EA or no mater what symbol, just to close all orders when the profit per account is reached ?

Also, the stop loss should be account equity related or order/pair related ?

I know it sounds complicated but it isn't quite that complicated. Our computers are so dumb that unless you specify exactly what you want, they're lost.

Was this of any help to you ? Hope it was.

Cheers

Hello Again

Thanks for a very clear reply.. and thanks for being very helpful .Now I understand lot you taught..

"Are you looking for specific symbols for this EA or no mater what symbol, just to close all orders when the profit per account is reached ?" = second half with some conditions is the requirement

"just to close all orders when the profit per account is reached"

Ok, I trade only 2 pairs at a go .. First I open an order on one pair .. if it goes against me, I hedge it off with order on other pair ..

I am looking for EA which does following things:

1) Do NOTHING if there is NO order or only ONE order

2) It should CLOSE on X profit ONLY if there are TWO orders runnings, else goto 1)

3) While closing X, it should consider spread to be paid and consider X as NET profit [ this already has been explained above that AccountProfit() directly negates the spread you have to pay and shows you net and not gross profit .. correct if wrong ]

4) As you can see, SL and TP are no concerns, I dont use those so are not needed in the EA

Now, I totally am with you regarding free stuff, plus though I dont know coding, I think more than half of what I need is already there in above EA .. I just have to find something to change that it does what it does only when two orders are open .. I think it has to do something with that FOR loop in there .. or something like that .. =D [ Ok, now I am jealous that you guys can read code and I cannot!! .. now I feel like a dumb dude from 20th century ! ahahha in 21st century everyone must know coding >.< ]

I made a quick mind flowchart of my needs

EA starts ---> Does nothing till there is 0 or 1 order ----> Makes a 'call open sound' when 2nd order gets triggered ----> Closes both orders at X amount of pure profit [after considering spread] and makes a 'call close sound' ]

of course, call open and call close sound files can be any small wave files.. easily available on mt4 itself. .. I think these things can be achieved in the above EA that I had posted by changing a few things ! hehehe help me plz =D

Reason: