Problem Description
Solution
Here is a complete, fully functional Expert Advisor (EA) for MetaTrader 4 based on your requirements.
Strategy Logic
- Entry Signal: Buy when the Tenkan-sen (Red line) crosses above the Kijun-sen (Blue line).
- Confirmation: The cross is confirmed on the close of the previous bar (Shift 1) to prevent "repainting" signals while the current candle is forming.
- Exit Strategy: The EA includes a fixed Stop Loss and Take Profit. Additionally, it includes logic to close the Buy position if a "Death Cross" (Tenkan crosses back below Kijun) occurs, ensuring you don't hold onto a reversing trend.
MQL4 Code
//+------------------------------------------------------------------+
//| Ichimoku_TK_EA.mq4 |
//| Copyright 2023, Quantitative Trading AI |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Quantitative Trading AI"
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- Input Parameters
input double InpLots = 0.1; // Lot size
input int InpStopLoss = 50; // Stop Loss in pips (0 = no SL)
input int InpTakeProfit = 100; // Take Profit in pips (0 = no TP)
input int InpSlippage = 3; // Maximum slippage in pips
input int InpMagicNumber = 12345; // Magic Number to identify orders
//--- Ichimoku Settings
input int InpTenkan = 9; // Tenkan-sen Period
input int InpKijun = 26; // Kijun-sen Period
input int InpSenkou = 52; // Senkou Span B Period
//--- Global Variables
double adjustedPoint;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Adjust point value for 3 and 5 digit brokers
if(Digits == 3 || Digits == 5)
adjustedPoint = Point * 10;
else
adjustedPoint = Point;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// 1. Check for Open Orders to manage Exits
ManageOpenOrders();
// 2. Check for New Entry Signals
if(CountOrders(OP_BUY) == 0) // Only open if no Buy exists
{
if(CheckBuySignal())
{
OpenBuyOrder();
}
}
}
//+------------------------------------------------------------------+
//| Check for Tenkan-sen crossing ABOVE Kijun-sen |
//+------------------------------------------------------------------+
bool CheckBuySignal()
{
// Get Ichimoku values for the previous closed candle (Shift 1)
double tenkan1 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_TENKANSEN, 1);
double kijun1 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_KIJUNSEN, 1);
// Get Ichimoku values for the candle before previous (Shift 2)
double tenkan2 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_TENKANSEN, 2);
double kijun2 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_KIJUNSEN, 2);
// Logic: Tenkan was below/equal Kijun previously, and is now above Kijun
if(tenkan2 <= kijun2 && tenkan1 > kijun1)
{
return(true);
}
return(false);
}
//+------------------------------------------------------------------+
//| Check for Tenkan-sen crossing BELOW Kijun-sen (Exit Signal) |
//+------------------------------------------------------------------+
bool CheckCloseSignal()
{
double tenkan1 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_TENKANSEN, 1);
double kijun1 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_KIJUNSEN, 1);
double tenkan2 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_TENKANSEN, 2);
double kijun2 = iIchimoku(NULL, 0, InpTenkan, InpKijun, InpSenkou, MODE_KIJUNSEN, 2);
// Logic: Tenkan was above/equal Kijun previously, and is now below
if(tenkan2 >= kijun2 && tenkan1 < kijun1)
{
return(true);
}
return(false);
}
//+------------------------------------------------------------------+
//| Open a Buy Order |
//+------------------------------------------------------------------+
void OpenBuyOrder()
{
double sl = 0, tp = 0;
// Calculate Stop Loss and Take Profit prices
if(InpStopLoss > 0)
sl = Ask - InpStopLoss * adjustedPoint;
if(InpTakeProfit > 0)
tp = Ask + InpTakeProfit * adjustedPoint;
// Normalize prices to prevent errors
sl = NormalizeDouble(sl, Digits);
tp = NormalizeDouble(tp, Digits);
int ticket = OrderSend(Symbol(), OP_BUY, InpLots, Ask, InpSlippage, sl, tp, "Ichimoku Buy", InpMagicNumber, 0, clrGreen);
if(ticket < 0)
{
Print("OrderSend failed with error #", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Manage Open Orders (Close if opposite signal occurs) |
//+------------------------------------------------------------------+
void ManageOpenOrders()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == InpMagicNumber)
{
if(OrderType() == OP_BUY)
{
// If Tenkan crosses below Kijun, close the Buy
if(CheckCloseSignal())
{
if(!OrderClose(OrderTicket(), OrderLots(), Bid, InpSlippage, clrRed))
{
Print("OrderClose failed with error #", GetLastError());
}
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Count open orders for this EA |
//+------------------------------------------------------------------+
int CountOrders(int type)
{
int count = 0;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == InpMagicNumber && OrderType() == type)
{
count++;
}
}
}
return(count);
}
//+------------------------------------------------------------------+
How to Install and Use
- Open MetaTrader 4.
- Press
F4to open the MetaEditor. - Click New -> Expert Advisor (template) -> Name it
Ichimoku_TK_EA. - Delete everything in the new file and paste the code provided above.
- Press
F7or click Compile. Ensure there are no errors in the "Errors" tab at the bottom. - Go back to the main MT4 terminal.
- Find
Ichimoku_TK_EAin the Navigator window under Expert Advisors. - Drag it onto a chart (e.g., EURUSD H1).
- Ensure AutoTrading is enabled in the top toolbar.
Key Features Explained
- 5-Digit Broker Support: The code automatically detects if your broker uses 5 decimal places (e.g., EURUSD 1.12345) and adjusts the pip calculations (
adjustedPoint) so that a 50 pip Stop Loss is calculated correctly as 500 points. - Magic Number: The
InpMagicNumberensures this EA only manages its own trades and does not interfere with manual trades or other EAs running on the same account. - Signal Logic:
MODE_TENKANSEN(1) andMODE_KIJUNSEN(2) are used within theiIchimokufunction.- It compares the values at
Shift 1(the last completed candle) andShift 2. This ensures the crossover has actually completed and won't disappear if the current price moves (repainting).
- Risk Management: You can set
InpStopLossandInpTakeProfitin the inputs. If you set them to 0, the EA will rely solely on the opposite crossover signal to close the trade.
Q&A
Q: Can I use this on any timeframe?
A: Yes, the EA uses Period() (0 in the code), which means it calculates based on the timeframe of the chart you attach it to. Ichimoku is traditionally most effective on H4 and Daily charts.
Q: Why does it check Shift 1 and Shift 2?
A: Checking Shift 0 (current candle) is risky because the lines move as the price ticks. A crossover might appear and disappear within the same candle. Checking Shift 1 ensures the candle has closed and the crossover is confirmed.
Q: Will this EA open Sell trades?
A: No. As per your request, this code specifically looks for the Buy signal (Tenkan > Kijun). However, it will close an existing Buy trade if a Sell signal (Tenkan < Kijun) appears.