一般程序化交易的模型
  1. 在回调中计算交易信号
  2. 处理已有持仓
  3. 根据信号下单,在信号出现时还要计算止损止盈。
    • 止损:ATR/前一根K线的低点/前一个分形的低点/反向信号
    • 止盈: 2*ATR/3*ATR/4*ATR/反向信号
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // 设置短期和长期均线的周期
   int shortPeriod = 20;
   int longPeriod = 50;

   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   double shortMA = iMA(Symbol(), 0, shortPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
   double longMA = iMA(Symbol(), 0, longPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);

   double atr = iATR(Symbol(), 0, 14, 0);

    // ATR 方式设置止盈止损
   double stopLoss = shortMA - 2*atr;
   double takeProfit = shortMA + 4*atr;     

   // 获取前一根蜡烛图的高点和低点
   // double prevHigh = High[1];
   // double prevLow = Low[1];

   // 设置止损和止盈
   // double stopLoss = prevLow;
   // double takeProfit = prevHigh;

   // 获取前一根蜡烛图的分形低点和分形高点
   // double prevFractalLow = iFractals(Symbol(), 0, MODE_LOWER, 1);
   // double prevFractalHigh = iFractals(Symbol(), 0, MODE_UPPER, 1);

   // 设置止损和止盈
   // double stopLoss = prevFractalLow;
   // double takeProfit = prevFractalHigh;

   // 获取已有持仓
   int totalPositions = PositionsTotal();
   for (int i = totalPositions - 1; i >= 0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS))
      {
         // 判断均线交叉
         if (shortMA > longMA && OrderType() == OP_SELL)
         {
            // 平掉空单
            OrderClose(OrderTicket(), OrderLots(), MarketInfo(Symbol(), MODE_ASK), 3, clrNONE);
         }
         else if (shortMA < longMA && OrderType() == OP_BUY)
         {
            // 平掉多单
            OrderClose(OrderTicket(), OrderLots(), MarketInfo(Symbol(), MODE_BID), 3, clrNONE);
         }
      }
   }

   // 判断均线交叉
   if (shortMA > longMA && shortMA > iMA(Symbol(), 0, shortPeriod, 0, MODE_EMA, PRICE_CLOSE, 1))
   {
      // 如果没有持仓,则执行限价买单
      if (totalPositions == 0)
      {
         int ticket = OrderSend(Symbol(), OP_BUYLIMIT, 0.1, shortMA, 3, stopLoss, takeProfit, "Double MA Strategy", 0, clrNONE);
         if (ticket > 0)
            Print("Buy limit order opened successfully. Ticket: ", ticket);
         else
            Print("Error opening buy limit order. Error code: ", GetLastError());
      }
   }
   else if (shortMA < longMA && shortMA < iMA(Symbol(), 0, shortPeriod, 0, MODE_EMA, PRICE_CLOSE, 1))
   {
      // 如果没有持仓,则执行限价卖单
      if (totalPositions == 0)
      {
         int ticket = OrderSend(Symbol(), OP_SELLLIMIT, 0.1, shortMA, 3, stopLoss, takeProfit, "Double MA Strategy", 0, clrNONE);
         if (ticket > 0)
            Print("Sell limit order opened successfully. Ticket: ", ticket);
         else
            Print("Error opening sell limit order. Error code: ", GetLastError());
      }
   }
}
//+------------------------------------------------------------------+

Create an Expert Advisor for a SuperTrend Trading Strategy

Last Updated on September 19, 2023 by Mark Ursell

In this article, I will show you how to build an Expert Advisor for a SuperTrend Trading Strategy.

MT4 is a massively popular trading platform that is offered by a huge range of different brokers. This article will help you power-up your programming skills and help you quickly start backtesting your strategies.

The article and accompanying video shows how an EA is written and how that EA can be used to backtest and automatically trade a trading strategy. I break down the components of the EA and explain how each part is used to follow the strategy.

The SuperTrend Technical Indicator

SuperTrend Icon
The SuperTrend indicator is a great indicator for identifying the current market trend. The indicator is constructed by combining the Average True Range with the Median Price (High-Low)/2 and the Closing Price. I explain how the indicator is calculated in my article and video How to Calculate the SuperTrend Indicator Using Excel.

SuperTrend Trading Strategy

In my previous article, Backtesting a SuperTrend Trading Strategy Using Excel, I showed how Excel can be used to test a trading strategy.

In this test we are going to use basically the same strategy using the following rules:

Only one trade at a time.

Enter Long:

When the closing price is above 200 SMA and crosses from below to above SuperTrend. Or when the closing price is above SuperTrend and crosses from below to above 200 SMA

Enter Short:

When the closing price is below 200 SMA and crosses from above to below SuperTrend.Or when the closing price is below SuperTrend and crosses from above to below 200 SMA

Close Long Trade:

When either Profit Target or Stop-Loss is hit. Or when closing price crosses from above to below 25 EMA.

Close Short Trade:

When either Profit Target or Stop-Loss is hit. Or when closing price crosses from below to above 25 EMA

Video

This article is accompanied by a video article and I suggest you watch the video while reading the article.



MT4 Expert Advisors

MT4 is a widely used trading platform, offered by Forex Brokers around the world. EAs are programs written using the MQL4 language that describe trading strategies. If you are interested in learning more about MQL4, there is an online reference guide, the MQL4 Book.

Expert Advisor for a SuperTrend Trading Strategy

Constants
#define

We are going to use this command to define our trade opening criteria. For example:

#define LongTrade 1
External Inputs

Any variables that we want to be able to manually change or optimise are called external variables and we indicate them using extern. For example:

extern double PercentagePerTrade = 1.0;

The above sets an external variable that is a double type number. Double numbers are real numbers with a decimal point. PercentagePerTrade is the name of the variable and represents the amount of capital that we will invest per trade. 1.0 is our initial value.

Int Start()

All the calculations and trading carried out by the EA is within the Start() function. The contents of the start function are enclosed with curly brackets {…}.

The start function runs every time a new tick (change in market price) is received. This is important because the EA needs to be constantly monitoring the market, ready to act when the trading criteria are met.

Declaring Variables

SuperTrend Strategy Variables
Our EA uses variables to carry out the calculations that are needed to follow the trading strategy. We declare variables by telling the MT4 what type of variables they are. We have already seen the double type of variable. The other types of variables used in this EA are:

int integer (whole number)
bool boolean (true or false)
Calculate Lots per Trade

I like to use trading strategies that alter the trade size based on the amount risked. In this EA the stop-loss is automatically calculated based on a multiple of the ATR.

This part of the program uses the percentage risked and the stop-loss length to automatically set the number of lots per trade.

Calculate Technical Indicators

This part of the program sets out the technical indicators that we are going to use in this EA. The SuperTrend indicator does not come built into MT4 and so we are going to use a Custom Indicator for this. Custom indicators are called iCustom. In our EA we have used the following to describe the SuperTrend indicator:

double ST1 = iCustom(NULL, 0, “SuperTrend”, 20, STMultiplier, 0, 1);

The above line sets out the following information:

  • We have called the variable ST1 and set it as a double type.
  • NULL means that this indicator can run on any market.
  • 0 means that this indicator can run on any timeframe.
  • “SuperTrend” is the name of the indicator.
  • 20 is the number of periods that the SuperTrend indicator is calculated over.
  • STMultiplier is the external variable that we set earlier, the initial value is 2.0.
  • 0 is the mode of the SuperTrend and in this case refers to the main indicator line.
  • 1 refers to the previous period which is the last complete bar. We only want this EA to trade based on a complete bar.

The other indicators used are EMA (exponential moving average), SMA (simple moving average) and ATR. These indicators are built into MT4 and more information can be found about how to customise them in the MQL4 Book section on Technical Indicators.

Enter Long Trade

In this section we set out our trade entry criteria. We use an IF Statement to set the criteria.

if (Close1 > ST1 && Close2 < ST2 && Close1 > SMA1) Order = LongTrade;
if (Close1 > SMA1 && Close2 < SMA2 && Close1 > ST1) Order = LongTrade;
Check the Trading Time

The forex market is open 24 hours a day, 5 days a week. However, the amount of liquidity varies significantly at different times of the day. Many EAs will operate better at certain times of the day.

In our external variables, we have set the times that the EA should be looking for trades. This IF Statement will check if the EA is allowed to trade at the current time; if so it will move to the next stage; if not it will wait for the next tick and check the time again.

Number of Trades Allowed

This part of the program counts the number of trades that are live or pending from the EA. It will ignore manual trades and trades made by other EAs with a different Magic Number. The Magic Number is a unique number that identifies each Expert Advisor. It is set as an external variable.

Opening Trades

At this stage, our EA has checked that all the previous criteria have been met and can open a long trade.

Before we can open a trade we need to use our external variables to calculate our stop-loss and profit targets.

if (UseStopLoss) double LongStopLossLevel = Ask – (ATR * SLATRMultiplier) ; else LongStopLossLevel = 0.0;
if (UseTakeProfit) double LongTakeProfitLevel = Ask + (ATR * TPATRMultiplier) ; else LongTakeProfitLevel = 0.0;

The trade is opened using the function OrderSend. Our long trades are opened with the following:

ticket=OrderSend(Symbol(),OP_BUY,LotsTraded,Ask,Slippage,LongStopLossLevel,LongTakeProfitLevel,”Buy(#” + MagicNumber + “)”,MagicNumber,0,Green);
if(ticket>0)
Closing Positions

In our trading strategy, positions can be closed by crossing the EMA. The first thing we need to do is check that the EA currently has a position open. To do this we use for which sets up a cycle to count the number of open positions:

for(cnt=0;cnt<EATotal;cnt++)

If we have a position open, the OrderSelect function will find this position and select it.

OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

The OrderType function will then be used to check whether the open position is a long position or a short position.

OrderType()<=OP_SELL && OrderSymbol()==Symbol()

Our criteria for closing a long positions is:

if(Close1 < EMA1 && Close2 > EMA2)
Trailing Stop

A trailing stop can be useful for locking in profits. Our original trading strategy does not use a trailing stop, however we can use MT4 to see whether it could improve our profitability. The following code uses a series of if statements to check whether we are using a trailing stop and if so whether our stop-loss should be altered based on the latest price change.

if(UseTrailingStop)
{
if(Bid-OrderOpenPrice()>(TSATRMultiplierATR)) { if(OrderStopLoss()<Bid-(TSATRMultiplierATR))

The stop-loss is altered using the OrderModify function.

OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(TSATRMultiplier*ATR),OrderTakeProfit(),0,Green);

Trading Live – Caution!

This EA is a working model that can be used to backtest a trading strategy. However, if you intend to use a self-built EA for live trading you must first test it using a demo account. Doing this you will be able to see exactly how the EA operates and whether it causes any problems with other EAs or manual trading.

参考

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇