!! [i] Darma_Bollatr

Author: darma
!! [i] Darma_Bollatr

This code implements a custom indicator in MQL4 (MetaQuotes Language 4), likely for use in the MetaTrader 4 trading platform. Let's break down what it does, its purpose, and potential improvements.

Overall Purpose

The indicator aims to identify potential trading opportunities based on price action relative to Bollinger Bands and Average True Range (ATR). It's designed to be used in a range-bound market strategy, where the trader looks to profit from price oscillations within a defined range. The code seems to be a starting point for a more complex trading system.

Code Breakdown

  1. Includes and Definitions:

    • The code doesn't have explicit #include statements, but it relies on built-in MQL4 functions and constants.
    • bandperiod: The period for calculating Bollinger Bands (default 15).
    • deviation: The standard deviation multiplier for Bollinger Bands (default 2).
    • period_atr: The period for calculating Average True Range (default 200).
    • multiplier: A multiplier used to extend the Bollinger Bands based on ATR (default 1.2). This creates wider bands.
    • show_fix_line: A boolean flag to control whether fixed lines are drawn (default 1, meaning they are shown).
    • fix_line: The distance (in points) for the fixed lines relative to the Bollinger Bands (default 14).
  2. init() Function:

    • This function is called once when the indicator is loaded.
    • It sets up the indicator's visual properties:
      • SetIndexStyle(): Defines the line style (DRAW_LINE, STYLE_DOT) and color for each index (data series).
      • SetIndexShift(): Sets the starting bar for the index.
      • SetIndexDrawBegin(): Sets the starting bar for drawing the index.
      • SetIndexBuffer(): Associates the index with the data array (e.g., upper with upper[]).
      • SetIndexLabel(): Sets the label displayed in the indicator's data window.
  3. deinit() Function:

    • This function is called when the indicator is removed from the chart. It's currently empty, but it's a good place to release any resources if the indicator were to allocate memory or create objects.
  4. start() Function:

    • This is the core of the indicator. It's called on every tick (or at a defined interval).
    • if (TimeCurrent() > StrToTime("2007.3.5 10:50")) { return; }: This is a crucial line. It prevents the indicator from running on bars before a specific date and time. This is likely for testing or development purposes, as it significantly reduces the calculation load. Remove this line for live trading.
    • limit = Bars - counted_bars;: Calculates the number of bars to process.
    • The for loop iterates through the bars:
      • middle[i] = iMA(NULL, 0, bandperiod, 0, MODE_SMA, PRICE_OPEN, i);: Calculates the Simple Moving Average (SMA) for the specified period.
      • boll_up[i] = iBands(NULL, 0, bandperiod, deviation, 0, PRICE_OPEN, MODE_UPPER, i);: Calculates the upper band of the Bollinger Bands.
      • boll_lw[i] = iBands(NULL, 0, bandperiod, deviation, 0, PRICE_OPEN, MODE_LOWER, i);: Calculates the lower band of the Bollinger Bands.
      • upper[i] = boll_up[i] + (multiplier * iATR(NULL, 0, period_atr, i+1));: Calculates the extended upper band by adding a multiple of the ATR to the upper Bollinger Band.
      • lower[i] = boll_lw[i] - (multiplier * iATR(NULL, 0, period_atr, i+1));: Calculates the extended lower band by subtracting a multiple of the ATR from the lower Bollinger Band.
      • The if (show_fix_line > 0) block calculates and draws fixed lines based on the upper and lower Bollinger Bands.

Potential Improvements and Considerations

  • Remove the Date Restriction: The if (TimeCurrent() > StrToTime("2007.3.5 10:50")) { return; } line must be removed for the indicator to function correctly on live data.
  • Error Handling: The code lacks error handling. For example, if iBands or iMA fails to calculate a value, it could lead to unexpected behavior. Consider adding checks for INVALID_HANDLE or other error codes.
  • Input Parameters: Make the parameters (bandperiod, deviation, period_atr, multiplier, show_fix_line, fix_line) user-adjustable through the indicator's input settings. This allows traders to optimize the indicator for different markets and timeframes. Use the input keyword in MQL4 to define these.
  • Alerts/Signals: Add logic to generate alerts or signals based on specific conditions, such as:
    • Price crossing the extended upper or lower bands.
    • The ATR expanding or contracting, which could indicate increased or decreased volatility.
  • Visual Enhancements:
    • Use different colors for the bands and lines to make them more visually distinct.
    • Add arrows or other markers to indicate potential trading opportunities.
  • Comments: Add more comments to explain the purpose of each section of the code.
  • Optimization: The indicator calculates values for every bar. Consider optimizing the code to reduce the calculation load, especially for high-frequency data.
  • Trading Strategy Integration: This indicator is a tool. It needs to be integrated into a complete trading strategy that includes risk management rules, position sizing, and entry/exit criteria.
  • Backtesting: Thoroughly backtest the indicator on historical data to evaluate its performance and identify potential weaknesses.

Example of Adding Input Parameters

extern int bandperiod = 15;
extern int deviation = 2;
extern int period_atr = 200;
extern double multiplier = 1.2;
extern int show_fix_line = 1;
extern int fix_line = 14;

This would create input parameters in the indicator's properties window, allowing the user to change the values without modifying the code.

In summary, this code provides a foundation for a custom indicator that combines Bollinger Bands and ATR. By addressing the points above, you can create a more robust, flexible, and useful tool for your trading. Remember to thoroughly test and optimize the indicator before using it in live trading.

Price Data Components
Series array that contains open time of each bar
Indicators Used
Moving average indicatorBollinger bands indicatorIndicator of the average true range
Miscellaneous
Implements a curve of type %1
7 Views
3 Downloads
0 Favorites
!! [i] Darma_Bollatr
//+----------------------------------------------------------------------------+
//|                                                        !!Darma_Bollatr.mq4 |
//|                                                             Coded by Darma |
//|                                                 for capturing range market |
//|                              trade the range when volatility is decreasing |
//+----------------------------------------------------------------------------+
//+----------------------------------------------------------------------------+
//|The idea was from Ron's bolltrade EA                                        |
//|He is a genius                                                              |
//|To avoid confusion, let me tell first:                                      |
//|This proposed trading system is different from Ron's bolltrade EA.          |
//|So do not try to match the entries from this proposed system                |
//|with Ron's Bolltrade entries.                                               |
//|Althought the idea of this proposed system was inspired by Ron's EA,        |
//|they are not matched, you may get confused                                  |
//+----------------------------------------------------------------------------+
//+----------------------------------------------------------------------------+


//+----------------------------------------------------------------------------+
//+----------------------------------------------------------------------------+
//|How to use this indicator into a trading system:                            |
//+----------------------------------------------------------------------------+
//|First is to determine decreasing volatility,                                |
//|place an ATR(30) on a >>>>15min<<<<< chart                                  |
//|Then overlay an SMA(30) on that ATR window.                                 |
//|When the ATR itself below its SMA,                                          |
//|then we have a decreasing volatility                                        |
//+----------------------------------------------------------------------------+
//|When we have decreasing volatility, we trade the range.                     |
//|That means: selling the top and buying the bottom.                          |
//|There are 2 kinds of top/bottom.                                            |
//|Example for top (bottom is the reverse):                                    |
//+----------------------------------------------------------------------------+
//|1st kind of top is:                                                         |
//|When the previous bar breaks the upper bollinger (green) band               |
//|and the current bar's high is not higher than the previous bar's high       |
//|Rules for selling this 1st kind of top:                                     |
//|Sell at next bar. Place limit sell order at current bar's pivot (H+L)/2     |
//+----------------------------------------------------------------------------+
//|2nd kind of top is:                                                         |
//|When the bar is touching the ATR (Blue) band                                |
//|Sell at market.                                                             |
//+----------------------------------------------------------------------------+
//|Initial SL is 4*ATR(500).                                                   |
//|For example: for eurusd, it will be arround 4*6 = 24 pips                   |
//|For gbpusd, it will be around 4*9 = 36 pips                                 |
//+----------------------------------------------------------------------------+
//|Exit trade when price touching either one of these levels:                  |
//|Exit #1: the level where the bollinger band is WHEN THE TRADE WAS ENTERED   |
//|Exit #2: moving average (middle bollinger band) that moves along the way    |
//+----------------------------------------------------------------------------+
//|                                                                            |
//|                                                                            |
//|Money Management ( VERY IMPORTANT!! )                                       |
//|"Risk 2% for each trade". What does this mean ?                             |
//|When having a 20pips SL and a 10k account,                                  |
//|a loss of 20 pips should decrease the account by a $200                     |
//|this will allow a $ 100,000 position = 1 standar lot = 10 mini lot          |
//|                                                                            |
//|                                                                            |
//+----------------------------------------------------------------------------+
//+----------------------------------------------------------------------------+
//|For more info please ask me at                                              |
//|indotraders.org or at the metatrader yahoogroups                            |
//+----------------------------------------------------------------------------+
//+----------------------------------------------------------------------------+



#property copyright "darma"
#property link      "http://risenberg.com"
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 7
#property indicator_color1 SteelBlue
#property indicator_color2 Sienna
#property indicator_color3 Green
#property indicator_color4 Green
#property indicator_color5 Green
#property indicator_color6 SteelBlue
#property indicator_color7 Sienna

extern int bandperiod      = 15;
extern int deviation       = 2; 
extern int period_atr      = 200;
extern double multiplier   = 1.2; 
extern bool show_fix_line  = 1;
extern int fix_line = 14;

double upper[], middle[], lower[], boll_up[], boll_lw[], upper_fix[], lower_fix[];

int init()
  {
   SetIndexStyle(0,DRAW_LINE,0,1);
   SetIndexShift(0,0);
   SetIndexDrawBegin(0,0);
   SetIndexBuffer(0,upper);
   SetIndexLabel(0,"UP Spike Bid");

   SetIndexStyle(1,DRAW_LINE,0,1);
   SetIndexShift(1,0);
   SetIndexDrawBegin(1,0);
   SetIndexBuffer(1,lower);
   SetIndexLabel(1,"DN Spike Bid");
   
   SetIndexStyle(2,DRAW_LINE,STYLE_DOT);
   SetIndexShift(2,0);
   SetIndexDrawBegin(2,0);
   SetIndexBuffer(2,middle);
   SetIndexLabel(2,"SMA");

   SetIndexStyle(3,DRAW_LINE);
   SetIndexShift(3,0);
   SetIndexDrawBegin(3,0);
   SetIndexBuffer(3,boll_up);
   SetIndexLabel(3,"Upper Boll");

   SetIndexStyle(4,DRAW_LINE);
   SetIndexShift(4,0);
   SetIndexDrawBegin(4,0);
   SetIndexBuffer(4,boll_lw);
   SetIndexLabel(4,"Lower Boll");   
   
   SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
   SetIndexShift(5,0);
   SetIndexDrawBegin(5,0);
   SetIndexBuffer(5,upper_fix);
   SetIndexLabel(5,"Upper Fix");   
   
   SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
   SetIndexShift(6,0);
   SetIndexDrawBegin(6,0);
   SetIndexBuffer(6,lower_fix);
   SetIndexLabel(6,"Lower Fix");   

//---- indicators
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//---- TODO: add your code here
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start() {

   if (TimeCurrent() > StrToTime("2007.3.5 10:50")) {
       return ;
       }

   int limit;
   int counted_bars=IndicatorCounted();
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
   limit=Bars-counted_bars;
   
   for(int i=0; i<limit; i++) {
      middle[i] = iMA(NULL, 0, bandperiod, 0, MODE_SMA, PRICE_OPEN, i);
      boll_up[i]= iBands(NULL, 0, bandperiod , deviation, 0, PRICE_OPEN, MODE_UPPER, i);
      boll_lw[i]= iBands(NULL, 0, bandperiod , deviation, 0, PRICE_OPEN, MODE_LOWER, i);
      upper[i]  = boll_up[i] + (multiplier * iATR(NULL, 0, period_atr, i+1));
      lower[i]  = boll_lw[i] - (multiplier * iATR(NULL, 0, period_atr, i+1));
      if (show_fix_line >0) 
      {
      upper_fix[i]= boll_up[i] + fix_line*Point;
      lower_fix[i]= boll_lw[i] - fix_line*Point;
      }
   }
   return(0);
  }
//+------------------------------------------------------------------+

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 ---