Spread trading in Meta Trader - page 142

 

Friends !!!! I've decided to give myself another bump and write an EA based on limit orders and I will be glad for any help. I have already opened Limit orders based on Kim's functions. I am currently trying to get the average and deviations based on tick statistics(https://www.mql5.com/ru/forum/125272)(since I think they are more reliable) to open positions. We will have to implement a module to move limit orders behind the price and a module to close positions when the profit reaches a certain point.

 
Scorp1978 >>:

...... Надо будет реализовать модуль передвижки лимит ордера за ценой и модуль закрытия позиций при достижения профита определенного.

Here's the code to move the orders around. Beer's on you !

extern bool    Modify =True;
extern int     DistanceSet=14;//в пунктах
//-----------------------------------

if (Modify == true) {//если выключатель модификации включен
//если есть отложенный ордер и нет откр. одноименных позиций и
// расстояние от текущей цены превышает величину DistanceSet - модернизируем
// - т.е. подтягиваем к текущей цене
if(NumberOfOrders(NULL,OP_BUYLIMIT,Magic)>0 &&  NumberOfPositions(NULL,OP_BUY,Magic)<1){
  if( ExistOPNearMarket(NULL,OP_BUYLIMIT,Magic,DistanceSet)==0 ) { 
    for (int isl_= OrdersTotal()-1; isl_>=0; isl_-- )                  {
    if(OrderSelect(isl_,SELECT_BY_POS,MODE_TRADES))                 {
     if(OrderSymbol()==Symbol() )                                   {
      if(OrderType()==OP_BUYLIMIT && OrderMagicNumber()==Magic)      { 
      double pAsk=Ask-DistanceSet*Point;            
      if (sl!=0) double ldStop=pAsk-sl*Point;
      if (tp!=0) double ldTake=pAsk+tp*Point;         
     OrderModify(OrderTicket(), pAsk,ldStop,ldTake, 0, DarkGreen);
      Print("Modify OP_BUYLIMIT ");  Sleep(500);  RefreshRates(); }
      }}}}}
if(NumberOfOrders(NULL,OP_SELLLIMIT,Magic)>0 && NumberOfPositions(NULL,OP_SELL,Magic)<1){      
  if( ExistOPNearMarket(NULL,OP_SELLLIMIT,Magic,DistanceSet)==0 ) { 
   for (int isl= OrdersTotal()-1; isl>=0; isl-- )                  {
    if(OrderSelect(isl,SELECT_BY_POS,MODE_TRADES))                 {
     if(OrderSymbol()==Symbol() )                                   {
      if(OrderType()==OP_SELLLIMIT && OrderMagicNumber()==Magic)      { 
       double pBid=Bid+DistanceSet*Point;  
       if (sl!=0) double ldStop_=pBid+sl*Point;
       if (tp!=0) double ldTake_=pBid-tp*Point; 
     OrderModify(OrderTicket(), Bid+DistanceSet*Point,ldStop_,ldTake_, 0, DarkGreen);
      Print("Modify OP_SELLLIMIT");  Sleep(500);  RefreshRates(); }
      }}}}}            
}//выключатель модификации 
Where, - Function ExistOPNearMarket()
//This function returns a flag for the existence of an order or a position near the market
//(at a specified distance in pips from the market). A more accurate selection of orders or positions to be checked
Orders or positions to be //checked are set by external parameters:
//sy - Name of the instrument. If this parameter is set, the function will verify
check the //orders or positions of only the specified symbol. "" or NULL means
//current symbol.
//op - Trade operation, order or position type. Valid values: OP_BUY,
// OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, OP_SELLSTOP or -1.
//The default value of -1 means any trade operation.
//mn - Order or position identifier (MagicNumber). Default value -1
// - any identifier.
//ds - Market distance in pips. The default value is 1000000.
//+----------------------------------------------------------------------------+
//| Автор : Ким Игорь                                                                |
//+----------------------------------------------------------------------------+
//| Версия : 19.02.2008 |
//| Описание : Возвращает флаг существования позиции или ордера около рынка |
//+----------------------------------------------------------------------------+
//| Параметры: |
//| sy - наименование инструмента ("" или NULL - текущий символ) |
//| op - торговая операция ( -1 - любая операция) |
//| mn - MagicNumber ( -1 - любой магик) |
//| ds - расстояние в пунктах от рынка ( 1000000 - по умолчанию) |
//+----------------------------------------------------------------------------+
bool ExistOPNearMarket(string sy="", int op=-1, int mn=-1, int ds=1000000) {
  int i, k=OrdersTotal(), ot;
  if (sy=="" || sy=="0") sy=Symbol();
  double p=MarketInfo(sy, MODE_POINT);
  if (p==0) if (StringFind(sy, "JPY")<0) p=0.0001; else p=0.01;
  for (i=0; i<k; i++) {
  if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
  ot=OrderType();
  if ((OrderSymbol()==sy) && (op<0 || ot==op)) {
  if (mn<0 || OrderMagicNumber()==mn) {
  if (ot==OP_BUY || ot==OP_BUYLIMIT || ot==OP_BUYSTOP) {
  if (MathAbs(MarketInfo(sy, MODE_ASK)-OrderOpenPrice())<ds*p) return(True);
  }
  if (ot==OP_SELL || ot==OP_SELLLIMIT || ot==OP_SELLSTOP) {
  if (MathAbs(OrderOpenPrice()-MarketInfo(sy, MODE_BID))<ds*p) return(True);
  }}}}} return(False); }

And NumberOfOrders() function -
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Возвращает количество ордеров.                                 |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любой ордер)                    |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int NumberOfOrders(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), ko=0, ot;

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (ot>1 && ot<6) {
        if ((OrderSymbol()==sy || sy=="") && (op<0 || ot==op)) {
          if (mn<0 || OrderMagicNumber()==mn) ko++;
        }}}}  return(ko);}                        
 
rid


thanks a lot, crunch gave me the function to calculate the average of ticks with any period I promised him a beer too, I'll have to fill up a crate at once :)))) I wish I wasn't too drunk with joy myself!!!!!

 
Received a letter today in the mt4 B mail.
//-----------------------------
"Dear Clients, please note that starting from April 14, 2010, the action corresponding to clause 1.3.6. of the Appendix, Agreement BT-08 will take effect.
1.3.6 Balance Sheet Fixing.
1.3.6.1 The process of fixing of the trade balance shall be performed on a daily basis, prior to the process of swap accrual.
This procedure consists in automatic calculation of financial result of all performed trades and comparing it with the current balance of the trading account. If there is a discrepancy, the trading account balance will be corrected by the amount of the discrepancy.
Starting from this moment, the procedure of fixing the balance will be performed on a daily basis.
In caseof discrepancies in the financial result on the trading account after this procedure, you can contact the technical support department ....."
//------------------------------------------------
I can't figure out what the hell this is?
What is the difference in amounts? Where can it come from in theory?
What are we talking about here?
И - ".... the balance of the trading account will be adjusted" - how?

 

I am afraid to be wrong, but clause 1.3.6.1 of the BT-08 agreement, gives the company another chance to nibble on customers.
Where can discrepancies theoretically come from ?
There are two possibilities.
The first one is that if your orders have been executed at non-market prices (you know, spikes and other failures) - the company will decide the fate of such otder and determine what is "non-market price". But this does not happen very often and is not that bad.
The second option is more important for the trader. Let's imagine that at the time of fixing, the company will widen the trading spreads. It means that on all your open positions the total profit will decrease, and this difference will be deducted from the balance. This procedure will be done by the company at the end of each trading day, and it will be like a hidden swap... No devil, no devil can stop the company from doing that... she's the CFD hostess...

Of course, everyone would like to believe in the integrity of the company and that it will not cheat like this... time will tell..., but one must find somewhere to raise funds for overseas litigation and expensive lawyers...

 
GEFEL >>:

.....
Второй вариант более важен для трейдера. Представим себе, что на момент фиксинга, компания будет раздвигать торговые спреды. Это значит, что по всем Вашим открытым позициям суммарный профит будет уменьшаться, и эта разница будет списываться с баланса... Такую процедуру компания будет проводить в конце каждого торгового дня, - и это будет похоже на скрытое свопирование........

I'm thinking.....
Spreads do widen quite a bit every day at the sessional daily close (for those instruments where there is a break between the daily sessions, i.e. almost all commodities and futures - for our trading methodology).
It is not quite clear. In this situation, equity (funds) would decrease temporarily, but not the balance.
The positions remain open and the balance cannot change in any way.
And if this "widened" spread (when a new session is opened) is written off the balance, it is difficult to comprehend.
I have to save a DETAILED STATEMENT every evening, and scrupulously compare it with a "new balance" in the morning ...
Apparently so.

 
A friend has put the question to tech support.
Will get an answer.
http://www.procapital.ru/showthread.php?p=649145#post649145
 
rid писал(а) >>
An acquaintance has put the question to tech support.
Will get an answer.
>> http://www.procapital.ru/showthread.php?p=649145#post649145


I also read the reply from tech support and understand that nothing will happen (hopefully)

 

Balance = funds + total profits on open positions...

 

And this phrase in the answer, highlighted in red, doesn't bother you ... Once again, closed trades will not be affected by this, all their figures will remain as they are. Only the final account balance is checked.
Of course, no one was going to fix the already closed positions. This would be a burglary. But they could get into open ones...
I do not have a real in B ... and I kind of do not care, but you really advise to arrange a reconciliation of the evening and morning balance ...

Reason: