make it to ea by lotsize = 0.01, stop loss = middle band of bb at entry, take profit = 1.5 times of middle bb of entry
Assistant
Creating an expert advisor (EA) for MetaTrader using the specified trading strategy involves coding in MQL4 or MQL5, depending on the version of MetaTrader you are using. Below is a basic outline for an EA following your requirements, programmed in MQL4. This EA uses Bollinger Bands for entry and exit conditions, with a fixed lot size, and a set take profit and stop loss relative to the Bollinger Bands middle band.
Please ensure that you test any EA in a demo environment before using it in a live account. This code is a starting point and may need further optimization and testing.
mql4
User
Assistant
//+------------------------------------------------------------------+
//| BBStrategy.mq4 |
//| Copyright 2023 |
//| |
//+------------------------------------------------------------------+
#property strict
// Input parameters
input double Lots = 0.01;
input int TP_Factor = 150; // 1.5 times middle bb
input int BB_Period = 20;
input double BB_Deviation = 2;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double upperBand, middleBand, lowerBand;
int bbShift = 0;
// Calculate Bollinger Bands
middleBand = iBands(NULL, 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_MAIN, bbShift);
upperBand = iBands(NULL, 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_UPPER, bbShift);
lowerBand = iBands(NULL, 0, BB_Period, BB_Deviation, 0, PRICE_CLOSE, MODE_LOWER, bbShift);
// Check if there are open positions
if (OrdersTotal() == 0)
{
// Example: Buy order if current price crosses above middle band
if (Close[1] < middleBand && Close[0] > middleBand)
{
double takeProfit = middleBand + (middleBand * TP_Factor / 100);
double stopLoss = middleBand;
// Place buy order
int ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, stopLoss, takeProfit, "Buy Order", MAGIC_NUMBER, 0, Blue);
if (ticket < 0)
{
Print("Error opening buy order: ", GetLastError());
}
}
// Example: Sell order if current price crosses below middle band
if (Close[1] > middleBand && Close[0] < middleBand)
{
double takeProfit = middleBand - (middleBand * TP_Factor / 100);
double stopLoss = middleBand;
// Place sell order
int ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, 3, stopLoss, takeProfit, "Sell Order", MAGIC_NUMBER, 0, Red);
if (ticket < 0)
{
Print("Error opening sell order: ", GetLastError());
}
}
}
}
Summary of the EA:
Lot Size: The EA uses a fixed lot size of 0.01, adjustable with the Lots parameter.
Bollinger Bands: It calculates the middle band of Bollinger Bands for entry, stop loss, and take profit levels.
Stop Loss and Take Profit: The stop loss is set to the middle band value at entry. The take profit is 1.5 times the middle band value.
Order Conditions: Buy orders are triggered when the price crosses above the middle band, and sell orders are triggered when it crosses below.
Important Notes:
Magic Number: Add a unique magic number to differentiate orders placed by this EA from others.
Error Handling: The code should handle errors robustly, especially during order sending.
Testing: Thoroughly test this EA on historical data and a demo account to ensure it performs as expected.
Optimization: Consider adding features like slippage control, broader trading conditions, or risk management techniques.
Lastly, adapt and expand this template to accommodate your broader trading strategy and risk management practices.
//+------------------------------------------------------------------+
//| Indicator: BB_Cross.mq4 |
//| Created with EABuilder.com |
//| https://www.eabuilder.com |
//+------------------------------------------------------------------+
#property copyright "Created with EABuilder.com"
#property link "https://www.eabuilder.com"
#property version "1.00"
#property description ""
//+------------------------------------------------------------------+
//| 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[])
{
int limit = rates_total - prev_calculated;
//--- counting from 0 to rates_total
ArraySetAsSeries(Buffer1, true);
ArraySetAsSeries(Buffer2, true);
//--- initial zero
if (prev_calculated < 1)
{
ArrayInitialize(Buffer1, EMPTY_VALUE);
ArrayInitialize(Buffer2, EMPTY_VALUE);
}
else
limit++;
//--- main loop
for (int i = limit - 1; i >= 1; i--)
{
if (i >= MathMin(PLOT_MAXIMUM_BARS_BACK-1, rates_total-1-OMIT_OLDEST_BARS)) continue; //omit some old rates to prevent "Array out of range" or slow calculation
code
// Check for Buy signal
if (Close[i] > iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, i)
&& Close[i + 1] < iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_UPPER, i + 1)
&& !isBuySignal) // Only set if not already a buy signal
{
Buffer1[i] = Low[i] - iATR(NULL, PERIOD_CURRENT, 14, i);
if (i == 1 && Time[1] != time_alert) myAlert("indicator", "Buy"); // Alert on next bar open
isBuySignal = true;
isSellSignal = false; // Reset sell signal
time_alert = Time[1];
}
else
{
Buffer1[i] = EMPTY_VALUE;
}
// Check for Sell signal
if (Close[i] < iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, i)
&& Close[i + 1] > iBands(NULL, PERIOD_CURRENT, Period_BB, Deviations, 0, PRICE_CLOSE, MODE_LOWER, i + 1)
&& !isSellSignal) // Only set if not already a sell signal
{
Buffer2[i] = High[i] + iATR(NULL, PERIOD_CURRENT, 14, i);
if (i == 1 && Time[1] != time_alert) myAlert("indicator", "Sell"); // Alert on next bar open
isSellSignal = true;
isBuySignal = false; // Reset buy signal
time_alert = Time[1];
}
else
{
Buffer2[i] = EMPTY_VALUE;
}
}
To transform this custom indicator into an Expert Advisor (EA), we’ll create an EA script in MQL4 that uses signals from the indicator to automate trading. The original indicator looks for buy and sell conditions using Bollinger Bands and alerts when these conditions are met. In the EA, we’ll incorporate order execution logic based on these signals.
Below is a basic framework for converting this indicator into an EA. It includes logic to place buy and sell orders when the respective signals are detected. For simplicity, this example doesn't use indicator buffers directly, but you can integrate it with your own buffer logic if needed.
MetaTrader 4 MQL4 EA Code:
mql4
//+------------------------------------------------------------------+
//| BB_EA.mq4|
//| Copyright 2023 |
//| |
//+------------------------------------------------------------------+
#property strict
// Input parameters
input double Lots = 0.01;
input int Slippage = 3; // Slippage allowed in points
input int TP_Factor = 150;// Take profit factor (as percentage of middle band)
input int BB_Period = 20; // Bollinger Bands period
input double Deviations = 1; // Bollinger Bands deviations
// Variables for determining trade state
bool isPositionOpen = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate Bollinger Bands
double upperBand = iBands(NULL, 0, BB_Period, Deviations, 0, PRICE_CLOSE, MODE_UPPER, 1);
double lowerBand = iBands(NULL, 0, BB_Period, Deviations, 0, PRICE_CLOSE, MODE_LOWER, 1);
double middleBand = iBands(NULL, 0, BB_Period, Deviations, 0, PRICE_CLOSE, MODE_MAIN, 1);
// Read current and previous closing prices
double currentClose = iClose(NULL, 0, 0);
double previousClose = iClose(NULL, 0, 1);
// Check existing orders
if (OrdersTotal() > 0)
return; // Exit if there are any open orders or positions
// Check for buy signal
if (previousClose < upperBand && currentClose > upperBand)
{
double takeProfit = currentClose + (middleBand * TP_Factor / 100);
double stopLoss = upperBand;
int ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, stopLoss, takeProfit, "Buy order", 0, 0, Green);
if (ticket < 0)
Print("Error opening buy order: ", GetLastError());
}
// Check for sell signal
if (previousClose > lowerBand && currentClose < lowerBand)
{
double takeProfit = currentClose - (middleBand * TP_Factor / 100);
double stopLoss = lowerBand;
int ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, stopLoss, takeProfit, "Sell order", 0, 0, Red);
if (ticket < 0)
Print("Error opening sell order: ", GetLastError());
}
}
Explanation:
Lot Size: The EA uses a fixed lot size of 0.01, adjustable with the Lots parameter.
Signals: The EA places buy or sell orders based on the crossover of the current closing price with the upper or lower Bollinger Bands.
Stop Loss and Take Profit: These are set relative to the calculated Bollinger Bands. For TP, a factor of the middle band is used.
Order Management: The EA checks for existing orders and only places new ones when there are no open orders.
Things to Consider:
Backtesting and Optimization: Before deploying this EA, test it thoroughly in a demo account or using historical data backtesting to ensure it performs effectively.
Error Handling: The error handling is basic; consider expanding it for robustness in a live trading environment.
Risk Management: Integrate risk management strategies suitable for your trading approach.
Limitations: This is a basic implementation. You may wish to include various trading conditions and more sophisticated logic.
Remember, automated trading requires diligent monitoring and comprehensive understanding to manage effectively in live market environments.