로봇 만들기 - 페이지 4

 
글쎄요, 제가 쓰고 썼는데 정확히 말 안 한 줄 알았어요. 나는 항상 생각의 공식화에 문제가 있습니다. 열 번째 변화부터 단어처럼 알아들을 수 있습니다.
 
Роман Жилин :

오오오오오오오오오오오오오오오오오오오오오오오오오오오오오오오오 감사합니다.

막 출장을 떠나서 저에게 주어진 자료들을 더 깊이 파고들 생각도 하고 있는데 코딩은 어떨지... 시트로도 가능하고 좋은 운동이 될 것 같아요...


존경합니다, 로만

이것은 프로그램 코드의 바다에 있는 모래알과 같이 당신이 알아야 할 아주 작은 부분입니다. 그러나 이것으로 충분하지 않습니다. 또한 무엇을 신청해야 하는지, 어디에 신청해야 하는지, 언제 신청해야 하는지 이해해야 합니다!

" 로봇 만들기 "라는 주제의 제목부터 계속 진행하면 우선 손익분기점 (수익성, 무엇이라고 부르든 상관없음) 거래 전략이 필요하며 그런 다음 MQL5 프로그래밍 언어를 공부해야 합니다. .

그건 그렇고, MT5 터미널의 MetaEditor에는 프로그래밍 언어를 몰라도 쉽게 사용할 수 있는 MQL5 마법사 가 있습니다. 이 마법사를 사용하면 인기 있는 지표를 기반으로 생성된 Trading Signals Modules 를 사용하여 기성품 고문의 코드를 쉽게 얻을 수 있습니다. MQL5 Wizard의 도움으로 , 무릎 위에서 말하는 것처럼 신속하게 Expert Advisor를 구성하고 전략이 지표만을 기반으로 하는 경우 전략을 테스트할 수 있습니다. 다음은 MQL5 마법사를 사용하여 거래 로봇을 만드는 방법에 대한 기사 링크입니다. https://www.mql5.com/en/articles/171

안부 인사를 전합니다. 블라디미르.

Мастер MQL5: Создание эксперта без программирования
Мастер MQL5: Создание эксперта без программирования
  • www.mql5.com
При создании автоматических торговых систем возникает необходимость написания алгоритмов анализа рыночной ситуации и генерации торговых сигналов, алгоритмов сопровождения открытых позиций, систем управления капиталом и контроля риска торговли. После того как код модулей написан самой сложной задачей является компоновка всех частей и отладка...
 
MrBrooklin :

57 조금. 그리고 경로 에 대한 귀하의 질문에 대한 답변 이미 알고 있습니다.

로만 지린 :

아니요, 프리랜서에는 필요에 따라 스스로 개발할 수 있는 아이디어를 컴파일하는 프로세스가 없습니다. 그리고 제 3자 프로그래머가 아닌 저 자신만이 제 실수에 대한 책임이 있습니다. 그러니 공부하고, 공부하고, 코딩하고, 비틀거리고, 전략을 개선하고, 다시 공부하십시오."

안부 인사를 전합니다. 블라디미르.

좋은 선택, 감사합니다.

그것은 나에게 레닌의 유언을 상기시켰습니다.

문제 중 하나는 시간이 없다는 것입니다. 기가바이트의 문학을 삽질하는 데는 많은 시간이 걸리며, 다른 하나는 대부분의 경우 고문을 쓰는 것이 말도 안되는 것으로 판명되는 것과 비교하여 주요 전략으로 밝혀졌습니다. 어떤 종류의 고문이 필요한지 명확하게 파악하려면 먼저 작업을 시작해야 합니다.

 

포지션을 닫기 위한 2개의 버튼을 더 추가했습니다.

 //+------------------------------------------------------------------+
//|                                                         0002.mq5 |
//|                        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"
#define   InpMagic   182979245
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position; // trade position object
CTrade         m_trade;     // trading object
CSymbolInfo    m_symbol;   // symbol info object
//---
input double InpLots          = 0.01 ; // Lots
//---
double m_adjusted_point;   // point value adjusted for 3 or 5 points
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//---
   if (!m_symbol.Name( Symbol ())) // sets symbol name
       return ( INIT_FAILED );;
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
//--- tuning for 3 or 5 digits
   int digits_adjust= 1 ;
   if (m_symbol. Digits ()== 3 || m_symbol. Digits ()== 5 )
      digits_adjust= 10 ;
   m_adjusted_point=m_symbol. Point ()*digits_adjust;
//---
   m_trade.SetDeviationInPoints( 3 *digits_adjust);
   if (!m_position.Select( Symbol ()))
     {
      CheckObject();
      CheckObjectClose();
     }
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
   if ( ObjectFind ( 0 , "BUY" )== 0 )
     {
       ObjectDelete ( 0 , "BUY" );
     }
   if ( ObjectFind ( 0 , "SELL" )== 0 )
     {
       ObjectDelete ( 0 , "SELL" );
     }
//---
   if ( ObjectFind ( 0 , "Close BUY" )== 0 )
     {
       ObjectDelete ( 0 , "Close BUY" );
     }
   if ( ObjectFind ( 0 , "Close SELL" )== 0 )
     {
       ObjectDelete ( 0 , "Close SELL" );
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   CheckButon();
   CheckButonClose();
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButon( void )
  {
//---
   bool res= false ;
     {
       if ( ObjectGetInteger ( 0 , "BUY" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "BUY" , OBJPROP_STATE , 0 );
         double price=m_symbol.Ask();
           {
             //--- open position
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
        }
       if ( ObjectGetInteger ( 0 , "SELL" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "SELL" , OBJPROP_STATE , 0 );
         double price0=m_symbol.Bid();
           {
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price0, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price0, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
        }
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObject( void )
  {
//---
   bool res= false ;
     {
       ObjectCreate ( 0 , "BUY" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 102 );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_YDISTANCE , 37 );
       ObjectSetString ( 0 , "BUY" , OBJPROP_TEXT , "BUY" );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_BGCOLOR , clrMediumSeaGreen );
       ObjectCreate ( 0 , "SELL" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 50 );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_YDISTANCE , 37 );
       ObjectSetString ( 0 , "SELL" , OBJPROP_TEXT , "SELL" );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_BGCOLOR , clrDarkOrange );
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButonClose( void )
  {
//---
   bool res= false ;
   double level;
     {
       if ( ObjectGetInteger ( 0 , "Close BUY" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_STATE , 0 );
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_BUY ,level);
         PlaySound ( "ok.wav" );
        }
       if ( ObjectGetInteger ( 0 , "Close SELL" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_STATE , 0 );
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_SELL ,level);
         PlaySound ( "ok.wav" );
        }
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObjectClose( void )
  {
//---
   bool res= false ;
     {
       ObjectCreate ( 0 , "Close BUY" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 102 );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_YDISTANCE , 57 );
       ObjectSetString ( 0 , "Close BUY" , OBJPROP_TEXT , "Close BUY" );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_BGCOLOR , clrTomato );
       ObjectCreate ( 0 , "Close SELL" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 50 );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_YDISTANCE , 57 );
       ObjectSetString ( 0 , "Close SELL" , OBJPROP_TEXT , "Close SELL" );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_BGCOLOR , clrFireBrick );
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
bool FreezeStopsLevels( double &level)
  {
//--- check Freeze and Stops levels
   if (!RefreshRates() || !m_symbol.Refresh())
       return ( false );
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol. Point ();
   if (freeze_level== 0.0 )
      freeze_level=(m_symbol.Ask()-m_symbol.Bid())* 3.0 ;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol. Point ();
   if (stop_level== 0.0 )
      stop_level=(m_symbol.Ask()-m_symbol.Bid())* 3.0 ;
   if (freeze_level<= 0.0 || stop_level<= 0.0 )
       return ( false );
   level=(freeze_level>stop_level)?freeze_level:stop_level;
   double spread=m_symbol.Spread()*m_adjusted_point;
   level=(level>spread)?level:spread;
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions( const ENUM_POSITION_TYPE pos_type, const double level)
  {
   for ( int i= PositionsTotal ()- 1 ; i>= 0 ; i--) // returns the number of current positions
       if (m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if (m_position. Symbol ()==m_symbol.Name() /* && m_position.Magic()==InpMagic*/ )
             if (m_position.PositionType()==pos_type)
              {
               if (m_position.PositionType()== POSITION_TYPE_BUY )
                 {
                   bool take_profit_level=(m_position.TakeProfit()!= 0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=level) || m_position.TakeProfit()== 0.0 ;
                   bool stop_loss_level=(m_position.StopLoss()!= 0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=level) || m_position.StopLoss()== 0.0 ;
                   if (take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               if (m_position.PositionType()== POSITION_TYPE_SELL )
                 {
                   bool take_profit_level=(m_position.TakeProfit()!= 0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=level) || m_position.TakeProfit()== 0.0 ;
                   bool stop_loss_level=(m_position.StopLoss()!= 0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=level) || m_position.StopLoss()== 0.0 ;
                   if (take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               PlaySound ( "ok.wav" );
              }
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
     {
       Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " , "RefreshRates error" );
       return ( false );
     }
//--- protection against the return value of "zero"
   if (m_symbol.Ask()== 0 || m_symbol.Bid()== 0 )
     {
       Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " , "Ask == 0.0 OR Bid == 0.0" );
       return ( false );
     }
//---
   return ( true );
  }
//+------------------------------------------------------------------+
파일:
0002.mq5  11 kb
 
MrBrooklin :

.. 여전히 " Returns "라는 단어로 시작하는 지속적으로 발생하는 구의 의미를 이해하지 못합니다.

누가, 누구에게, 어디로, 어디로, 그는 왜 돌아오는가 ? 아직 도무지 알 수가 없네요...

내가 설명할 수 있을지도 몰라.

현재 화면에서 변동하는 상품(기호, 예를 들어 EUR/USD)의 시세가 있고 프로그램/어드바이저/로봇이 터미널에서 실행 중이라고 가정해 보겠습니다. 로봇은 당신이 집어넣은 코드를 실행합니다. 그리고 이 코드에는 다음과 같은 줄이 있습니다.

           ... 
 
           if ( OrderSelect (i,SELECT_BY_POS,MODE_TRADES)== false ) break ;

           double OpenPrice = OrderOpenPrice(); 

	   ...
"orderSelect"는 거래 기능이며 추가 작업을 위해 이미 열린 주문을 선택합니다.
//이 예에서 주문을 선택할 수 없는 경우(...==false), "if" 함수의 추가 실행은 "break" 명령에 의해 중단됩니다.

더 나아가. 주문은 OrderSelect 거래 기능 에 의해 선택됩니다. 이제 우리는 특정 명령으로 그와 함께 일하고 있습니다. 이해를 쉽게 하기 위해 두 개의 주문만 열려 있다고 가정해 보겠습니다.

다음으로 코드에서 OpenPrice 변수를 입력합니다.   [이중 유형] 우리가 선택한 주문이 열린 가격의 값을 할당합니다(코드 섹션 OpenPrice=OrderOpenPrice(); ).

여기에서는 매개변수를 반환하는 것이 무엇을 의미하는지 설명합니다. OrderOpenPrice 거래 함수는 상품의 현재 가격 값을 반환합니다 . 즉, 프로그램이 현재 가격에 대한 요청으로 서버에 접속한 후 이 가격 값을 사용자에게 반환 하고 이 값을 변수에 할당했습니다.

 

MACD 표시기 추가

 //+------------------------------------------------------------------+
//|                                                         0003.mq5 |
//|                        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"
#define   InpMagic   182979245
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position; // trade position object
CTrade         m_trade;     // trading object
CSymbolInfo    m_symbol;   // symbol info object
//---
input double InpLots= 0.01 ; // Lots
//---
double    m_adjusted_point; // point value adjusted for 3 or 5 points
int       handle_iCustom;   // variable for storing the handle of the iStochastic indicator
datetime ExtPrevBars= 0 ;     // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//---
   if (!m_symbol.Name( Symbol ())) // sets symbol name
       return ( INIT_FAILED );;
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
//--- tuning for 3 or 5 digits
   int digits_adjust= 1 ;
   if (m_symbol. Digits ()== 3 || m_symbol. Digits ()== 5 )
      digits_adjust= 10 ;
   m_adjusted_point=m_symbol. Point ()*digits_adjust;
//---
   m_trade.SetDeviationInPoints( 3 *digits_adjust);
   if (!m_position.Select( Symbol ()))
     {
      CheckObject();
      CheckObjectClose();
     }
   handle_iCustom= iMACD (m_symbol.Name(), Period (), 12 , 26 , 9 , PRICE_CLOSE );
//--- if the handle is not created
   if (handle_iCustom== INVALID_HANDLE )
     {
       //--- tell about the failure and output the error code
       PrintFormat ( "Failed to create handle of the handle_iCustom indicator for the symbol %s/%s, error code %d" ,
                  m_symbol.Name(),
                   EnumToString ( Period ()),
                   GetLastError ());
       //--- the indicator is stopped early
       return ( INIT_FAILED );
     }
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
   if ( ObjectFind ( 0 , "BUY" )== 0 )
     {
       ObjectDelete ( 0 , "BUY" );
     }
   if ( ObjectFind ( 0 , "SELL" )== 0 )
     {
       ObjectDelete ( 0 , "SELL" );
     }
//---
   if ( ObjectFind ( 0 , "Close BUY" )== 0 )
     {
       ObjectDelete ( 0 , "Close BUY" );
     }
   if ( ObjectFind ( 0 , "Close SELL" )== 0 )
     {
       ObjectDelete ( 0 , "Close SELL" );
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   CheckButon();
   CheckButonClose();
   if (SearchTradingSignals())
     {
       return ;
     }
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButon( void )
  {
//---
   bool res= false ;
     {
       if ( ObjectGetInteger ( 0 , "BUY" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "BUY" , OBJPROP_STATE , 0 );
         double price=m_symbol.Ask();
           {
             //--- open position
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
        }
       if ( ObjectGetInteger ( 0 , "SELL" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "SELL" , OBJPROP_STATE , 0 );
         double price0=m_symbol.Bid();
           {
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price0, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price0, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
        }
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObject( void )
  {
//---
   bool res= false ;
     {
       ObjectCreate ( 0 , "BUY" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 102 );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_YDISTANCE , 37 );
       ObjectSetString ( 0 , "BUY" , OBJPROP_TEXT , "BUY" );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_BGCOLOR , clrMediumSeaGreen );
       ObjectCreate ( 0 , "SELL" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 50 );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_YDISTANCE , 37 );
       ObjectSetString ( 0 , "SELL" , OBJPROP_TEXT , "SELL" );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_BGCOLOR , clrDarkOrange );
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButonClose( void )
  {
//---
   bool res= false ;
   double level;
     {
       if ( ObjectGetInteger ( 0 , "Close BUY" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_STATE , 0 );
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_BUY ,level);
         PlaySound ( "ok.wav" );
        }
       if ( ObjectGetInteger ( 0 , "Close SELL" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_STATE , 0 );
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_SELL ,level);
         PlaySound ( "ok.wav" );
        }
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObjectClose( void )
  {
//---
   bool res= false ;
     {
       ObjectCreate ( 0 , "Close BUY" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 102 );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_YDISTANCE , 57 );
       ObjectSetString ( 0 , "Close BUY" , OBJPROP_TEXT , "Close BUY" );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_BGCOLOR , clrTomato );
       ObjectCreate ( 0 , "Close SELL" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 50 );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_YDISTANCE , 57 );
       ObjectSetString ( 0 , "Close SELL" , OBJPROP_TEXT , "Close SELL" );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_BGCOLOR , clrFireBrick );
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
bool FreezeStopsLevels( double &level)
  {
//--- check Freeze and Stops levels
   if (!RefreshRates() || !m_symbol.Refresh())
       return ( false );
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol. Point ();
   if (freeze_level== 0.0 )
      freeze_level=(m_symbol.Ask()-m_symbol.Bid())* 3.0 ;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol. Point ();
   if (stop_level== 0.0 )
      stop_level=(m_symbol.Ask()-m_symbol.Bid())* 3.0 ;
   if (freeze_level<= 0.0 || stop_level<= 0.0 )
       return ( false );
   level=(freeze_level>stop_level)?freeze_level:stop_level;
   double spread=m_symbol.Spread()*m_adjusted_point;
   level=(level>spread)?level:spread;
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions( const ENUM_POSITION_TYPE pos_type, const double level)
  {
   for ( int i= PositionsTotal ()- 1 ; i>= 0 ; i--) // returns the number of current positions
       if (m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if (m_position. Symbol ()==m_symbol.Name() /* && m_position.Magic()==InpMagic*/ )
             if (m_position.PositionType()==pos_type)
              {
               if (m_position.PositionType()== POSITION_TYPE_BUY )
                 {
                   bool take_profit_level=(m_position.TakeProfit()!= 0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=level) || m_position.TakeProfit()== 0.0 ;
                   bool stop_loss_level=(m_position.StopLoss()!= 0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=level) || m_position.StopLoss()== 0.0 ;
                   if (take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               if (m_position.PositionType()== POSITION_TYPE_SELL )
                 {
                   bool take_profit_level=(m_position.TakeProfit()!= 0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=level) || m_position.TakeProfit()== 0.0 ;
                   bool stop_loss_level=(m_position.StopLoss()!= 0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=level) || m_position.StopLoss()== 0.0 ;
                   if (take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               PlaySound ( "ok.wav" );
              }
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
     {
       Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " , "RefreshRates error" );
       return ( false );
     }
//--- protection against the return value of "zero"
   if (m_symbol.Ask()== 0 || m_symbol.Bid()== 0 )
     {
       Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " , "Ask == 0.0 OR Bid == 0.0" );
       return ( false );
     }
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignals( void )
  {
//--- we work only at the time of the birth of new bar
   datetime time_0= iTime (m_symbol.Name(), Period (), 0 );
   if (time_0==ExtPrevBars)
       return ( false );
   ExtPrevBars=time_0;
   if (!RefreshRates())
     {
      ExtPrevBars= 0 ;
       return ( false );
     }
//---
   double level;
   double main[],signal[];
   ArraySetAsSeries (main, true );
   ArraySetAsSeries (signal, true );
   int start_pos= 0 ,count= 3 ;
   if (!iGetArray(handle_iCustom, MAIN_LINE ,start_pos,count,main) ||
      !iGetArray(handle_iCustom, SIGNAL_LINE ,start_pos,count,signal))
     {
      ExtPrevBars= 0 ;
       return ( false );
     }
//--- check for long position (BUY) possibility
   if (main[ 0 ]< 0 )
       if (main[ 0 ]>signal[ 0 ] && main[ 1 ]<signal[ 1 ])
        {
         double price=m_symbol.Ask();
           {
             //--- open position
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_SELL ,level);
        }
//--- check for short position (SELL) possibility
   if (main[ 0 ]> 0 )
       if (main[ 0 ]<signal[ 0 ] && main[ 1 ]>signal[ 1 ])
        {
         double price0=m_symbol.Bid();
           {
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price0, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price0, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_BUY ,level);
        }
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
double iGetArray( const int handle, const int buffer, const int start_pos, const int count, double &arr_buffer[])
  {
   bool result= true ;
   if (! ArrayIsDynamic (arr_buffer))
     {
       Print ( "This a no dynamic array!" );
       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 ( "Failed to copy data from the indicator, error code %d" , GetLastError ());
       //--- quit with zero result - it means that the indicator is considered as not calculated
       return ( false );
     }
   return (result);
  }
//+------------------------------------------------------------------+
파일:
0003.PNG  107 kb
0003.mq5  15 kb
 
SanAlex :

MACD 표시기 추가

가장 중요한 것은 - 이제 모든 것이 당신 것입니다.

 
4elovechishe :

내가 설명할 수 있을지도 몰라.

현재 화면에서 변동하는 상품(기호, 예를 들어 EUR/USD)의 시세가 있고 프로그램/어드바이저/로봇이 터미널에서 실행 중이라고 가정해 보겠습니다. 로봇은 당신이 그것에 망치질한 코드를 실행합니다. 그리고 이 코드에는 다음과 같은 줄이 있습니다.

"orderSelect"는 거래 기능이며 추가 작업을 위해 이미 열린 주문을 선택합니다.
//이 예에서 주문을 선택할 수 없는 경우(...==false), "if" 함수의 추가 실행은 "break" 명령에 의해 중단됩니다.

더 나아가. 주문은 OrderSelect 거래 기능 에 의해 선택됩니다. 이제 우리는 특정 명령으로 그와 함께 일하고 있습니다. 이해의 편의를 위해 두 개의 주문만 열려 있다고 가정해 보겠습니다.

다음으로 코드에서 OpenPrice 변수를 입력합니다.   [이중 유형] 우리가 선택한 주문이 열린 가격의 값을 할당합니다(코드 섹션 OpenPrice=OrderOpenPrice(); ).

여기에서는 매개변수를 반환하는 것이 무엇을 의미하는지 설명합니다. OrderOpenPrice 거래 함수는 상품의 현재 가격 값을 반환합니다 . 즉, 프로그램이 현재 가격에 대한 요청으로 서버에 접속한 후 이 가격 값을 사용자에게 반환 하고 이 값을 변수에 할당했습니다.

명확하게 해 주셔서 감사합니다. Roman이 프로그래밍 언어를 마스터하는 데에도 도움이 되기를 바랍니다.

안부 인사를 전합니다. 블라디미르.

 

안녕하세요! 그래서 누군가가 나를 도울 수 있습니다 ...

이제 주문을 시작/마감하는 메커니즘을 파악하고 있으며 열린 위치를 닫는 문제에 직면했습니다.

코드는 간단합니다. 알고리즘의 핵심은 차트에 MA(이동 평균)가 기간 100으로 그려지는 것입니다. 이전 캔들[1]이 MA 위에서 열리고 MA 아래에서 닫히면 다음 캔들에서 매도 주문 이 열립니다. [0].

//(구매조건이 반대입니다. 도색을 하지 않습니다)

주문을 마감하려면 다음과 같은 조건이 필요합니다. 현재 가격은 주문의 시작 가격, 포인트의 설정 값(예: 40)에서 전달되었습니다.

예: Bid=1.20045에서 열린 샷, Ask=1.20005에서 닫혀야 합니다.

간단히 말해서, 뭔가 작동하지 않습니다 ..(( 열기 및 닫기 코드는 OnTick() 함수에 의해 차례로 호출되는 2개의 해당 함수로 압축됩니다. 이론상 닫기 조건을 확인해야 합니다 각 틱으로 표시되지만 실제로 가격은 지정된 수준(종가 수준) 아래로 떨어질 수 있으며 주문은 종료되지 않습니다. 스크린샷과 코드가 첨부되어 있습니다.

 
4elovechishe :

안녕하세요! 그래서 누군가가 나를 도울 수 있습니다 ...

이제 주문을 시작/마감하는 메커니즘을 파악하고 있으며 열린 위치를 닫는 문제에 직면했습니다.

코드는 간단합니다. 알고리즘의 핵심은 차트에 MA(이동 평균)가 기간 100으로 그려지는 것입니다. 이전 캔들[1]이 MA 위에서 열리고 MA 아래에서 닫히면 다음 캔들에서 매도 주문 이 열립니다. [0].

//(구매조건이 반대입니다. 도색을 하지 않습니다)

주문을 마감하려면 다음과 같은 조건이 필요합니다. 현재 가격은 주문의 시작 가격, 포인트의 설정 값(예: 40)에서 전달되었습니다.

예: Bid=1.20045에서 열린 샷, Ask=1.20005에서 닫혀야 합니다.

간단히 말해서, 뭔가 작동하지 않습니다 ..(( 열기 및 닫기 코드는 OnTick() 함수에 의해 차례로 호출되는 2개의 해당 함수로 압축됩니다. 이론상 닫기 조건을 확인해야 합니다 각 틱으로 표시되지만 실제로 가격은 지정된 수준(종가 수준) 아래로 떨어질 수 있으며 주문은 종료되지 않습니다. 스크린샷 및 코드가 첨부되어 있습니다.

https://www.mql5.com/en/forum/160683/page767#comment_10725713 링크의 포럼에 스레드가 있습니다.

거기에서 더 빨리 도움을 받을 수 있습니다.

안부 인사를 전합니다. 블라디미르.

Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам
Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам
  • 2019.02.21
  • www.mql5.com
В этой ветке я хочу начать свою помощь тем, кто действительно хочет разобраться и научиться программированию на новом MQL4 и желает легко перейти н...