초보자의 질문 MQL5 MT5 MetaTrader 5 - 페이지 1117

 
MrBrooklin :

모두 좋은 하루!

다음은 Metatrader5에 대한 스크립트 코드의 일부입니다.


질문이 생겼습니다.

1. 계획대로 스크립트는 매도호가와 매수호가로부터 특정 거리에 보류 중인 지정가 주문 또는 정지 주문을 배치해야 합니다. 한도 보류 주문 은 문제 없이 설정되지만 스탑 주문은 그렇지 않습니다. 구매 중지 및 판매 중지 보류 주문이 설정되지 않은 이유를 알아낼 수 있도록 도와주세요.

2. 마켓이 닫힐 때(예: 주말) 스크립트를 테스트할 수 있는 방법이 있습니까?

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

도움말: 일반 원칙 - 거래 운영

보류 중인 주문의 유형

시장의 현재 상태

- 현재 시장 상황

예측

- 예측

현재 가격

- 현재 가격

주문 가격

— 주문 가격

보류 중인 주문이 배치되는 가격

— 보류 중인 주문이 배치되는 가격

예상 성장

- 예상 성장

예상되는 가을

- 예상되는 가을


그리고 시작 가격 형성의 실수:

 //--- start work
   double start_price_ask=m_symbol.Ask()-ExtUpGap;
   double start_price_bid=m_symbol.Bid()+ExtDownGap;

시작가를 Stop에 대해 별도로 지정하고 Limit 보류 주문에 대해 별도로 시작 가격을 설정하는 것이 좋습니다.

Общие принципы - Торговые операции - MetaTrader 5
Общие принципы - Торговые операции - MetaTrader 5
  • www.metatrader5.com
Перед тем как приступить к изучению торговых функций платформы, необходимо создать четкое представление об основных терминах: ордер, сделка и позиция. — это распоряжение брокерской компании купить или продать финансовый инструмент. Различают два основных типа ордеров: рыночный и отложенный. Помимо них существуют специальные ордера Тейк Профит...
 

거래, 자동 거래 시스템 및 거래 전략 테스트에 관한 포럼

초보자의 질문 MQL5 MT5 MetaTrader 5

블라디미르 카르푸토프 , 2019.08.31 08:16


그리고 시작 가격 형성의 실수:

 //--- start work
   double start_price_ask=m_symbol.Ask()-ExtUpGap;
   double start_price_bid=m_symbol.Bid()+ExtDownGap;

시작가를 Stop에 대해 별도로 지정하고 Limit 보류 주문에 대해 별도로 시작 가격을 설정하는 것이 좋습니다.

팁을 주신 Vladimir에게 감사드립니다.

비공개 시장(예: 주말)에서 스크립트를 테스트할 수 있는 가능성에 대해 어떻게 말씀하십니까?

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

 

비공개 시장(예: 주말)에서 스크립트를 테스트할 수 있는 가능성에 대해 어떻게 말씀하십니까?



때문에 질문이 삭제되었습니다. 답변은 다른 스레드에서 제공된 것 같습니다.

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

 
MrBrooklin :

때문에 질문이 삭제되었습니다. 답변은 다른 스레드에서 제공된 것 같습니다.

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

글쎄, 당신은 포럼 전체에 하나의 질문을 낳고 흩어 놓았습니다 ... 당신 자신이 혼란스러워합니다.

 
MrBrooklin :

팁을 주신 Vladimir에게 감사드립니다.

비공개 시장(예: 주말)에서 스크립트를 테스트할 수 있는 가능성에 대해 어떻게 말씀하십니까?

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

주말에는 거래 스크립트를 실행할 수 없지만 스크립트에서 Expert Advisor를 만들면 테스트 할 수 있습니다.

OnStart 대신 OnTick을 넣고거래 기능 을 OnInit으로 이동합니다. 별로 예쁘지는 않지만 주말에 스크립트 테스트에 사용할 수 있습니다.
 
MrBrooklin :

팁을 주신 Vladimir에게 감사드립니다.

비공개 시장(예: 주말)에서 스크립트를 테스트할 수 있는 가능성에 대해 어떻게 말씀하십니까?

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

전문가의 모습은 다음과 같습니다.

 //+------------------------------------------------------------------+
//|                                               Stop and Limit.mq5 |
//|                              Copyright © 2019, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2019, Vladimir Karputov"
#property link        "http://wmua.ru/slesar/"
#property version    "1.00"
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
CTrade         m_trade;                       // trading object
CSymbolInfo    m_symbol;                     // symbol info object
//+------------------------------------------------------------------+
//| Enum Stop or Limit                                               |
//+------------------------------------------------------------------+
enum ENUM_STOP_OR_LIMIT
  {
   stop= 0 ,     // Buy stop and Sell stop
   limit= 1      // Buy limit and Sell limit
  };
//--- input parameters
input ushort                InpUpGap          = 15 ;     // Gap for pending orders UP from the current price (in points)
input ushort                InpUpStep         = 30 ;     // Step between orders UP (in points)
input ushort                InpDownGap        = 15 ;     // Gap for pending orders DOWN from the current price (in points)
input ushort                InpDownStep       = 30 ;     // Step between orders DOWN (in points)
input ENUM_STOP_OR_LIMIT   InpPending        = stop;   // Type of pending orders
input uchar                 InpUpQuantity     = 1 ;     // UP quantity orders
input uchar                 InpDownQuantity   = 1 ;     // DOWN quantity orders
input double                InpLots           = 0.01 ;   // Lots
input ushort                InpStopLoss       = 50 ;     // Stop Loss (in points)
input ushort                InpTakeProfit     = 50 ;     // Take Profit (in points)
//---
ulong        m_slippage     = 30 ;     // slippage

double       ExtUpGap       = 0.0 ;
double       ExtUpStep      = 0.0 ;
double       ExtDownGap     = 0.0 ;
double       ExtDownStep    = 0.0 ;
double       ExtStopLoss    = 0.0 ;
double       ExtTakeProfit  = 0.0 ;
double       m_adjusted_point;       // point value adjusted for 3 or 5 points
bool         m_first_start  = false ;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
   if (!m_symbol.Name( Symbol ())) // sets symbol name
     {
       Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: CSymbolInfo.Name" );
       return ( INIT_FAILED );
     }
   RefreshRates();
//--- 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;

   ExtUpGap       =  InpUpGap       * m_adjusted_point;
   ExtUpStep      =  InpUpStep      * m_adjusted_point;
   ExtDownGap     =  InpDownGap     * m_adjusted_point;
   ExtDownStep    =  InpDownStep    * m_adjusted_point;
   ExtStopLoss    =  InpStopLoss    * m_adjusted_point;
   ExtTakeProfit  =  InpTakeProfit  * m_adjusted_point;
//--- check the input parameter "Lots"
   string err_text= "" ;
   if (!CheckVolumeValue(InpLots,err_text))
     {
       //--- when testing, we will only output to the log about incorrect input parameters
       if ( MQLInfoInteger ( MQL_TESTER ))
        {
         Print ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " ,err_text);
         return ( INIT_FAILED );
        }
       else // if the Expert Advisor is run on the chart, tell the user about the error
        {
         Alert ( __FILE__ , " " , __FUNCTION__ , ", ERROR: " ,err_text);
         return ( INIT_PARAMETERS_INCORRECT );
        }
     }
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   if (m_first_start)
       return ;
//---
   if (!RefreshRates())
       return ;
//--- start work
   double start_price_ask= 0.0 ;
   double start_price_bid= 0.0 ;
   if (InpPending==stop)
     {
      start_price_ask=m_symbol.Ask()+ExtUpGap;
      start_price_bid=m_symbol.Bid()-ExtDownGap;
     }
   else
       if (InpPending==limit)
        {
         start_price_ask=m_symbol.Ask()-ExtUpGap;
         start_price_bid=m_symbol.Bid()+ExtDownGap;
        }
//--- set pending orders
   for ( int i= 0 ; i<InpUpQuantity; i++)
     {
       double price_ask = start_price_ask+i*ExtUpStep;
       double price_bid = start_price_bid+i*ExtUpStep;
       if (InpPending==stop)
        {
         double sl = (ExtStopLoss== 0.0 )   ? 0.0 : price_ask - ExtStopLoss;
         double tp = (ExtTakeProfit== 0.0 ) ? 0.0 : price_ask + ExtTakeProfit;
         m_trade.BuyStop(InpLots,m_symbol.NormalizePrice(price_ask),m_symbol.Name(),
                         m_symbol.NormalizePrice(sl),
                         m_symbol.NormalizePrice(tp));
        }
       else
        {
         double sl = (ExtStopLoss== 0.0 )   ? 0.0 : price_bid + ExtStopLoss;
         double tp = (ExtTakeProfit== 0.0 ) ? 0.0 : price_bid - ExtTakeProfit;
         m_trade.SellLimit(InpLots,m_symbol.NormalizePrice(price_bid),m_symbol.Name(),
                           m_symbol.NormalizePrice(sl),
                           m_symbol.NormalizePrice(tp));
        }
     }

//--- set pending orders
   for ( int i= 0 ; i<InpDownQuantity; i++)
     {
       double price_ask = start_price_ask-i*ExtDownStep;
       double price_bid = start_price_bid-i*ExtDownStep;
       if (InpPending==limit)
        {
         double sl = (ExtStopLoss== 0.0 )   ? 0.0 : price_ask - ExtStopLoss;
         double tp = (ExtTakeProfit== 0.0 ) ? 0.0 : price_ask + ExtTakeProfit;
         m_trade.BuyLimit(InpLots,m_symbol.NormalizePrice(price_ask),m_symbol.Name(),
                          m_symbol.NormalizePrice(sl),
                          m_symbol.NormalizePrice(tp));
        }
       else
        {
         double sl = (ExtStopLoss== 0.0 )   ? 0.0 : price_bid + ExtStopLoss;
         double tp = (ExtTakeProfit== 0.0 ) ? 0.0 : price_bid - ExtTakeProfit;
         m_trade.SellStop(InpLots,m_symbol.NormalizePrice(price_bid),m_symbol.Name(),
                          m_symbol.NormalizePrice(sl),
                          m_symbol.NormalizePrice(tp));
        }
     }
//---
   m_first_start= true ;
  }
//+------------------------------------------------------------------+
//| 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 );
  }
//+------------------------------------------------------------------+
//| Check the correctness of the position volume                     |
//+------------------------------------------------------------------+
bool CheckVolumeValue( double volume, string &error_description)
  {
//--- minimal allowed volume for trade operations
   double min_volume=m_symbol.LotsMin();
   if (volume<min_volume)
     {
       if ( TerminalInfoString ( TERMINAL_LANGUAGE )== "Russian" )
         error_description= StringFormat ( "Объем меньше минимально допустимого SYMBOL_VOLUME_MIN=%.2f" ,min_volume);
       else
         error_description= StringFormat ( "Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f" ,min_volume);
       return ( false );
     }
//--- maximal allowed volume of trade operations
   double max_volume=m_symbol.LotsMax();
   if (volume>max_volume)
     {
       if ( TerminalInfoString ( TERMINAL_LANGUAGE )== "Russian" )
         error_description= StringFormat ( "Объем больше максимально допустимого SYMBOL_VOLUME_MAX=%.2f" ,max_volume);
       else
         error_description= StringFormat ( "Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f" ,max_volume);
       return ( false );
     }
//--- get minimal step of volume changing
   double volume_step=m_symbol.LotsStep();
   int ratio=( int ) MathRound (volume/volume_step);
   if ( MathAbs (ratio*volume_step-volume)> 0.0000001 )
     {
       if ( TerminalInfoString ( TERMINAL_LANGUAGE )== "Russian" )
         error_description= StringFormat ( "Объем не кратен минимальному шагу SYMBOL_VOLUME_STEP=%.2f, ближайший правильный объем %.2f" ,
                                        volume_step,ratio*volume_step);
       else
         error_description= StringFormat ( "Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f" ,
                                        volume_step,ratio*volume_step);
       return ( false );
     }
   error_description= "Correct volume value" ;
   return ( true );
  }
//+------------------------------------------------------------------+
파일:
 

블라디미르 카르푸토프 , 2019.08.31 13:20

전문가의 모습은 다음과 같습니다.



수업!

감사합니다, 블라디미르, 그들은 저를 도와주었습니다. 그렇지 않으면 월요일까지 고통을 겪었을 것입니다.

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

 
MrBrooklin :

수업!

감사합니다, 블라디미르, 그들은 저를 도와주었습니다. 그렇지 않으면 월요일까지 고통을 겪었을 것입니다.

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

물론이죠.

전역 프로그램 수준에서 선언된 m_first_start 변수에 주의하십시오.

 bool         m_first_start  = false ;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()

OnTick의 끝에서 이 변수는 "true"로 설정됩니다.

 //---
   m_first_start= true ;
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {

EA는 다음에 다시 시작할 때까지 더 이상 보류 중인 주문 을 하지 않습니다.

 //+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   if (m_first_start)
       return ;
 

거래, 자동 거래 시스템 및 거래 전략 테스트에 관한 포럼

초보자의 질문 MQL5 MT5 MetaTrader 5

블라디미르 카르푸토프 , 2019.08.31 14:38

물론이죠.

전역 프로그램 수준에서 선언된 m_first_start 변수에 주의하십시오.

예, Vladimir, 저는 Expert Advisor가 테스트 중에 스크립트처럼 작동한다는 것을 즉시 알아차렸습니다. 다시 한번 감사합니다!

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

 

촛불 출력이 작동하지 않는 이유는 무엇입니까?


 #property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property version    "1.00"
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots    1

#property indicator_label1    "SecondInstrument"
#property indicator_type1    DRAW_CANDLES
#property indicator_color1    clrBlack , clrGreen , clrRed
#property indicator_style1    STYLE_SOLID 
#property indicator_width1    1 

double OBuffer[];
double HBuffer[];
double LBuffer[];
double CBuffer[];

string symbol = "GBPJPY.m" ;
int barsToBuid = 100 ;
int deviation = 0 ;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- indicator buffers mapping
   SetIndexBuffer ( 0 ,OBuffer, INDICATOR_DATA );
   SetIndexBuffer ( 1 ,HBuffer, INDICATOR_DATA );
   SetIndexBuffer ( 2 ,LBuffer, INDICATOR_DATA );
   SetIndexBuffer ( 3 ,CBuffer, INDICATOR_DATA );

   PlotIndexSetDouble ( 0 , PLOT_EMPTY_VALUE , 0 ); 
   PlotIndexSetString ( 0 , PLOT_LABEL ,symbol+ " Open;" +symbol+ " High;" +symbol+ " Low;" +symbol+ " Close" ); 
   IndicatorSetString ( INDICATOR_SHORTNAME , "DRAW_CANDLES(" +symbol+ ")" );
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate ( const int rates_total,
                 const int prev_calculated,
                 const datetime &time[],
                 const double &open[],
                 const double &high[],
                 const double &low[],
                 const double &close[],
                 const long &tick_volume[],
                 const long &volume[],
                 const int &spread[]){
                
   for ( int i= 0 ;i<barsToBuid;i++){
      OBuffer[i] = iOpen (symbol, PERIOD_CURRENT , i) + deviation* _Point ;
      HBuffer[i] = iHigh (symbol, PERIOD_CURRENT , i) + deviation* _Point ;
      LBuffer[i] = iLow (symbol, PERIOD_CURRENT , i) + deviation* _Point ;
      CBuffer[i] = iClose (symbol, PERIOD_CURRENT , i) + deviation* _Point ;
      
     }
   return (rates_total);
  }
//+------------------------------------------------------------------+
사유: