mt4自带eamt4 macd双线指标设置 怎么用

您现在的位置:>>
>>正文内容
MACD Sample ---真正的用面向对象的思路来写EA [MT4]
我初步看了下系统自带的MACD Sample EA,这个实例其实用原来MT4的方式实现起来很简单。但是我看了系统自带的代码:简直和C++代码没什么区别了:首先应用头文件或者说是库文件。这些文件其实都是类库文件,每个类里面自带了许多处理方法接着定义一个类然后吧一些变量和方法都封装到类中。最后void OnTick()程序实体部分简单的不可想象:就是定义一个类的实例,然后调用一个类的方法就完了。以后有时间我好好分析分析。//+------------------------------------------------------------------+//| MACD Sample.mq5 |//| Copyright , MetaQuotes Software Corp. |//|
|//+------------------------------------------------------------------+#property copyright &Copyright , MetaQuotes Software Corp.&#property link &&#property version &5.04&#property description &It is important to make sure that the expert works with a normal&#property description &chart and the user did not make any mistakes setting input&#property description &variables (Lots, TakeProfit, TrailingStop) in our case,&#property description &we check TakeProfit on a chart of more than 2*trend_period bars&//---#include &Trade\Trade.mqh& 引用头文件#include &Trade\SymbolInfo.mqh&#include &Trade\PositionInfo.mqh&#include &Trade\AccountInfo.mqh&#include &Indicators\Indicators.mqh&//---input double InpLots =0.1; // Lotsinput int InpTakeProfit =50; // Take Profit (in pips)input int InpTrailingStop =30; // Trailing Stop Level (in pips)input double InpMACDOpenLevel =0.3; // MACD open levelinput double InpMACDCloseLevel=0.2; // MACD close levelinput int InpMATrendPeriod =26; // MA trend period//---int ExtTimeOut=10; // time out in seconds between trade operations//+------------------------------------------------------------------+//| MACD Sample expert class |//+------------------------------------------------------------------+class CSampleExpert {protected: double m_adjusted_ // point value adjusted for 3 or 5 points CTrade m_ // trading object CSymbolInfo m_ // symbol info object CPositionInfo m_ // trade position object CAccountInfo m_ // account info wrapper //--- indicators CIndicators *m_ // indicator collection to fast recalculations CiMACD *m_MACD; // MACD indicator object CiMA *m_EMA; // moving average indicator object //--- indicator data for processing double m_macd_ double m_macd_ double m_signal_ double m_signal_ double m_ema_ double m_ema_public: CSampleExpert(); ~CSampleExpert() { Deinit(); } bool Init(); void Deinit(); bool Processing();protected: bool InitCheckParameters(int digits_adjust); bool InitIndicators(); bool LongClosed(); bool ShortClosed(); bool LongModified(); bool ShortModified(); bool LongOpened(); bool ShortOpened(); };//---CSampleExpert ExtE//+------------------------------------------------------------------+//| Constructor |//+------------------------------------------------------------------+CSampleExpert::CSampleExpert() {//--- m_adjusted_point=0; m_indicators=NULL; m_MACD=NULL; m_EMA =NULL;//--- m_macd_current =0; m_macd_previous =0; m_signal_current =0; m_signal_previous=0; m_ema_current =0; m_ema_previous =0;//--- }//+------------------------------------------------------------------+//| Initialization and checking for input parameters |//+------------------------------------------------------------------+bool CSampleExpert::Init() {//--- initialize common information m_symbol.Name(Symbol()); // symbol m_trade.SetExpertMagicNumber(12345); // magic//--- 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_//--- set default deviation for trading in adjusted points m_trade.SetDeviationInPoints(3*digits_adjust);//--- if(!InitCheckParameters(digits_adjust)) return(false); if(!InitIndicators()) return(false);//--- ok return(true); }//+------------------------------------------------------------------+//| Checking for input parameters |//+------------------------------------------------------------------+bool CSampleExpert::InitCheckParameters(int digits_adjust) {//--- initial data checks if(InpTakeProfit*digits_adjust&m_symbol.StopsLevel()) { printf(&Take Profit must be greater than %d&,m_symbol.StopsLevel()); return(false); } if(InpTrailingStop*digits_adjust&m_symbol.StopsLevel()) { printf(&Trailing Stop must be greater than %d&,m_symbol.StopsLevel()); return(false); }//--- check for right lots amount if(InpLots&m_symbol.LotsMin() || InpLots&m_symbol.LotsMax()) { printf(&Lots amount must be in the range from %f to %f&,m_symbol.LotsMin(),m_symbol.LotsMax()); return(false); } if(MathAbs(MathMod(InpLots,m_symbol.LotsStep()))&1.0E-15) { printf(&Lots amount is not corresponding with lot step %f&,m_symbol.LotsStep()); return(false); }//--- warning if(InpTakeProfit&=InpTrailingStop) printf(&Warning: Trailing Stop must be greater than Take Profit&);//--- ok return(true); }//+------------------------------------------------------------------+//| Initialization of the indicators |//+------------------------------------------------------------------+bool CSampleExpert::InitIndicators() {//--- create indicators collection if(m_indicators==NULL) if((m_indicators=new CIndicators)==NULL) { printf(&Error creating indicators collection&); return(false); }//--- create MACD indicator and add it to collection if(m_MACD==NULL) if((m_MACD=new CiMACD)==NULL) { printf(&Error creating MACD indicator&); return(false); } if(!m_indicators.Add(m_MACD)) { printf(&Error adding MACD indicator to collection&); return(false); }//--- initialize MACD indicator if(!m_MACD.Create(NULL,0,12,26,9,PRICE_CLOSE)) { printf(&Error MACD indicator init&); return(false); } m_MACD.BuffSize(2);//--- create EMA indicator and add it to collection if(m_EMA==NULL) if((m_EMA=new CiMA)==NULL) { printf(&Error creating EMA indicator&); return(false); } if(!m_indicators.Add(m_EMA)) { printf(&Error adding EMA indicator to collection&); return(false); }//--- initialize EMA indicator if(!m_EMA.Create(NULL,0,InpMATrendPeriod,0,MODE_EMA,PRICE_CLOSE)) { printf(&Error EMA indicator init&); return(false); } m_EMA.BuffSize(2);//--- ok return(true); }//+------------------------------------------------------------------+//| Function for deleting of dynamic objects |//+------------------------------------------------------------------+void CSampleExpert::Deinit() {//--- delete indicators collection if(m_indicators!=NULL) { delete m_ m_indicators=NULL; m_MACD=NULL; m_EMA =NULL; }//--- }//+------------------------------------------------------------------+//| Check for long position closing |//+------------------------------------------------------------------+bool CSampleExpert::LongClosed() { bool res=//--- should it be closed? if(m_macd_current&0) if(m_macd_current&m_signal_current && m_macd_previous&m_signal_previous) if(m_macd_current&InpMACDCloseLevel*m_adjusted_point) { //--- close position if(m_trade.PositionClose(Symbol())) printf(&Long position by %s to be closed&,Symbol()); else printf(&Error closing position by %s : '%s'&,Symbol(),m_trade.ResultComment()); //--- processed and cannot be modified res= }//--- return(res); }//+------------------------------------------------------------------+//| Check for short position closing |//+------------------------------------------------------------------+bool CSampleExpert::ShortClosed() { bool res=//--- should it be closed? if(m_macd_current&0) if(m_macd_current&m_signal_current && m_macd_previous&m_signal_previous) if(MathAbs(m_macd_current)&InpMACDCloseLevel*m_adjusted_point) { //--- close position if(m_trade.PositionClose(Symbol())) printf(&Short position by %s to be closed&,Symbol()); else printf(&Error closing position by %s : '%s'&,Symbol(),m_trade.ResultComment()); //--- processed and cannot be modified res= }//--- return(res); }//+------------------------------------------------------------------+//| Check for long position modifying |//+------------------------------------------------------------------+bool CSampleExpert::LongModified() { bool res=//--- check for trailing stop if(InpTrailingStop&0) { if(m_symbol.Bid()-m_position.PriceOpen()&m_adjusted_point*InpTrailingStop) { if(m_position.StopLoss()&m_symbol.Bid()-m_adjusted_point*InpTrailingStop || m_position.StopLoss()==0.0) { double sl=m_symbol.Bid()-m_adjusted_point*InpTrailingS double tp=m_position.TakeProfit(); //--- modify position if(m_trade.PositionModify(Symbol(),sl,tp)) printf(&Long position by %s to be modified&,Symbol()); else { printf(&Error modifying position by %s : '%s'&,Symbol(),m_trade.ResultComment()); printf(&Modify parameters : SL=%f,TP=%f&,sl,tp); } //--- modified and must exit from expert res= } } }//--- return(res); }//+------------------------------------------------------------------+//| Check for short position modifying |//+------------------------------------------------------------------+bool CSampleExpert::ShortModified() { bool res=//--- check for trailing stop if(InpTrailingStop&0) { if((m_position.PriceOpen()-m_symbol.Ask())&(m_adjusted_point*InpTrailingStop)) { if((m_position.StopLoss()&(m_symbol.Ask()+m_adjusted_point*InpTrailingStop)) || m_position.StopLoss()==0.0) { double sl=m_symbol.Ask()+m_adjusted_point*InpTrailingS double tp=m_position.TakeProfit(); //--- modify position if(m_trade.PositionModify(Symbol(),sl,tp)) printf(&Short position by %s to be modified&,Symbol()); else { printf(&Error modifying position by %s : '%s'&,Symbol(),m_trade.ResultComment()); printf(&Modify parameters : SL=%f,TP=%f&,sl,tp); } //--- modified and must exit from expert res= } } }//--- return(res); }//+------------------------------------------------------------------+//| Check for long position opening |//+------------------------------------------------------------------+bool CSampleExpert::LongOpened() { bool res=//--- check for long position (BUY) possibility if(m_macd_current&0) if(m_macd_current&m_signal_current && m_macd_previous&m_signal_previous) if(MathAbs(m_macd_current)&(InpMACDOpenLevel*m_adjusted_point) && m_ema_current&m_ema_previous) { //--- check for free money if(m_account.FreeMarginCheck(Symbol(),0,InpLots)&0.0) printf(&We have no money. Free Margin = %f&,m_account.FreeMargin()); else { double price=m_symbol.Ask(); double tp =m_symbol.Ask()+InpTakeProfit*m_adjusted_ //--- open position if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,InpLots,price,0.0,tp)) printf(&Position by %s to be opened&,Symbol()); else { printf(&Error opening BUY position by %s : '%s'&,Symbol(),m_trade.ResultComment()); printf(&Open parameters : price=%f,TP=%f&,price,tp); } } //--- in any case we must exit from expert res= }//--- return(res); }//+------------------------------------------------------------------+//| Check for short position opening |//+------------------------------------------------------------------+bool CSampleExpert::ShortOpened() { bool res=//--- check for short position (SELL) possibility if(m_macd_current&0) if(m_macd_current&m_signal_current && m_macd_previous&m_signal_previous) if(m_macd_current&(InpMACDOpenLevel*m_adjusted_point) && m_ema_current&m_ema_previous) { //--- check for free money if(m_account.FreeMarginCheck(Symbol(),0,InpLots)&0.0) printf(&We have no money. Free Margin = %f&,m_account.FreeMargin()); else { double price=m_symbol.Bid(); double tp =m_symbol.Bid()-InpTakeProfit*m_adjusted_ //--- open position if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,InpLots,price,0.0,tp)) printf(&Position by %s to be opened&,Symbol()); else { printf(&Error opening SELL position by %s : '%s'&,Symbol(),m_trade.ResultComment()); printf(&Open parameters : price=%f,TP=%f&,price,tp); } } //--- in any case we must exit from expert res= }//--- return(res); }//+------------------------------------------------------------------+//| main function returns true if any position processed |//+------------------------------------------------------------------+bool CSampleExpert::Processing() {//--- refresh rates if(!m_symbol.RefreshRates()) return(false);//--- refresh indicators m_indicators.Refresh();//--- to simplify the coding and speed up access//--- data are put into internal variables m_macd_current =m_MACD.Main(0); m_macd_previous =m_MACD.Main(1); m_signal_current =m_MACD.Signal(0); m_signal_previous=m_MACD.Signal(1); m_ema_current =m_EMA.Main(0); m_ema_previous =m_EMA.Main(1);//--- it is important to enter the market correctly, //--- but it is more important to exit it correctly... //--- first check if position exists - try to select it if(m_position.Select(Symbol())) { if(m_position.PositionType()==OP_BUY) { //--- try to close or modify long position if(LongClosed()) return(true); if(LongModified()) return(true); } else { //--- try to close or modify short position if(ShortClosed()) return(true); if(ShortModified()) return(true); } }//--- no opened position identified else { //--- check for long position (BUY) possibility if(LongOpened()) return(true); //--- check for short position (SELL) possibility if(ShortOpened()) return(true); }//--- exit without position processing return(false); }//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+int OnInit() {//--- create all necessary objects if(!ExtExpert.Init()) { ExtExpert.Deinit(); return(-1); }//--- ok return(0); }//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+void OnDeinit(const int reason) { ExtExpert.Deinit(); }//+------------------------------------------------------------------+//| Expert new tick handling function |//+------------------------------------------------------------------+void OnTick() { static datetime limit_time=0; // last trade processing time + timeout//--- don't process if timeout if(TimeCurrent()&=limit_time) { //--- check for data if(Bars(Symbol(),Period())&2*InpMATrendPeriod) { //--- change limit time by timeout in seconds if processed if(ExtExpert.Processing()) limit_time=TimeCurrent()+ExtTimeO } }//--- }//+------------------------------------------------------------------+
【字体: 】【】【】
没有相关内容
本月热门排行
会员登录/注册MT4平台设置双线MACD的方法
我的图书馆
MT4平台设置双线MACD的方法
MT4平台设置双线MACD的方法
国内许多炒外汇的朋友由于习惯了国内股票软件上的MACD,对于如MT4提供的MACD自然感觉很别扭。然而,刚刚接触时苦于不会设置而犯难。下面我就将自己的方法与大家分享。
&&& 点击工具栏中的“导航”,在弹出的窗口选择打开“自定义指标”,右键点击“MACD”,选择“修改(M)”。之后弹出“MACD”的源代码。将其全部删除,粘贴上一下代码:
//+------------------------------------------------------------------+//|&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& Custom MACD.mq4 |//|&&&&&&&&&&&&&&&&&&&&& Copyright ?2004, MetaQuotes Software Corp. |//|&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
|//+------------------------------------------------------------------+#property& copyright "Copyright ?2004, MetaQuotes Software Corp."#property& link&&&&& ""//---- indicator settings#property& indicator_separate_window#property& indicator_buffers 3#property& indicator_color1& Silver#property& indicator_color2& Gold#property& indicator_color3& Red#property& indicator_width1& 1//---- indicator parametersextern int FastEMA=12;extern int SlowEMA=26;extern int SignalEMA=9;//---- indicator buffersdouble&&&& MacdBuffer[];double&&&& SignalBuffer[];double&&&& DiffBuffer[];
//+------------------------------------------------------------------+//| Custom indicator initialization function&&&&&&&&&&&&&&&&&&&&&&&& |//+------------------------------------------------------------------+int init()& {//---- drawing settings&& SetIndexStyle(0,DRAW_LINE);&& SetIndexStyle(1,DRAW_LINE);&& SetIndexStyle(2,DRAW_HISTOGRAM);&& SetIndexDrawBegin(1,SignalEMA);&& IndicatorDigits(Digits+1);//---- indicator buffers mapping&& SetIndexBuffer(0,MacdBuffer);&& SetIndexBuffer(1,SignalBuffer);&& SetIndexBuffer(2,DiffBuffer);//---- name for DataWindow and indicator subwindow label&& IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalEMA+")");&& SetIndexLabel(0,"MACD");&& SetIndexLabel(1,"Signal");&& SetIndexLabel(2,"Diff");//---- initialization done&& return(0);& }//+------------------------------------------------------------------+//| Moving Averages Convergence/Divergence&&&&&&&&&&&&&&&&&&&&&&&&&& |//+------------------------------------------------------------------+int start()& {&&&& int counted_bars=IndicatorCounted();//---- last counted bar will be recounted&& if(counted_bars&0) counted_bars--;&& limit=Bars-counted_//---- macd counted in the 1-st buffer&& for(int i=0; i& i++)&&&&& MacdBuffer[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)-iMA
(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i);//---- signal line counted in the 2-nd buffer&& for(i=0; i& i++)&&&&& SignalBuffer[i]=iMAOnArray(MacdBuffer,Bars,SignalEMA,0,MODE_EMA,i);&& for(i=0; i& i++)&&&&& DiffBuffer[i]=MacdBuffer[i]-SignalBuffer[i];//---- done&& return(0);& }//+------------------------------------------------------------------+
然后点击“编译”,“保存”,即完成了MACD的双线设置。
馆藏&17936
TA的最新馆藏[转]&[转]&[转]&[转]&[转]&[转]&
喜欢该文的人也喜欢MT4自带交易系统(EA):MACD&Sample的详解
+------------------------------------------------------------------+
Sample.mq4 & & &
&Copyright ?2005, MetaQuotes Software Corp.
//+------------------------------------------------------------------+
extern double TakeProfit = 50; & 盈利目标点数
extern double Lots = 0.1; &
& & 每单入场的手数
extern double TrailingStop = 30; 追踪止损的点数
extern double MACDOpenLevel=3; MACD开仓的参考位置
extern double MACDCloseLevel=2; MACD出场的参考位置
extern double MATrendPeriod=26; 条件中使用的MA均线的周期数
程序最上面extern开始的这些数据都是程序参数,也就是在使用者调用的时候可以修改的部分。
这个EA是个常见的技术指标条件入场,条件出场 同时又移动止损功能的完成示意,很适合初学者研究。
先总结这个程序的基本条件的意思 以方便大家对号入座,尽快理解。
多头入场条件:
& &MACD小于0 并且
小于指定的参数MACDOpenLevel & 并且 MACD讯号下下穿基准线(死叉) 并且
MA向上趋势
多头出场条件:
& &MACD大于0 并且
大于指定的参数MACDCloseLevel 并且 MACD信号线上传基准线(金叉)
空头入场条件:
MACD大于0 并且 大于指定的参数MACDOpenLevel & 并且
MACD讯号线上穿基准线(金叉) 并且 MA向下趋势
空头出场条件:
MACD小于0 并且 小于制定的参数MACDCloseLevel & 并且
MACD讯号线下穿基准线(死叉)
=============================================================
有了以上的初步了解,下面开始进行EA程序基本结构的分析:
1、start()函数是最重要的执行部分,每来一个价格 此函数都自动执行一次,所以主要的逻辑结构都在这个函数里
2、程序的基本流程都是按照以下步骤进行,我们先牢牢记住这个结构,然后再对号入座去理解程序。
先判断当前自身的仓位状态,因为start函数式循环运行的,所以中间的每个步骤都会使用start函数,因此,当函数开始的时候我们首先要通过MT4的仓位操作函数获得当前的仓位状态,并进一步根据状态进行不同分支的计算。
程序开始的以下两个部分不重要 简单说一下:
if(Bars&100)
& &Print("bars less than
& &return(0);
以上是说如果当前图形的K线个数少于100 则不进行运算
直接返回。这种情况一般不会出现,所以我们自己写程序的时候可以不写这部分。
if(TakeProfit&10)
& &Print("TakeProfit less
than 10");
& &return(0);
& // check TakeProfit
以上这段意思是参数TakeProfit移动止损点数的设定如果小于10点,则发出报警,并返回不进行运算。这是为了防止乱设数值,引起后面计算的错误。这部分,如果程序只是我们自己使用,估计不会犯这种低级错误,所以写程序的时候也可以忽略不写。
下面这段:
MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
这部分是变量赋值部分,等于提前计算出为后面用到的当前MACD数值以及MA数值,这样提前写出来在后面直接使用赋值后的变量就很清楚了。是很好的编程习惯。
&再下面开始最主要的程序逻辑部分,首先遇到的就是我们上面说过的通过仓位函数获得当前状态的部分。
total=OrdersTotal();
通过函数获得当前持仓单的个数,如果持仓单个数小于1,则说明是空仓状态,那末就进行多头和空头的入场条件判断,如果满足条件则进行入场。代码如下:
if(total&1)
& &// no opened orders
identified
&if(AccountFreeMargin()&(1000*Lots))
& 这句诗判断保证金余量是否够下单,如果不够则直接返回,并不进行后续入场判断
Print("We have no money. Free Margin = ",
AccountFreeMargin());
return(0); &
& &// check for long
position (BUY) possibility
& &if(MacdCurrent&0
&& MacdCurrent&SignalCurrent &&
MacdPrevious
MathAbs(MacdCurrent)&(MACDOpenLevel*Point) &&
MaCurrent&MaPrevious) 这句就是多头入场条件的判断,可以看到2个技巧,1、交叉
的数学意思是“前面再下后面在上”或反之 2、MA向上趋势 的数学意思是当前K线的MA大于上一K线的MA数值
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"macd
sample",16384,0,Green); 这是入场语句
记得一定要判断入场是否成功,因为很多服务器由于滑点或者服务器价格变动而不能入场成功,所以,要判断入场不成功后作出提示。ticket就是定单入场是否成功的标记。
if(ticket&0) 大于0说明入场成功
&if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
Print("BUY order opened : ",OrderOpenPrice());
& & & else
Print("Error opening BUY order : ",GetLastError());
入场不成功,输出不成功的系统原因。
return(0);
这里为什麽使用了返回呢。因为一种情况是入场成功,那末直接返回等待下一个价格到来的时候再执行start函数,另一种情况是入场不成功,则返回也是等待下一个价格到来的时候在此执行入场操作。
&下面就是空单入场的判断了,大家自己对照观看即可
& &// check for short
position (SELL) possibility
& &if(MacdCurrent&0
&& MacdCurrentSignalPrevious &&
MacdCurrent&(MACDOpenLevel*Point) && MaCurrent
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,"macd
sample",16384,0,Red);
if(ticket&0)
&if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
Print("SELL order opened : ",OrderOpenPrice());
& & & else
Print("Error opening SELL order : ",GetLastError());
return(0);
& &return(0);
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 mt4 ea写macd 的文章

 

随机推荐