MQL4 및 MQL5에 대한 초보자 질문, 알고리즘 및 코드에 대한 도움말 및 토론 - 페이지 1561

 
MakarFX :
정리할 필요가 없다

내가 쓴대로 기호를 변경해야합니다

그래서 나는 변경했고 그는 평소처럼 최대 5개의 계약을 엽니다.

 
Eugen8519 :

그래서 나는 변경했고 그는 평소처럼 최대 5개의 계약을 엽니다.

OnTick() 코드 게시
 
MakarFX :

그런 다음 추가하여 해당 기간의 전체 이익을 계산합니다.

당신은 다시 이해하지 못했습니다. 그는 이익을 계산하고 싶다고 말했다. 그리고 이 함수는 마지막으로 마감된 주문의 손실을 계산하려고 시도했지만, 그것도 틀렸습니다. 그래서 그는 결국 모두를 혼란스럽게 만들었습니다.

 
MakarFX :
OnTick() 코드 게시
 void OnTick ()
  {  

   double close1 = iClose ( _Symbol ,Timeframe, 1 );

   datetime time_0= iTime ( 0 );
   if (TimeBar==time_0)
       return ;
   if (TimeBar== 0 )
     {
      TimeBar=time_0;
       return ;
     } //first program run
 
   double EMA0[],EMA_TREND[],WMA0[];
//---
   int start_pos= 1 ,count= 3 ;
   if (!iGetArray(handle_iMA_EMA, 0 ,start_pos,count,EMA0))
       return ;
   if (!iGetArray(handle_iMA_EMA_TREND, 0 ,start_pos,count,EMA_TREND))
       return ;
   if (!iGetArray(handle_iMA_WMA, 0 ,start_pos,count,WMA0))
       return ;
      
//---

   if (UseTimeLimit)
     {
       YesStop= true ;
       MqlDateTime str1;
       TimeToStruct ( TimeCurrent () , str1);
       if (str1.hour > startHour && str1.hour < stopHour)
          YesStop= false ;
     }
   if (YesStop== false )
   {
   
   ulong   m_ticket= 0 ;
   double SEma,LEma;
   
   SEma = iMAGet(handle_iMA_WMA, 0 );
   LEma = iMAGet(handle_iMA_EMA, 0 );
   
       static int isCrossed= 0 ;
   if (!Reverse)
      isCrossed=Crossed(LEma,SEma);
   else
      isCrossed=Crossed(SEma,LEma);
//---
   if (!RefreshRates())
       return ;
//---
   bool    condition1 = (close1 > EMA_TREND[ 0 ]);
   bool    condition2 = (isCrossed== 1 );

{  
   {  
         int pos_total= PositionsTotal ();
     {
       if (condition1 && condition2 && pos_total== 0 )
        {

       if (!RefreshRates())
         return ;
      TimeBar=time_0;
      my_TP = m_symbol.Ask() + ExtTakeProfit* Point ();
      my_SL = m_symbol.Ask() - ExtStopLoss* Point ();
      my_lot = Lots;
      OPENORDER( "Buy" );
      CLOSEORDER( "Sell" );
         }  
 }
   bool    condition3 = (close1 < EMA_TREND[ 0 ]);
   bool    condition4 = (isCrossed== 2 );
   
       if (condition3 && condition4 && pos_total== 0 )
         {
       if (!RefreshRates())
         return ;
      TimeBar=time_0;
      my_TP  = m_symbol.Bid() - ExtTakeProfit* Point ();
      my_SL  = m_symbol.Bid() + ExtStopLoss* Point ();

      my_lot= Lots;
      OPENORDER( "Sell" );
      CLOSEORDER( "Buy" );
         }
     } 
 } 
 
 
 if (UseTimeLimitClose)
     {
       MqlDateTime TimeNow;
       TimeToStruct ( TimeCurrent (),TimeNow);
       if   ( TimeNow.day_of_week >= closday  && TimeNow.hour >= Close_Hour && TimeNow.min >= Close_min ) 
       {
          CloseAllPositions();
       }     
   }
//---
   TrailingOrder();
   Trailing();
//---
   return ;
    }
 }

//--------------------------------------------------------------------
void CLOSEORDER( string ord)
  {
   for ( int i= PositionsTotal ()- 1 ; i>= 0 ; i--)   // returns the number of open positions
       if (m_position.SelectByIndex(i))
         if (m_position. Symbol ()== Symbol () && m_position.Magic()==m_magic)
           {
             if (m_position.PositionType()== POSITION_TYPE_BUY && ord== "Buy" )
               m_trade.PositionClose(m_position.Ticket());   // Close Buy
             if (m_position.PositionType()== POSITION_TYPE_SELL && ord== "Sell" )
               m_trade.PositionClose(m_position.Ticket()); // Close Sell
           }
  }
 

   
//--------------------------------------------------------------------   
void CloseAllPositions()
{
 
   for ( int i= PositionsTotal ()- 1 ; i>= 0 && ! IsStopped (); i--)
     {
       if (m_position.SelectByIndex(i))
        {
         //--- trading object
         m_trade.SetExpertMagicNumber(m_position.Magic());
         m_trade.SetTypeFillingBySymbol(m_position. Symbol ());
         //--- close positions
         if (m_trade.PositionClose(m_position.Ticket()) && (m_trade.ResultRetcode()== TRADE_RETCODE_DONE || m_trade.ResultRetcode()== TRADE_RETCODE_PLACED ))
             PrintFormat ( "Position #%I64u on %s to be closed" ,m_position.Ticket(),m_position. Symbol ());
         else
             PrintFormat ( "> Error closing position #%I64u on %s (%s)" ,m_position.Ticket(),m_position. Symbol (),m_trade.ResultComment());
        }
      }
   }
//--------------------------------------------------------------------

void OPENORDER( string ord)

  {
  
   double priceL=m_symbol.Ask();
   if (ord== "Sell" )      
         //--- check for free money
             if (m_account.FreeMarginCheck( Symbol (), ORDER_TYPE_BUY ,my_lot,priceL)< 0.0 )
               printf ( "We have no money. Free Margin = %f" ,m_account.FreeMargin());
             else
       if (!m_trade.Sell(my_lot, Symbol (),m_symbol.Bid(),my_SL,my_TP, "" ))
         Print ( "BUY_STOP -> false. Result Retcode: " ,m_trade.ResultRetcode(),
               ", description of Retcode: " ,m_trade.ResultRetcodeDescription(),
               ", ticket of order: " ,m_trade.ResultOrder());                     // Если sell, то не открываемся
     double priceS=m_symbol.Bid();
   if (ord== "Buy" )
         //--- check for free money
             if (m_account.FreeMarginCheck( Symbol (), ORDER_TYPE_SELL ,my_lot,priceS)< 0.0 )
               printf ( "We have no money. Free Margin = %f" ,m_account.FreeMargin());
             else
       if (!m_trade.Buy(my_lot, Symbol (),m_symbol.Ask(),my_SL,my_TP, "" ))
 
         Print ( "Buy -> false. Result Retcode: " ,m_trade.ResultRetcode(),
               ", description of result: " ,m_trade.ResultRetcodeDescription(),
               ", ticket of deal: " ,m_trade.ResultDeal());
   return ;
 }
   double iMAGet( const int handle, const int index)
  {
   double MA[];
   ArraySetAsSeries (MA, true );
//--- reset error code
   ResetLastError ();
//--- fill a part of the iMABuffer array with values from the indicator buffer that has 0 index
   if ( CopyBuffer (handle, 0 , 0 ,index+ 1 ,MA)< 0 )
     {
       //--- if the copying fails, tell the error code
       PrintFormat ( "Failed to copy data from the iMA indicator, error code %d" , GetLastError ());
       //--- quit with zero result - it means that the indicator is considered as not calculated
       return ( 0.0 );
     }
   return (MA[index]);
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
       return ( false );
//--- protection against the return value of "zero"
   if (m_symbol.Ask()== 0 || m_symbol.Bid()== 0 )
       return ( false );
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Get Time for specified bar index                                 |
//+------------------------------------------------------------------+
datetime iTime ( const int index, string symbol= NULL , ENUM_TIMEFRAMES timeframe= PERIOD_CURRENT )
  {
   if (symbol== NULL )
      symbol= Symbol ();
   if (timeframe== 0 )
      timeframe= Period ();
   datetime Time[];
   datetime time= 0 ;
   ArraySetAsSeries (Time, true );
   int copied= CopyTime (symbol,timeframe,index, 1 ,Time);
   if (copied> 0 )
      time=Time[ 0 ];
   return (time);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
bool iGetArray( const int handle, const int buffer, const int start_pos,
               const int count, double &arr_buffer[])
  {
   bool result= true ;
   if (! ArrayIsDynamic (arr_buffer))
     {
       PrintFormat ( "ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!" , __FILE__ , __FUNCTION__ );
       return ( false );
     }
   ArrayFree (arr_buffer);
//--- reset error code
   ResetLastError ();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied= CopyBuffer (handle,buffer,start_pos,count,arr_buffer);
   if (copied!=count)
     {
       //--- if the copying fails, tell the error code
       PrintFormat ( "ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d" ,
                   __FILE__ , __FUNCTION__ ,count,copied, GetLastError ());
       //--- quit with zero result - it means that the indicator is considered as not calculated
       return ( false );
     }
   return (result);
 
 
}
void TrailingOrder()

  {
   int pos_total= PositionsTotal ();

   if (InpTrailingOrderLimit== 0 )
         return ;
   for ( int i= PositionsTotal ()- 1 ;i>= 0 ;i--) // returns the number of open positions
       if (m_position.SelectByIndex(i))
         if (m_position. Symbol ()==m_symbol.Name() && m_position.Magic()==m_magic)
           {
             if (m_position.PositionType()== POSITION_TYPE_BUY )
              {
               if (m_position.PriceCurrent()-m_position.PriceOpen()>ExtTrailingOrderLimit+ExtTrailingOrderStep)
                   if (m_position.StopLoss()<m_position.PriceCurrent()-(ExtTrailingOrderLimit+ExtTrailingOrderStep))
                       OPENORDER( "Buy" );
 
                  
              }
             else
              {
               if (m_position.PriceOpen()-m_position.PriceCurrent()>ExtTrailingOrderLimit+ExtTrailingOrderStep)
                   if ((m_position.StopLoss()>(m_position.PriceCurrent()+(ExtTrailingOrderLimit+ExtTrailingOrderStep))))
                        OPENORDER( "Sell" );
 
              }
           }
    }      
 void Trailing()
  {
   if (InpTStop== 0 )
       return ;
         if (m_position. Symbol ()==m_symbol.Name() && m_position.Magic()==m_magic)
           {
             if (m_position.PositionType()== POSITION_TYPE_BUY )
              {
               if (m_position.PriceCurrent()-m_position.PriceOpen()>ExtTStop+ExtTStep)
                   if (m_position.StopLoss()<m_position.PriceCurrent()-(ExtTStop+ExtTStep))
                    {
                     if (!m_trade.PositionModify(m_position.Ticket(),
                        m_symbol.NormalizePrice(m_position.PriceCurrent()-ExtTStepShift),
                        m_position.TakeProfit()))
                         Print ( "Modify " ,m_position.Ticket(),
                               " Position -> false. Result Retcode: " ,m_trade.ResultRetcode(),
                               ", description of result: " ,m_trade.ResultRetcodeDescription());
                    }
              }
             else
              {
               if (m_position.PriceOpen()-m_position.PriceCurrent()>ExtTStop+ExtTStep)
                   if ((m_position.StopLoss()>(m_position.PriceCurrent()+(ExtTStop+ExtTStep))) ||
                     (m_position.StopLoss()== 0 ))
                    {
                     if (!m_trade.PositionModify(m_position.Ticket(),
                        m_symbol.NormalizePrice(m_position.PriceCurrent()+ExtTStepShift),
                        m_position.TakeProfit()))
                         Print ( "Modify " ,m_position.Ticket(),
                               " Position -> false. Result Retcode: " ,m_trade.ResultRetcode(),
                               ", description of result: " ,m_trade.ResultRetcodeDescription());
                   }
              }
         }
   }
//+------------------------------------------------------------------+


현재 pos_total<=2 제거됨
 
Eugen8519 :

라인을 찾아

OPENORDER( "Buy" );

로 대체

   if ( PositionsTotal ()<= 2 )
     {
      OPENORDER( "Buy" );
     }

라인을 찾아

OPENORDER( "Sell" );

로 대체

   if ( PositionsTotal ()<= 2 )
     {
      OPENORDER( "Sell" );
     }
 
Mihail Matkovskij :

당신은 다시 이해하지 못했습니다. 그는 이익을 계산하고 싶다고 말했다. 그리고 이 함수는 마지막으로 마감된 주문의 손실을 계산하려고 시도했지만, 그것도 틀렸습니다. 그래서 그는 결국 모두를 혼란스럽게 만들었습니다.

당신은 이익이 음수일 수 있다고 말했고 그는 거래에서 양수든 음수든 완전한 이익을 얻고 싶어했습니다.
 
MakarFX :

라인을 찾아

로 대체

라인을 찾아

로 대체


   if (InpTrailingOrderLimit== 0 )
         return ;
   for ( int i= PositionsTotal ()- 1 ;i>= 0 ;i--) // returns the number of open positions
       if (m_position.SelectByIndex(i))
         if (m_position. Symbol ()==m_symbol.Name() && m_position.Magic()==m_magic)
           {
             if (m_position.PositionType()== POSITION_TYPE_BUY )
              {
               if (m_position.PriceCurrent()-m_position.PriceOpen()>ExtTrailingOrderLimit+ExtTrailingOrderStep)
                   if (m_position.StopLoss()<m_position.PriceCurrent()-(ExtTrailingOrderLimit+ExtTrailingOrderStep))
                     if ( PositionsTotal ()<= 2 )
                          {
                        OPENORDER( "Buy" );
                          }
 
                  
              }
             else
              {
               if (m_position.PriceOpen()-m_position.PriceCurrent()>ExtTrailingOrderLimit+ExtTrailingOrderStep)
                   if ((m_position.StopLoss()>(m_position.PriceCurrent()+(ExtTrailingOrderLimit+ExtTrailingOrderStep))))
                 if ( PositionsTotal ()<= 2 )
                           {
                            OPENORDER( "Sell" );
                            }


이렇게 삽입, 어쨌든 두 계약에 무제한

 
MakarFX :
당신은 이익이 음수일 수 있다고 말했고 그는 거래에서 양수든 음수든 완전한 이익을 얻고 싶어했습니다.

이것은 이익이 양수인 경우에만 합산된다는 것을 의미합니다. 음수이면 이미 손실입니다. 총 이익을 찾아야 하는 경우 음수를 포함하여 모든 이익이 요약됩니다. 그리고 그의 기능은 마지막 주문의 이익을 찾으려고 시도했지만 잘못했으며 마지막 손실이라고 불렀습니다. 그들이 이해하지 못했습니까? 글쎄, 크리스마스 트리 스틱 ... 나는 힘이 없다 ...

 
Eugen8519 :



이렇게 삽입, 어쨌든 두 계약에 무제한

void OnTick에 없습니다.

 
MakarFX :

그런 다음 추가하여 해당 기간의 전체 이익을 계산합니다.

“왜 이익을 위해 수수료가 있는 스왑을 추가합니까?
OrderProfit()

부정적일 수...

그리고 적격 주문을 1개 또는 몇 개만 처리하고 전부는 처리하지 않는 경우 총 이익은 얼마입니까?"


뭔가 서로 정말 혼란스러웠다. 주석의 모든 것이 맞았습니다. 음수의 덧셈과 뺄셈에 관한 것이 아님)

대답도 싫어. 봐봐, 거기 있어)