scurtrailma

Author: Scur
Indicators Used
Moving average indicator
0 Views
0 Downloads
0 Favorites
scurtrailma
//+------------------------------------------------------------------+
//|                                                  scurtrailma.mq5 |
//|                                                             Scur |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Scur"
#property version   "4.00"

#include <Indicators\Trend.mqh>
#include <Trade\Trade.mqh>

//--- input parameters
input group                "MA config"
input int                  TS_ma_period=20;                 // period of ma
input int                  TS_ma_shift=0;                   // shift
input ENUM_MA_METHOD       TS_ma_method=MODE_LWMA;          // type of smoothing
input ENUM_APPLIED_PRICE   TS_applied_price=PRICE_WEIGHTED; // type of price
input ENUM_TIMEFRAMES      TS_period=PERIOD_CURRENT;        // timeframe

string                     TS_SL_symbol=_Symbol;            // EA symbol
input group                "Trail options"
input int                  max_sl=100;                      // max sl applied to orders
input bool                 pre_init=true;                   // can close orders that exceed max_sl
input int                  MA_bars_trail=1;                 // distance in bars for the MA trailing signal
input int                  trail_below_MA=5;                // how many points below MA to set TS
input int                  trail_below_price=20;            // points below price to trail on positive
input int                  trail_below_negative=60;         // points below price to trail on negative

CiMA                       TS_MA;                           // MA management
int                        TS_handle;                       // MA handle

CTrade                     TS_trade;                        // trade management

MqlTradeRequest            TS_data;                         // position management
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {

//-----------------  sets indicator parameters
   MqlParam pars[4];
//--- period
   pars[0].type=TYPE_INT;
   pars[0].integer_value=TS_ma_period;
//--- shift
   pars[1].type=TYPE_INT;
   pars[1].integer_value=TS_ma_shift;
//--- type of smoothing
   pars[2].type=TYPE_INT;
   pars[2].integer_value=TS_ma_method;
//--- type of price
   pars[3].type=TYPE_INT;
   pars[3].integer_value=TS_applied_price;

//-----------------  tries to create the indicator
//   if(!TS_MA.Create(TS_SL_symbol, TS_period, IND_MA, 4, pars))
   if(!((CIndicator)TS_MA).Create(TS_SL_symbol, TS_period, IND_MA, 4, pars))
      return(INIT_FAILED);

//-----------------  gets the handle
   if((TS_handle = iMA(TS_SL_symbol, PERIOD_CURRENT, TS_ma_period, TS_ma_shift, TS_ma_method, TS_applied_price)) == INVALID_HANDLE)
      return(INIT_FAILED);

//-----------------  adds indicator to chart
   if(!ChartIndicatorAdd(0,0,TS_handle))
      return(INIT_FAILED);

//-----------------  refresh the chart
   TS_MA.Redrawer(true);

//---
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   string   short_name;

//-----------------  set the indicator name to search and terminate
   StringConcatenate(short_name, "MA(",TS_ma_period,")");
   ChartIndicatorDelete(0,0,short_name);
   IndicatorRelease(TS_handle);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   int totalorders = PositionsTotal();
   double   TS_bid,
            TS_ask,
            trail = 0,
            TS_MA_val;
   ulong    TS_ticket;
   bool     changed;

//-----------------  pre-calculates values based on inputs
   double   TS_maxsl = max_sl*_Point;
   double   TS_trailma = trail_below_MA*_Point;
   double   TS_trailprice = trail_below_price*_Point;
   double   TS_trailnegative = trail_below_negative*_Point;

//-----------------  refresh the chart
   TS_MA.Redrawer(true);
   TS_MA.Refresh();

//-----------------  get indicator value on defined distance
   TS_MA_val=TS_MA.Main(MA_bars_trail);

   if(totalorders>0)
     {
      for(int cnt=0 ; cnt<totalorders ; cnt++)
        {
         if(!OrderSelect(cnt))
           {
            TS_trade.Request(TS_data);

            //-----------------  if on current ea chart
            if(TS_data.symbol == TS_SL_symbol)
              {
               TS_ticket=PositionGetTicket(cnt);
               TS_bid=SymbolInfoDouble(TS_SL_symbol, SYMBOL_BID);
               TS_ask=SymbolInfoDouble(TS_SL_symbol, SYMBOL_ASK);
               changed=false;

               //-----------------  if buy order
               if((int)TS_data.type == 0)
                 {
                  //-----------------  case the current value exceeds max sl
                  if(TS_bid <= TS_data.price - TS_maxsl)
                    {
                     if(pre_init)
                        TS_trade.PositionClose(TS_ticket,1000);
                    }

                  //-----------------  check what value to assign to trail
                  if(TS_MA_val - TS_trailma >= TS_bid - TS_trailprice)
                     trail = TS_bid - TS_trailprice;
                  else
                     trail = TS_MA_val - TS_trailma;

                  //-----------------  if moving too close to current price
                  if(trail > TS_bid - TS_trailprice)
                     trail = TS_bid - TS_trailprice;

                  //-----------------  if trail still in the negative use the negative trail as new value
                  if(TS_data.price >= trail)
                     trail = TS_bid - TS_trailnegative;

                  //-----------------  compares the ts with trail to check if a change occurs
                  if((TS_data.sl < NormalizeDouble(trail, _Digits)) || TS_data.sl == 0)
                    {
                     trail = NormalizeDouble(trail, _Digits);
                     changed = true;
                    }
                 }

               //-----------------  if sell order
               if((int)TS_data.type == 1)
                 {
                  //-----------------  case the current value exceeds max sl
                  if(TS_ask >= TS_data.price + TS_maxsl)
                    {
                     if(pre_init)
                        TS_trade.PositionClose(TS_ticket,1000);
                    }

                  //-----------------  check what value to assign to trail
                  if(TS_MA_val + TS_trailma <= TS_ask + TS_trailprice)
                     trail = TS_ask + TS_trailprice;
                  else
                     trail = TS_MA_val + TS_trailma;

                  //-----------------  if moving too close to current price
                  if(trail < TS_ask + TS_trailprice)
                     trail = TS_ask + TS_trailprice;

                  //-----------------  if trail still in the negative use the negative trail as new value
                  if(TS_data.price <= trail)
                     trail = TS_bid + TS_trailnegative;

                  //-----------------  compares the ts with trail to check if a change occurs
                  if((TS_data.sl > NormalizeDouble(trail, _Digits)) || TS_data.sl == 0)
                    {
                     trail = NormalizeDouble(trail, _Digits);
                     changed = true;
                    }
                 }

               //-----------------  if there was a change update the position
               if(changed)
                  TS_trade.PositionModify(TS_ticket, trail, TS_data.tp);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---