FiboPivotCandleBar is a sophisticated trading tool designed to provide trading signals by combining several technical indicators, including Fibonacci levels, Pivot Points, ZigZag, MACD, and Moving Averages. Below is a breakdown of the main components and their functions:
Fibonacci Levels:
Function: Identify potential support and resistance levels based on the Fibonacci retracement levels. These levels are derived from the Fibonacci sequence and are used by traders to predict potential reversal points in the market.
Pivot Points:
Function: Calculate key price levels that are expected to act as support or resistance. These levels are computed from the high, low, and close prices of the previous trading period. Pivot Points help traders to anticipate the likely market turning points.
ZigZag Indicator:
Function: Highlight significant price changes, filtering out smaller movements and noise in the market. The ZigZag indicator connects significant tops and bottoms to identify the prevailing trend and potential reversal points.
MACD (Moving Average Convergence Divergence):
Function: Determine the momentum and trend direction by comparing different timeframes of moving averages. MACD consists of two exponential moving averages (EMA) and a histogram that indicates the difference between the MACD line and the signal line. It helps traders identify bullish and bearish market conditions.
Moving Averages:
Function: Smooth out price data to identify the trend direction over a specified period. Moving averages are used to filter out short-term fluctuations and provide a clearer view of the underlying trend.
By integrating these indicators, the FiboPivotCandleBar Multi-Currency EA generates trading signals that guide traders on when to enter and exit trades. The combination of these technical tools allows for a comprehensive analysis of the market, aiming to enhance trading accuracy and profitability.
Therefore, in this article I will not explain each function because you can see the explanation in the article A Comprehensive Guide to FiboPivotCandleBar: Functions and Performance of the Expert Advisor for MT5.
The differences in function and program writing between multi-currency and single-currency can be illustrated in the function example below:
Detailed explanation of the differences between the two functions:
In Multi-Currency Expert Advisor:
void MCEA::CurrentSymbolSet(const string symbol)
This function is designed for a Multi-Currency Expert Advisor. It takes a single parameter, symbol, which is a string representing the symbol of the financial instrument. Here are the steps it follows:
1. Set Symbol Name: It sets the name of the symbol using mc_symbol.Name(symbol)
2. Check Market Watch: It ensures the symbol is in the market watch using mc_symbol.CheckMarketWatch().
3. Synchronization: It checks if the symbol is synchronized with the server using mc_symbol.IsSynchronized().
4. Set Trade Type: It sets the trade type filling by symbol using mc_trade.SetTypeFillingBySymbol(symbol).
5. Refresh Symbol Data:It refreshes the symbol's data using mc_symbol.Refresh().
6. Refresh Rates: It refreshes the rates for the symbol using mc_symbol.RefreshRates().
In Single-Currency Expert Advisor:
void SFPCB::CurrentSymbolSet(void)
This function is designed for a Single-Currency Expert Advisor. It does not take any parameters. Instead, it uses a predefined symbol, SPC. Here are the steps it follows:
1. Set Symbol Name: It sets the name of the symbol using sc_symbol.Name(SPC).
2. Check Market Watch: It ensures the symbol is in the market watch using sc_symbol.CheckMarketWatch().
3. Synchronization: It checks if the symbol is synchronized with the server using sc_symbol.IsSynchronized().
4. Set Trade Type: It sets the trade type filling by symbol using sc_trade.SetTypeFillingBySymbol(SPC).
5. Refresh Symbol Data: It refreshes the symbol's data using sc_symbol.Refresh().
6. Refresh Rates: It refreshes the rates for the symbol using sc_symbol.RefreshRates().
Key Differences
1. Parameter Input:
MCEA::CurrentSymbolSet takes a parameter symbol as input, allowing dynamic setting of symbols.
SFPCB::CurrentSymbolSet does not take any parameters and uses a predefined symbol SPC.
2. Usage Context:
MCEA::CurrentSymbolSet is used in a Multi-Currency environment where the symbol can change dynamically based on the input parameter.
SFPCB::CurrentSymbolSet is used in a Single-Currency environment where the symbol is fixed and predefined.
3. Flexibility:
MCEA::CurrentSymbolSet offers more flexibility by allowing different symbols to be set at runtime.
SFPCB::CurrentSymbolSet is less flexible as it always operates on the same predefined symbol.
By understanding these differences, you can appreciate how each function is tailored to its specific use case within the context of multi-currency versus single-currency trading strategies.
Let's break down the ExpFPCB_MCEA_Config function of FiboPivotCandleBar Expert Advisor for MT5.
void MCEA::ExpFPCB_MCEA_Config(void)
This function configures an Expert Advisor (EA) for multi-currency trading. Below are the step-by-step processes within this function:
//+------------------------------------------------------------------+
//| Expert Configuration |
//+------------------------------------------------------------------+
void MCEA::ExpFPCB_MCEA_Config(void)
{
//---
//--
HandlingSymbolArrays(); // With this function we will handle all pairs that will be traded
//--
TFT05=PERIOD_M5;
TFT15=PERIOD_M15;
TFT30=PERIOD_M30;
TFT60=PERIOD_H1;
ENUM_TIMEFRAMES TFs[]={PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H2,PERIOD_H3,PERIOD_H4,PERIOD_H6,PERIOD_H8,PERIOD_H12,PERIOD_D1};
int arTFs=ArraySize(TFs);
//--
for(int x=0; x<arTFs; x++) if(tfinuse==x) TFt=TFs[x]; // TF for calculation signal
//--
//-- Indicators handle for all symbol
for(int x=0; x<arrsymbx; x++)
{
hMATrF[x]=iMA(DIRI[x],TFt,2,0,MODE_LWMA,PRICE_WEIGHTED);
hMATrS[x]=iMA(DIRI[x],TFt,20,0,MODE_SMA,PRICE_MEDIAN);
hiMA02[x]=iMA(DIRI[x],TFT15,2,0,MODE_EMA,PRICE_MEDIAN);
hiMA20[x]=iMA(DIRI[x],TFT15,20,0,MODE_SMA,PRICE_MEDIAN);
hiMACD[x]=iMACD(DIRI[x],TFT60,12,26,9,PRICE_CLOSE);
hZZm30[x]=iCustom(DIRI[x],TFT30,indiname,depth,devia,backs);
hZZm60[x]=iCustom(DIRI[x],TFT60,indiname,depth,devia,backs);
hPar05[x]=iSAR(DIRI[x],TFT05,SARstep,SARmaxi); //-- Handle for the iSAR indicator for M5 Timeframe
//--
}
//--
minprofit=NormalizeDouble(TSmin/100.0,2);
//--
ALO=(int)mc_account.LimitOrders()>sall ? sall : (int)mc_account.LimitOrders();
if(Close_by_Opps==No)
{
if((int)mc_account.LimitOrders()>=(sall*2)) ALO=sall*2;
else
ALO=(int)(mc_account.LimitOrders()/2);
}
//--
LotPS=(double)ALO;
maxSpread=maxsprd;
if(MQLInfoInteger(MQL_TESTER))
maxSpread=(int)SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
//--
mc_trade.SetExpertMagicNumber(magicEA);
mc_trade.SetDeviationInPoints(slip);
mc_trade.SetMarginMode();
Set_Time_Zone();
//--
return;
//---
} //-end ExpFPCB_MCEA_Config()
//---------//
Function Explanation
Detailed Breakdown:
1. Handling Symbol Arrays:
HandlingSymbolArrays(); This function manages all the pairs that will be traded.
This will be explained in more detail in the paragraphs below.
2. Timeframe Setup:
TFT05=PERIOD_M5;, TFT15=PERIOD_M15;, TFT30=PERIOD_M30;, TFT60=PERIOD_H1; Sets up several timeframe constants for later use.
3. Dynamic Timeframe Selection:
Creates an array of different timeframes:
ENUM_TIMEFRAMES TFs[]=PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H2,PERIOD_H3,PERIOD_H4,PERIOD_H6,PERIOD_H8,PERIOD_H12,PERIOD_D1};
Determines the size of the array: int arTFs=ArraySize(TFs);
Loops through the array to set the calculation timeframe (TFt) based on a condition:
for(int x=0; x<arTFs; x++) if(tfinuse==x) TFt=TFs[x];
4. Indicators Handling for All Symbols:
Iterates through each symbol in arrsymbx to initialize various indicators for each symbol:
//-- Indicators handle for all symbol
for(int x=0; x<arrsymbx; x++)
{
hMATrF[x]=iMA(DIRI[x],TFt,2,0,MODE_LWMA,PRICE_WEIGHTED);
hMATrS[x]=iMA(DIRI[x],TFt,20,0,MODE_SMA,PRICE_MEDIAN);
hiMA02[x]=iMA(DIRI[x],TFT15,2,0,MODE_EMA,PRICE_MEDIAN);
hiMA20[x]=iMA(DIRI[x],TFT15,20,0,MODE_SMA,PRICE_MEDIAN);
hiMACD[x]=iMACD(DIRI[x],TFT60,12,26,9,PRICE_CLOSE);
hZZm30[x]=iCustom(DIRI[x],TFT30,indiname,depth,devia,backs);
hZZm60[x]=iCustom(DIRI[x],TFT60,indiname,depth,devia,backs);
hPar05[x]=iSAR(DIRI[x],TFT05,SARstep,SARmaxi);
//--
}
//--
5. Profit Calculation:
Normalizes the minimum profit value: minprofit=NormalizeDouble(TSmin/100.0,2);
6. Account Limit Orders:
Sets the allowable limit orders (ALO) based on the account's limit and certain conditions:
The MCEA::ExpFPCB_MCEA_Config function is crucial for configuring a multi-currency Expert Advisor by setting up symbol arrays, timeframes, indicators, and trading parameters. It ensures that all required symbols and their respective indicators are prepared for trading, and it adjusts trading limits and parameters based on current market conditions and account settings.
This section of the function iterates through each symbol in the arrsymbx array to initialize various indicator handles for each symbol. The indicators used include Moving Averages (MA), Moving Average Convergence Divergence (MACD), Custom Indicator (ZZ), and Parabolic SAR (iSAR). Here’s a detailed breakdown:
1. Iteration Through Symbols:
The loop for(int x=0; x<arrsymbx; x++) iterates over all the symbols in the arrsymbx array.
Initializes the same custom indicator for the 60-minute timeframe with specified parameters.
Parabolic SAR (iSAR):
hPar05[x]=iSAR(DIRI[x],TFT05,SARstep,SARmaxi);
Initializes the Parabolic SAR indicator for the 5-minute timeframe with specified parameters (SARstep and SARmaxi).
Summary
The "Indicators Handling for All Symbols" loop is critical for setting up the necessary technical indicators for each symbol that the Expert Advisor will trade. By initializing these indicators, the function ensures that the EA has the required data to analyze market conditions and make informed trading decisions based on various timeframes and price calculations.
The "Trade on Specific Time" feature allows traders to align their trading activities with specific time zones. This is particularly useful for traders who want to focus on particular trading sessions, such as the London, New York, or Tokyo sessions.
By enabling this feature, the Expert Advisor can be configured to trade only during specific time frames, potentially reducing exposure to market volatility during less active periods.
Provides 2 options:
Trade on Specific Time = No;
Trade on Specific Time = Yes;
No Specific Time:
If "Trade on Specific Time Zone" is set to "No," the Expert Advisor will trade 24/5, from 00:15 to 23:59, based on the MT5 server time.
Specific Time Zones:
If "Trade on Specific Time Zone" is set to "Yes," the trader can select from the following options:
Custom Session:
Traders can specify custom start and end times for the trading session.
The EA will only execute trades within this specified time.
Predefined Sessions:
New Zealand Session: Trades during New Zealand trading hours.
Australia Sydney Session: Trades during Australian trading hours.
Asia Tokyo Session: Trades during Asian trading hours.
Europe London Session: Trades during European trading hours.
America New York Session: Trades during US trading hours.
Trading Session Duration Calculation:
For trades initiated during the New Zealand to New York session, the Expert Advisor calculates the duration of the trade, which can be useful for various trading strategies and analysis.
Function:MCEA::GoodMarginTrade function of FiboPivotCandleBar Multi-Currency Expert Advisor for MT5.
The GoodMarginTrade function is designed to check whether an order can be placed based on the available free margin in the trading account. It evaluates if the account has sufficient free margin to open a trade with specified parameters and triggers an alert if the margin is insufficient.
bool MCEA::GoodMarginTrade(const string symbol,ENUM_ORDER_TYPE _cmd,double lotsz,double atprice)
{
//---
bool goodmrgn=true;
//--
if((mc_account.FreeMarginCheck(symbol,_cmd,lotsz,atprice)<=0.0)||(mc_account.FreeMargin()<(mc_account.Equity()*maxmrgn/100))) goodmrgn=false;
//--
if(!goodmrgn)
{
string nomargn="Account Free Margin minimum has reached the specified limit, Order will not opened";
Do_Alerts(symbol,nomargn);
}
//--
return(goodmrgn);
//---
} //-end GoodMarginTrade()
//---------//
Parameters:
symbol: A string representing the trading symbol (e.g., "EURUSD").
_cmd: An enumeration (ENUM_ORDER_TYPE) indicating the type of order (e.g., buy, sell).
lotsz: A double value representing the lot size of the trade.
atprice: A double value indicating the price at which the order is to be placed.
Steps:
1. Initialize Margin Status:
bool goodmrgn=true;
A boolean variable goodmrgn is initialized to true, assuming the margin status is good by default.
The function checks two conditions to determine if the margin is insufficient:
a. If the free margin required to open the trade (FreeMarginCheck) is less than or equal to zero.
b. If the available free margin is less than a specified percentage (maxmrgn) of the account's equity.
If either condition is met, goodmrgn is set to false.
3. Alert if Margin is Insufficient:
//--
if(!goodmrgn)
{
string nomargn="Account Free Margin minimum has reached the specified limit, Order will not opened";
Do_Alerts(symbol,nomargn);
}
//--
If goodmrgn is false (meaning the margin is insufficient), an alert message is created and sent using the Do_Alerts function.
4. Return Margin Status:
return(goodmrgn);
The function returns the value of goodmrgn, indicating whether the margin is sufficient (true) or insufficient (false).
Summary
The GoodMarginTrade function is essential for ensuring that trades are only placed when there is sufficient free margin in the account. It helps prevent margin calls and potential losses by checking the margin requirements before executing any trade orders. If the margin is insufficient, it alerts the user and prevents the order from being opened.
Function:MCEA::CheckSpread
The CheckSpread function is designed to check whether the spread for a given trading symbol is within an acceptable limit. If the spread exceeds the maximum allowed spread, the function triggers an alert.
Parameters:
symbol: A string representing the trading symbol (e.g., "EURUSD").
Steps:
1. Initialize Spread Allowance:
bool allow_spread=false;
A boolean variable allow_spread is initialized to false, assuming the spread is not allowed by default.
2. Get Symbol Index:
int x=PairsIdxArray(symbol);
The function calls PairsIdxArray(symbol) to get the index of the symbol in the pairs array.
3. Set Current Symbol:
CurrentSymbolSet(symbol);
Calls CurrentSymbolSet(symbol) to set up the current symbol context for subsequent operations.
Calculates the spread for the symbol by subtracting the bid price from the ask price and normalizing the result.
5. Check Spread Against Maximum Allowed Spread:
allow_spread=spreadx[x] <= maxSpread*pip;
Compares the calculated spread (spreadx[x]) with the maximum allowed spread (maxSpread multiplied by pip).
Sets allow_spread to true if the spread is within the acceptable limit, otherwise false
6. Trigger Alert if Spread is Too High:
//--
if(!allow_spread)
{
string bigspread="Spread in "+symbol+" is greater than maximum spread limit.";
Do_Alerts(symbol,bigspread);
}
//--
If allow_spread is false (meaning the spread is too high), an alert message is created and sent using the Do_Alerts function.
7. Return Spread Allowance Status:
return(allow_spread);
The function returns the value of allow_spread, indicating whether the spread is within the acceptable limit (true) or not (false).
Summary
The CheckSpread function is essential for ensuring that trades are only placed when the spread for a given symbol is within an acceptable limit. By checking the spread before executing any trade orders, the function helps to prevent trades with excessively high costs, thereby safeguarding the trading account. If the spread is too high, it alerts the user and prevents the order from being opened.
1. The Challenge of Multi-Currency Trading.
When dealing with a multi-currency Expert Advisor that trades multiple pairs on a single chart, managing and monitoring individual pair performance can be cumbersome.
The Solution: A Dedicated Button Panel.
A well-designed button panel can significantly enhance the trading experience. By providing quick access to different chart symbols and timeframes, traders can:
Monitor Individual Pair Performance: Easily switch between charts to assess the accuracy of entry and exit signals.
React to Market Changes: Quickly identify opportunities and risks in specific pairs.
Optimize Trading Strategies: Fine-tune strategies based on real-time market data.
Key Features of an Effective Button Panel:
Symbol Selection: A dropdown menu or a list of buttons to quickly switch between different currency pairs.
Timeframe Selection: Options to adjust the timeframe for each symbol, allowing for different time-frame analysis.
Chart Navigation: Buttons to navigate between charts.
Order Management: A clear overview of open and closed orders, including profit and loss information on that currency.
2. Manual Order Management.
Several manual buttons have been incorporated into this multi-currency expert advisor to enhance efficiency and effectiveness for traders in monitoring the advisor's operations.
Set SL / TP All Orders
This button is beneficial if the trader has initially set the parameters to Use Order Stop Loss (No) and/or Use Order Take Profit (No), but later decides to apply Stop Loss or Take Profit to all orders. By clicking the "Set SL / TP All Orders" button, all orders will be adjusted, and a Stop Loss and/or Take Profit will be implemented across the board.
Close All Orders
If a trader wants to close all orders, they can simply click on the "Close All Orders" button to close all open orders.
Close All Orders Profit
If a trader wishes to close all orders that are currently profitable, they can click on the "Close All Orders Profit" button to close all open orders that have generated profit.
3. Managing Orders and Chart Symbols.
For multi-currency expert advisors that trade 30 pairs using only one chart symbol, having a button panel for all symbols would be highly beneficial and convenient. This feature would allow traders to switch between chart timeframes or symbols with a single click, enabling them to quickly assess the accuracy of the indicator signal when the expert advisor opens or closes an order.
4. Expert Timeframe, Pair Selection, and Symbol Management
Expert Timeframe.
The Expert Timeframe setting determines the timeframe on which the Expert Advisor will calculate indicators and generate trading signals. By default, it's set to PERIOD_H1, meaning the EA will analyze hourly data.
Adjusting this setting can influence the sensitivity of the strategy to market movements. A shorter timeframe, like PERIOD_M15 or PERIOD_M30, can lead to more frequent signals, while a longer timeframe, like PERIOD_H4 or PERIOD_D1, can produce fewer, but potentially more reliable signals.
Pair Selection.
The Select Pairs to Trade property allows traders to choose from a predefined list of currency pairs. The default option is typically to trade all 30 pairs, but traders can customize this selection based on their preferences and risk tolerance.
Symbol Management with HandlingSymbolArrays
The HandlingSymbolArray function plays a crucial role in managing the symbols that the Expert Advisor will trade.
To perform the following tasks:
Symbol Initialization: Initializes an array to store the selected symbols.
Symbol Filtering: Filters the selected symbols based on market conditions or other criteria.
Symbol Validation: Ensures that the selected symbols are valid and supported by the trading platform.
Symbol Assignment: Assigns the selected symbols to the Expert Advisor's internal variables.
By effectively managing symbols, the EA can optimize its performance and reduce the risk of errors.
Validating Pair (Symbol) Names and Error Handling.
The Expert Advisor's ability to validate pair names is a critical feature to ensure smooth operation and prevent potential errors.
Here's a breakdown of how this process might work:
User Input: The trader enters a list of desired pairs in the Expert Advisor's input parameters.
Symbol Check: The EA iterates through each pair name and checks its validity:
Symbol Existence: The EA verifies if the specified symbol exists in the trading platform's symbol
Symbol Format: The EA ensures that the symbol adheres to the correct format (e.g., EURUSD, GBPUSD, XAUUSD).
Error Handling:
If a symbol is invalid, the EA generates a warning message in the journal or displays an alert to the trader and the EA will removed from the chart.
By incorporating robust symbol validation and error handling, the Expert Advisor can maintain its reliability and prevent unexpected issues.
Function:OnChartEvent
The OnChartEvent function handles various chart events, particularly focusing on click events for specific buttons on the chart. This allows for interactive actions based on user input.
Parameters:
id: An integer representing the event ID.
lparam: A long parameter associated with the event.
dparam: A double parameter associated with the event.
sparam: A string parameter associated with the event.
Steps:
1. Reset Error State:
ResetLastError();
Resets any previous error states to start fresh.
2. Set Current Timeframe:
ENUM_TIMEFRAMES CCS=mc.TFt;
Retrieves the current timeframe setting from the mc object.
3. Handle Object Click Events:
Checks if the event ID is CHARTEVENT_OBJECT_CLICK, indicating a click on a chart object.
if(id==CHARTEVENT_OBJECT_CLICK) { int lensymbol=StringLen(Symbol()); int lensparam=StringLen(sparam);
4. Button Click Handling:
"Set SL/TP All Orders" Button:
If this button is clicked, it sets Stop Loss (SL) and Take Profit (TP) for all orders.
//--- if "Set SL All Orders" button is click
if(sparam=="Set SL/TP All Orders")
{
mc.SetSLTPOrders();
Alert("-- "+mc.expname+" -- ",Symbol()," -- Set SL/TP All Orders");
//--- unpress the button
ObjectSetInteger(0,"Set SL/TP All Orders",OBJPROP_STATE,false);
ObjectSetInteger(0,"Set SL/TP All Orders",OBJPROP_ZORDER,0);
CreateManualPanel();
}
"Close All Order" Button:
If this button is clicked, it closes all open orders.
//--- if "Close All Order" button is click
if(sparam=="Close All Order")
{
mc.CloseAllOrders();
Alert("-- "+mc.expname+" -- ",Symbol()," -- Close All Orders");
//--- unpress the button
ObjectSetInteger(0,"Close All Order",OBJPROP_STATE,false);
ObjectSetInteger(0,"Close All Order",OBJPROP_ZORDER,0);
CreateManualPanel();
}
"Close All Profit" Button:
If this button is clicked, it closes all profitable orders.
//--- if "Close All Profit" button is click
if(sparam=="Close All Profit")
{
mc.ManualCloseAllProfit();
Alert("-- "+mc.expname+" -- ",Symbol()," -- Close All Profit");
//--- unpress the button
ObjectSetInteger(0,"Close All Profit",OBJPROP_STATE,false);
ObjectSetInteger(0,"Close All Profit",OBJPROP_ZORDER,0);
CreateManualPanel();
}
"X" Button:
If this button is clicked, it deletes all button, label, and rectangle label objects and resets the panel state.
//--- if "X" button is click
if(sparam=="X")
{
ObjectsDeleteAll(0,0,OBJ_BUTTON);
ObjectsDeleteAll(0,0,OBJ_LABEL);
ObjectsDeleteAll(0,0,OBJ_RECTANGLE_LABEL);
//--- unpress the button
ObjectSetInteger(0,"X",OBJPROP_STATE,false);
ObjectSetInteger(0,"X",OBJPROP_ZORDER,0);
//--
DeleteButtonX();
mc.PanelExtra=false;
DisplayManualButton();
}
"M" Button:
If this button is clicked, it toggles the manual panel.
//--- if "M" button is click
if(sparam=="M")
{
//--- unpress the button
ObjectSetInteger(0,"M",OBJPROP_STATE,false);
ObjectSetInteger(0,"M",OBJPROP_ZORDER,0);
mc.PanelExtra=true;
CreateManualPanel();
}
"C" Button:
If this button is clicked, it creates the symbol panel.
//--- if "C" button is click
if(sparam=="C")
{
//--- unpress the button
ObjectSetInteger(0,"C",OBJPROP_STATE,false);
ObjectSetInteger(0,"C",OBJPROP_ZORDER,0);
mc.PanelExtra=true;
CreateSymbolPanel();
}
"R" Button:
If this button is clicked, it removes the Expert Advisor from the chart.
//--- if "R" button is click
if(sparam=="R")
{
Alert("-- "+mc.expname+" -- ",Symbol()," -- expert advisor will be Remove from the chart.");
ExpertRemove();
//--- unpress the button
ObjectSetInteger(0,"R",OBJPROP_STATE,false);
ObjectSetInteger(0,"R",OBJPROP_ZORDER,0);
if(!ChartSetSymbolPeriod(0,Symbol(),Period()))
ChartSetSymbolPeriod(0,Symbol(),Period());
DeletePanelButton();
ChartRedraw(0);
}
5. Symbol Button Click:
If the length of sparam matches the length of the symbol name, it validates the symbol and changes the chart symbol.
//--- if Symbol button is click
if(lensparam==lensymbol)
{
int sx=mc.ValidatePairs(sparam);
ChangeChartSymbol(mc.AS30[sx],CCS);
mc.PanelExtra=false;
}
6. Return Statement:
Ensures the function exits cleanly.
return;
Summary
The OnChartEvent function is crucial for handling user interactions with the chart. By managing clicks on specific buttons, it allows for dynamic actions such as setting SL/TP, closing orders, toggling panels, and changing symbols. This enhances the usability and interactivity of the trading platform.
ChangeChartSymbol Function.
The ChangeChartSymbol function is designed to change the symbol and timeframe of the current chart in the MetaTrader platform. This function also handles resetting and redrawing the chart by unpressing buttons and deleting specific objects.
Parameters:
c_symbol: A string representing the new trading symbol (e.g., "EURUSD") to be set on the chart.
cstf: An enumeration (ENUM_TIMEFRAMES) indicating the new timeframe to be set for the chart.
Deletes all objects of type button (OBJ_BUTTON), label (OBJ_LABEL), and rectangle label (OBJ_RECTANGLE_LABEL) from the chart to reset the chart's visual elements.
3. Set Chart Symbol and Timeframe:
ChartSetSymbolPeriod(0, c_symbol, cstf);
Changes the chart's symbol to c_symbol and sets the timeframe to cstf.
4. Redraw the Chart:
ChartRedraw(0);
Forces the chart to redraw to reflect the changes made, ensuring the new symbol and timeframe are properly displayed.
5. Return Statement:
return;
Ensures the function exits cleanly.
Summary
The ChangeChartSymbol function is a crucial utility for dynamically changing the trading symbol and timeframe of a chart in MetaTrader. By unpressing buttons, deleting specific objects, setting the new symbol and timeframe, and redrawing the chart, it ensures a smooth transition and clear presentation of the updated chart.
Thank you for reading this article How to create a FiboPivotCandleBar Expert Advisor that trades Multi-Currency for MT5.
See you in the next article on Expert Advisor programs or indicators for MetaTrader 4 and MetaTrader 5.
If you are subscribed to my YouTube Channel, and would like to receive the source program of this article, please send a request via the Contact Us form page, and I will send it to your email, source code: ExpFPCB_MCEA.mq5.
Don't forget to stop by and subscribe to Forex Home Experts YouTube Channel:
FiboPivotCandleBar is a sophisticated trading tool designed to provide trading signals by combining several technical indicators, including Fibonacci levels, Pivot Points, ZigZag, MACD, and Moving Averages indicators. Below is a breakdown of the main components and their functions:
Fibonacci Levels:
Function: Identify potential support and resistance levels based on the Fibonacci retracement levels. These levels are derived from the Fibonacci sequence and are used by traders to predict potential reversal points in the market.
Pivot Points:
Function: Calculate key price levels that are expected to act as support or resistance. These levels are computed from the high, low, and close prices of the previous trading period. Pivot Points help traders to anticipate the likely market turning points.
ZigZag Indicator:
Function: Highlight significant price changes, filtering out smaller movements and noise in the market. The ZigZag indicator connects significant tops and bottoms to identify the prevailing trend and potential reversal points.
MACD (Moving Average Convergence Divergence):
Function: Determine the momentum and trend direction by comparing different timeframes of moving averages. MACD consists of two exponential moving averages (EMA) and a histogram that indicates the difference between the MACD line and the signal line. It helps traders identify bullish and bearish market conditions.
Moving Averages:
Function: Smooth out price data to identify the trend direction over a specified period. Moving averages are used to filter out short-term fluctuations and provide a clearer view of the underlying trend.
By integrating these indicators, the FiboPivotCandleBar EA generates trading signals that guide traders on when to enter and exit trades. The combination of these technical tools allows for a comprehensive analysis of the market, aiming to enhance trading accuracy and profitability.
Metadata Section: This section provides essential information about the EA, including the author, version, and description. It also includes warnings about potential risks in trading.
Properties: The #property directives are used to specify metadata and configuration options for the EA, such as copyright information, version number, and description.
//+------------------------------------------------------------------+
//| ExpFPCB_MT5.mq5 |
//| Copyright 2024, Roberto Jacobs (3rjfx) ~ Date: 2024-12-04 |
//| https://www.mql5.com/en/users/3rjfx |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Roberto Jacobs (3rjfx) ~ Date: 2024-12-04"
#property link "https://www.mql5.com/en/users/3rjfx"
#property version "1.00"
#property strict
#property description "The Expert ExpFPCB_MT5 is the Automated Trading Forex Expert Advisor for MetaTrader 5."
#property description "version: 1.00 ~ Update number: 1 ~ Last update: 2024/12/05 @17:03 (PM) WIT (Western Indonesian Time)"
#property description "WARNING:"
#property description "In any case the author is not liable for any damage or loss whatsoever."
#property description "Sometimes high profits can be disrupted by a row of losses."
#property description "In the Forex online trading, it is impossible to always profit."
//#property icon "\\Images\\ExpFPCB_MT5.ico";
//+------------------------------------------------------------------+
>
Includes: These lines include various MQL5 library files that provide functions and classes for trading operations (CTrade), position information (CPositionInfo), symbol information (CSymbolInfo), account information (CAccountInfo), and moving averages calculations. These libraries make it easier to develop trading strategies by providing pre-built functionalities.
Class Instances: These lines create instances of the CTrade, CSymbolInfo, CPositionInfo, and CAccountInfo classes. These instances will be used to manage trades, obtain symbol-specific data, retrieve information about open positions, and get account-related information respectively.
This initial setup ensures your EA has all the necessary components to manage trading operations efficiently.
Enumerations (Enums)
Enums are used to define a set of named constants. They make the code more readable and easier to manage. In your code, several enums are defined for different purposes:
Trading Sessions (tm_zone):
Cus_Session: Custom Session
New_Zealand: New Zealand Session
Australia: Australia Sydney Session
Asia_Tokyo: Asia Tokyo Session
Europe_London: Europe London Session
US_New_York: US New York Session
This enum allows the EA to select different trading sessions based on predefined zones.
Trading Hours (swhour): This enum represents hours of the day (0 to 23). Each constant corresponds to a specific hour, from hr_00 (00:00) to hr_23 (23:00). It helps in specifying trading hours.
Minutes (inmnt): This enum represents specific minutes within an hour at 5-minute intervals.
For example:
mn_00: Minute 0
mn_05: Minute 5
mn_10: Minute 10, and so on.
Yes/No Options (YN):
No = 0
Yes= 1
This enum is a simple binary choice often used for enabling or disabling options.
Money Management Types (mmt):
FixedLot: Fixed Lot Size
DynamLot: Dynamic Lot Size
This enum specifies whether the EA uses a fixed lot size or a dynamic lot size based on account balance or risk parameters.
Timeframes (TFUSE): This enum represents different timeframes for trading:
TFM5: 5-minute period
TFM15: 15-minute period
TFM30: 30-minute period
TFH1: 1-hour period
TFH2: 2-hour period, and so on.
These constants allow the EA to switch between different trading timeframes.
These enums help structure of EA's code, making it more modular and easier to maintain.
The input keyword is used to define variables that can be configured by the user. These input parameters allow for flexible adjustment of the EA's behavior without modifying the code.
1. Global Strategy EA Parameters:
input group "=== Global Strategy EA Parameter ==="; // Global Strategy EA Parameter
input double TPmin = 25; // Input Trailing Profit Value in Pips
input YN Close_by_Opps = Yes; // Close Trade By Opposite Signal (Yes) or (No)
input YN SaveOnRev = Yes; // Close Trade and Save profit due to weak signal (Yes) or (No)
Parameters for managing stop loss (SL), take profit (TP), and trailing stop loss (TS).
Options to automatically calculate SL and TP values.
Enable or disable closing trades by opposite signals or weak signals.
6. Other Expert Advisor Parameters:
input group "=== Others Expert Advisor Parameter ==="; // Others EA Parameter
input YN alerts = Yes; // Display Alerts / Messages (Yes) or (No)
input YN UseEmailAlert = No; // Email Alert (Yes) or (No)
input YN UseSendnotify = No; // Send Notification (Yes) or (No)
input YN trade_info_display = Yes; // Select Display Trading Info on Chart (Yes) or (No)
input ulong magicEA = 20241204; // Expert ID (Magic Number)
Parameters for alerts, email notifications, and display of trading information on the chart.
Unique ID for the EA (Magic Number) to distinguish its trades from others.
These input parameters provide a flexible way for users to customize the behavior of the EA without modifying the code itself. This ensures that the EA can adapt to different trading strategies and preferences.
//+------------------------------------------------------------------+
//| Class for working Expert Advisor |
//+------------------------------------------------------------------+
class SFPCB
{
//---
private:
//----
int x_year; // Year
int x_mon; // Month
int x_day; // Day of the month
int x_hour; // Hour in a day
int x_min; // Minutes
int x_sec; // Seconds
//--
int oBm,
oSm,
ldig;
//--- Variables used in prefix and suffix symbols
int posCur1,
posCur2;
int inpre,
insuf;
string pre,suf;
//--- Variables are used in Trading Time Zone
int ishour,
onhour;
int tftrlst,
tfcinws;
datetime rem,
znop,
zncl,
zntm;
datetime SesCuOp,
SesCuCl,
Ses01Op,
Ses01Cl,
Ses02Op,
Ses02Cl,
Ses03Op,
Ses03Cl,
Ses04Op,
Ses04Cl,
Ses05Op,
Ses05Cl,
SesNoOp,
SesNoCl;
//--
string tz_ses,
tz_opn,
tz_cls;
//--
string tmopcu,
tmclcu,
tmop01,
tmcl01,
tmop02,
tmcl02,
tmop03,
tmcl03,
tmop04,
tmcl04,
tmop05,
tmcl05,
tmopno,
tmclno;
//----------------------
//-- zigzag param
int depth; // Depth
int devia; // Deviation
int backs; // Backstep
//--
double LotPS;
double point;
double slv,
tpv,
pip,
xpip;
double SARstep,
SARmaxi;
double floatprofit,
fixclprofit;
//--
string hariini,
daytrade,
trade_mode;
//--
double OPEN[],
HIGH[],
LOW[],
CLOSE[];
datetime TIME[];
datetime closetime;
//--
//------------
//------------
void Set_Time_Zone(void);
void Time_Zone(void);
bool Trade_session(void);
string PosTimeZone(void);
int ThisTime(const int reqmode);
int ReqTime(datetime reqtime,const int reqmode);
//--
int DirectionMove(const ENUM_TIMEFRAMES stf);
int CombineIndicators(void);
int PARSAR05(void);
int LotDig(void);
int ZigZagDirection(const ENUM_TIMEFRAMES ztf);
int MA5Trend(void);
int WeightedClosePrice(void);
int BarDirection(const ENUM_TIMEFRAMES stf);
int PricePercentMove(const ENUM_TIMEFRAMES stf,int shift);
//--
bool CheckProfit(ENUM_POSITION_TYPE intype);
bool CheckLoss(ENUM_POSITION_TYPE intype);
//--
double MLots(void);
double NonZeroDiv(double val1,double val2);
double OrderSLSet(ENUM_ORDER_TYPE type,double atprice);
double OrderTPSet(ENUM_ORDER_TYPE type,double atprice);
double TSPrice(ENUM_POSITION_TYPE ptype,int TS_type);
//--
string ReqDate(int d,int h,int m);
string TF2Str(ENUM_TIMEFRAMES period);
string timehr(int hr,int mn);
string TradingDay(void);
string AccountMode(void);
string GetCommentForOrder(void) { return(expname); }
//------------
public:
//---
//-- ExpFPCB_MCEA Config --
//--
string expname;
string indiname;
string SPC;
//--
int hMATrF,
hMATrS;
int hiMA02,
hiMA20;
int hiMACD;
int hZZm30,
hZZm60;
int hPar05;
int ALO,
dgts;
int arper;
ulong slip;
//--
double profitb,
profits;
double minprofit;
//--
int Buy,
Sell;
int ccur,
psec,
xtto,
checktml;
int OpOr,xob,xos;
//--
int year, // Year
mon, // Month
day, // Day
hour, // Hour
min, // Minutes
sec, // Seconds
dow, // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)
doy; // Day number of the year (January 1st is assigned the number value of zero)
//--
ENUM_TIMEFRAMES TFt,
TFT15,
TFT30,
TFT60,
TFT05;
//--
datetime PbarB,
TbarB,
PbarS,
TbarS;
//------------
SFPCB(void);
~SFPCB(void);
//------------
//--
virtual void ExpFPCB_Config(void);
virtual void ExpertActionTrade(void);
//--
void SetSymbolNamePS(void);
void CurrentSymbolSet(void);
void Pips(void);
void TradeInfo(void);
void Do_Alerts(string msgText);
void CheckOpenPMx(void);
void CheckClose(void);
void TodayOrders(void);
void UpdatePrice(ENUM_TIMEFRAMES xtf);
void RefreshPrice(ENUM_TIMEFRAMES xtf,int bars);
//--
bool RefreshTick(void);
bool TradingToday(void);
bool OpenBuy(void);
bool OpenSell(void);
bool ModifySLTP(int TS_type);
bool CloseAllProfit(void);
bool CheckProfitLoss(void);
bool CloseBuyPositions(void);
bool CloseSellPositions(void);
bool IFNewBarsB(void);
bool IFNewBarsS(void);
//--
int GetOpenPosition(void);
int GetCloseInWeakSignal(int exis);
//--
string getUninitReasonText(int reasonCode);
//--
//------------
//---
}; //-end class SFPCB
//---------//
SFPCB sc;
The SFPCB class encapsulates all the functions and variables necessary for the Expert Advisor. This object-oriented approach helps in organizing the code efficiently.
Private Variables:
These variables are only accessible within the class and are used for various calculations and configurations.
The constructor SFPCB::SFPCB(void) initializes various member variables when an object of the SFPCB class is created. Here's a detailed breakdown of the variables and their initial values:
1. Date and Time Initialization:
x_year, x_mon, x_day, x_hour, x_min, x_sec: All set to 0, representing the year, month, day, hour, minute, and second.
year, mon, day, hour, min, sec, dow, doy: Initial values for year (0), month (1), day (2), hour (3), minute (4), second (5), day of week (6), and day of year (7).
2. Trading and Indicator Initialization:
psec, Buy, Sell: Set to 0, 1, and -1, respectively. Buy and Sell likely represent trading signals.
checktml: Set to 0, used to check whether algorithmic trading is allowed or prohibited on MetaTrader 5.
SARmaxi, SARstep: Parabolic SAR indicator parameters, set to 0.2 and 0.02, respectively.
expname: The name of the Expert Advisor, set to "ExpFPCB_MT5".
indiname: The name of the ZigZag indicator file, set to "ZigZag.ex5".
closetime: Initialized with the current time using TimeCurrent().
Destructor
The destructor SFPCB::~SFPCB(void) is called when an object of the SFPCB class is destroyed. In this case, it does not perform any specific operations but is defined to allow for potential cleanup tasks if needed in the future.
Summary
The constructor initializes all necessary variables for the Expert Advisor to function correctly, ensuring all parameters are set to their initial values. The destructor ensures any resources used by the EA can be released appropriately, although in this case, it doesn't perform any specific actions.
Let's break down the ExpFPCB_Config method of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::ExpFPCB_Config(void)
void SFPCB::ExpFPCB_Config(void)
{
//---
//--
// Retrieve and set the symbol name
SPC=Symbol();
SetSymbolNamePS();
//--
// Define various timeframes
TFT05=PERIOD_M5;
TFT15=PERIOD_M15;
TFT30=PERIOD_M30;
TFT60=PERIOD_H1;
ENUM_TIMEFRAMES TFs[]={PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H2,PERIOD_H3,PERIOD_H4,PERIOD_H6,PERIOD_H8,PERIOD_H12,PERIOD_D1};
int arTFs=ArraySize(TFs);
//--
// Set the timeframe to be used based on user selection
for(int x=0; x<arTFs; x++) if(tfinuse==x) TFt=TFs[x];
//--
// Initialize indicator handles
hMATrF=iMA(SPC,TFt,2,0,MODE_LWMA,PRICE_WEIGHTED);
hMATrS=iMA(SPC,TFt,20,0,MODE_SMA,PRICE_MEDIAN);
hiMA02=iMA(SPC,TFT15,2,0,MODE_EMA,PRICE_MEDIAN);
hiMA20=iMA(SPC,TFT15,20,0,MODE_SMA,PRICE_MEDIAN);
hiMACD=iMACD(SPC,TFT60,12,26,9,PRICE_CLOSE);
hZZm30=iCustom(SPC,TFT30,indiname,depth,devia,backs);
hZZm60=iCustom(SPC,TFT60,indiname,depth,devia,backs);
hPar05=iSAR(SPC,TFT05,SARstep,SARmaxi);
//--
// Normalize minimum profit
minprofit=NormalizeDouble(TSmin/100.0,2);
//--
// Get account limit orders
ALO=(int)sc_account.LimitOrders();
//--
// Set lot size based on account limit orders
LotPS=(double)ALO;
//--
// Configure trading settings
sc_trade.SetExpertMagicNumber(magicEA);
sc_trade.SetDeviationInPoints(slip);
sc_trade.SetMarginMode();
//--
// Set the time zone for trading sessions
Set_Time_Zone();
//--
return;
//---
} //-end ExpFPCB_Config()
//---------//
This function is responsible for setting up and configuring the main parameters and indicators of the Expert Advisor (EA).
Here’s a detailed step-by-step explanation of what each part of the code does:
Function Explanation.
Detailed Breakdown:
1. Symbol Configuration:
Retrieve Symbol: The Symbol() function gets the current symbol name.
2. Timeframe Definition:
Timeframe Variables: TFT05, TFT15, TFT30, and TFT60 are set to their respective timeframes.
Array of Timeframes: An array TFs is defined containing various timeframes.
Set User-Selected Timeframe: The loop sets TFt to the timeframe selected by the user (tfinuse).
3. Indicator Initialization:
Moving Averages: Various moving averages (iMA) are initialized with different parameters.
MACD: The MACD indicator handle is initialized.
Custom Indicator (ZigZag): Handles for the custom ZigZag indicator are initialized.
Parabolic SAR: The handle for the Parabolic SAR indicator is initialized for the M5 timeframe.
4. Profit Normalization:
Normalize Minimum Profit: minprofit is normalized to two decimal places.
5. Account Configuration:
Limit Orders: The number of limit orders is retrieved from the account.
Set Lot Size: LotPS is set based on the account's limit orders.
6. Trading Settings:
Magic Number: The EA's magic number is set for trade identification.
Deviation: The trade deviation in points is set.
Margin Mode: The margin mode for the trades is set.
7. Time Zone Configuration:
Set Time Zone: The time zone for trading sessions is set by calling Set_Time_Zone().
Summary
This method configures various parameters and indicators necessary for the proper functioning of the Expert Advisor. It sets up the symbol, timeframes, indicator handles, trading settings, and time zones, ensuring the EA is ready to operate according to the user’s specifications.
Let's break down the SetSymbolNamePS method of FiboPivotCandleBar Expert Advisor for MT5.
sym_Lenpre, sym_Lensuf: Length of the prefix and suffix.
sym_pre, sym_suf: Strings for the prefix and suffix.
insymbol: Current symbol name.
inlen: Length of the current symbol name.
toseek, pairx: Used to find the position of the currency in the symbol.
dep, bel, sym_use: Used for extracting parts of the symbol.
xcur: Array of major currencies.
xcar: Size of the xcur array.
2. Search for Currency Pair:
The loop iterates through the xcur array to find the currency pair in the symbol name. If found, pairx is set to the index of the currency.
3. Extract Symbol Parts:
Based on the position found (toseek), the code extracts the relevant parts of the symbol (dep and bel) to form sym_use.
4. Determine Prefix and Suffix:
The length and position of the prefix and suffix are determined. The prefix and suffix are set based on the extracted symbol parts and filtered to remove any major currency names that might be mistakenly included.
5. Set Prefix and Suffix:
pre, suf: Set the prefix and suffix strings.
inpre, insuf: Set the length of the prefix and suffix.
posCur1, posCur2: Positions related to the currency pair in the symbol name.
Summary
The SetSymbolNamePS method ensures that the correct symbol name is set with the appropriate prefix and suffix. It identifies the major currency pair in the symbol, extracts the necessary parts, and sets the prefix and suffix accordingly. This is crucial for accurate identification and manipulation of trading symbols in the EA.
Let's explain the OnInit function of FiboPivotCandleBar Expert Advisor for MT5 in detail:
int OnInit()
Function Explanation
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
// Initialize the Expert Advisor configuration
sc.ExpFPCB_Config();
//--
// Indicate successful initialization
return(INIT_SUCCEEDED);
//---
}
//---------//
Detailed Breakdown:
Call to Configuration Function:g>
sc.ExpFPCB_Config(): This line calls the ExpFPCB_Config function defined within the SFPCB class (represented by the sc object). This function configures various parameters and indicators necessary for the Expert Advisor to function correctly.
2. Return Initialization Status:
return(INIT_SUCCEEDED): This line returns the status of the initialization. INIT_SUCCEEDED is a predefined constant in MQL5 that indicates the Expert Advisor has initialized successfully.
Summary
The OnInit function is the starting point of the Expert Advisor. It calls the configuration function to set up the necessary environment and then returns a success status. This ensures that all required parameters and settings are in place before the EA begins its operation.
Let's break down the OnDeinit function of FiboPivotCandleBar Expert Advisor for MT5 in detail:
void OnDeinit(const int reason)
Function Explanation.
The OnDeinit function is called when the Expert Advisor is deinitialized, which happens when the EA is removed from the chart or when the terminal is shut down. This function handles the cleanup process, ensuring that all resources are properly released.
Comment(""): Clears any comments that are displayed on the chart.
2. Release Indicator Handles:
IndicatorRelease(sc.hMATrF), IndicatorRelease(sc.hMATrS), etc.: These lines release the handles for all the indicators used by the EA. This is crucial to free up resources and avoid memory leaks.
3. Print Deinitialization Reason:
PrintFormat("%s: Deinitialization reason code=%d", __FUNCTION__, reason): This prints the function name and the deinitialization reason code to the terminal for logging purposes.
Print(sc.getUninitReasonText(reason)): This prints a human-readable explanation of the deinitialization reason using the getUninitReasonText method.
Summary
The OnDeinit function is essential for cleaning up when the Expert Advisor is deinitialized. It releases all indicator handles, removes any chart comments, prints the deinitialization reason, and deletes all objects from the chart. This ensures that the EA leaves no residual data or resources, maintaining a clean and efficient environment.
Let's break down the OnTick function of FiboPivotCandleBar Expert Advisor for MT5.
void OnTick(void)
This is the main function that gets called on every tick (i.e., whenever there is a change in price) in the MetaTrader 5 platform. Here’s a detailed breakdown of each part of the code:
The `OnTick` function is the core of any Expert Advisor (EA) in MetaTrader 5. It is executed every time there is a new price quote for the financial instrument the EA is attached to.
2. Call to `ExpertActionTrade:
sc.ExpertActionTrade();`: This line calls the `ExpertActionTrade` method of the `sc` object. This method likely contains the logic for making trading decisions based on the current market conditions.
3. Return Statement:
`return;`: This ensures the function exits cleanly after executing the trading logic.
Summary
The `OnTick` function is crucial for the operation of the Expert Advisor as it processes incoming price data. Each tick triggers a call to `sc.ExpertActionTrade()`, where the core trading logic is executed. This setup ensures the EA responds immediately to market changes.
Let's break down the ExpertActionTrade function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::ExpertActionTrade(void)
This function contains the main logic for executing trades based on the signals and conditions defined within the Expert Advisor. Here’s a detailed breakdown of each part of the code:
void SFPCB::ExpertActionTrade(void)
{
//---
//--Check Trading Terminal
ResetLastError();
//--
if(!MQLInfoInteger(MQL_TRADE_ALLOWED) && sc.checktml==0) //-- Check whether MT5 Algorithmic trading is Allow or Prohibit
{
sc.Do_Alerts("Trading Expert at "+SPC+" are NOT Allowed by Setting.");
sc.checktml=1; //-- Variable checktml is given a value of 1, so that the alert is only done once.
return;
}
//--
if(trade_info_display==Yes) sc.TradeInfo(); //-- Displayed Trading Info on Chart
//---
//--
int mcsec=sc.ThisTime(sc.sec);
//--
if(fmod((double)mcsec,5.0)==0) sc.ccur=mcsec;
//--
if(sc.ccur!=sc.psec)
{
//--
sc.CurrentSymbolSet();
//--
if(sc.TradingToday() && sc.Trade_session())
{
//--
sc.OpOr=sc.GetOpenPosition(); //-- Get trading signals to open positions
//-- //-- and store in the variable OpOr[x]
if(sc.OpOr==sc.Buy) //-- If variable OpOr[x] get result of GetOpenPosition(symbol) as "Buy" (value=1)
{
//--
sc.CheckOpenPMx();
//--
if(Close_by_Opps==Yes && sc.xos>0) sc.CloseSellPositions();
//--
if(sc.xob==0 && sc.xtto<sc.ALO && sc.IFNewBarsB()) {sc.OpenBuy(); sc.PbarB=sc.TbarB;}
else
if(sc.xtto>=sc.ALO)
{
//--
sc.Do_Alerts("Maximum amount of open positions and active pending orders has reached"+
"n the limit = "+string(sc.ALO)+" Orders ");
//--
sc.CheckOpenPMx();
//--
if(sc.xos>0 && sc.profits<-1.02 && sc.xob==0) {sc.CloseSellPositions(); sc.OpenBuy();}
else
sc.CloseAllProfit();
}
}
if(sc.OpOr==sc.Sell) //-- If variable OpOr[x] get result of GetOpenPosition(symbol) as "Sell" (value=-1)
{
//--
sc.CheckOpenPMx();
//--
if(Close_by_Opps==Yes && sc.xob>0) sc.CloseBuyPositions();
//--
if(sc.xos==0 && sc.xtto<sc.ALO && sc.IFNewBarsS()) {sc.OpenSell(); sc.PbarS=sc.TbarS;}
else
if(sc.xtto>=sc.ALO)
{
//--
sc.Do_Alerts("Maximum amount of open positions and active pending orders has reached"+
"n the limit = "+string(sc.ALO)+" Orders ");
//--
sc.CheckOpenPMx();
//--
if(sc.xob>0 && sc.profitb<-1.02 && sc.xos==0) {sc.CloseBuyPositions(); sc.OpenSell();}
else
sc.CloseAllProfit();
}
}
}
//--
sc.CheckOpenPMx();
//--
if(sc.xtto>0)
{
//--
if(SaveOnRev==Yes) //-- Close Trade and Save profit due to weak signal (Yes)
{
sc.CheckOpenPMx();
if(sc.profitb>sc.minprofit && sc.xob>0 && sc.GetCloseInWeakSignal(sc.Buy)==sc.Sell)
{
sc.CloseBuyPositions();
sc.Do_Alerts("Close BUY order "+SPC+" to save profit due to weak signal.");
}
if(sc.profits>sc.minprofit && sc.xos>0 && sc.GetCloseInWeakSignal(sc.Sell)==sc.Buy)
{
sc.CloseSellPositions();
sc.Do_Alerts("Close SELL order "+SPC+" to save profit due to weak signal.");
}
}
//--
if(TrailingSLTP==Yes) //-- Use Trailing SL/TP (Yes)
{
if(autotrl==Yes) sc.ModifySLTP(1); //-- If Use Automatic Trailing (Yes)
if(autotrl==No) sc.ModifySLTP(0); //-- If Use Automatic Trailing (No)
}
}
//--
sc.CheckOpenPMx();
if(Close_by_Opps==No && (sc.xob+sc.xos>1))
{
sc.CheckProfitLoss();
sc.Do_Alerts("Close order due stop in loss.");
}
//--
sc.CheckClose();
}
//--
sc.psec=sc.ccur;
//--
return;
//---
} //-end ExpertActionTrade()
//---------//
Function Explanation
Detailed Breakdown:
1. Check Trading Terminal:
ResetLastError(): Resets the last error code.
2. Check if Algorithmic Trading is Allowed:
Checks if algorithmic trading is allowed. If not, an alert is shown, and the process stops to prevent repeated alerts.
3. Display Trading Info on Chart:
If enabled, displays trading information on the chart.
4. Get Current Seconds:
Retrieves the current seconds using ThisTime.
5. Update Current Seconds Every 5 Seconds:
Updates the ccur variable every 5 seconds.
6. Check if Seconds Have Changed:
If the seconds have changed (ccur != psec), proceeds to trading logic.
7. Set Current Symbol for Trading:
Sets the current symbol for trading using CurrentSymbolSet.
8. Check if Trading is Allowed Today and Within Trading Session:
Checks if trading is allowed on the current day and within the trading session.
9. Get Trading Signals to Open Positions:
Retrieves trading signals using GetOpenPosition and stores the result in OpOr.
10. If Signal is to Buy:
Checks conditions to open buy positions, closes sell positions if required, and opens buy positions if conditions are met.
11. If Signal is to Sell:
Checks conditions to open sell positions, closes buy positions if required, and opens sell positions if conditions are met.
12. Check Open Positions:
Checks the status of open positions.
13. Close Trades and Save Profit Due to Weak Signal:
If enabled, closes trades and saves profit if weak signals are detected.
14. Use Trailing Stop Loss/Take Profit:
If enabled, uses trailing stop loss/take profit.
15. Check Profit and Loss Conditions:
Checks profit and loss conditions and closes orders if necessary.
16. Update Seconds:
Updates the psec variable with the current seconds.
Summary
The ExpertActionTrade function is the core trading logic of the Expert Advisor. It checks various conditions, retrieves trading signals, opens or closes positions based on those signals, and manages open positions. This ensures that the EA trades according to the defined strategy and rules.
Let's break down the UpdatePrice function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::UpdatePrice(ENUM_TIMEFRAMES xtf)
This function updates the price data arrays used by the Expert Advisor for a given timeframe. Here’s a detailed breakdown of each part of the code:
void SFPCB::UpdatePrice(ENUM_TIMEFRAMES xtf)
{
//---
//--
ArrayFree(OPEN);
ArrayFree(HIGH);
ArrayFree(LOW);
ArrayFree(CLOSE);
ArrayFree(TIME);
//--
ArrayResize(OPEN,arper,arper);
ArrayResize(HIGH,arper,arper);
ArrayResize(LOW,arper,arper);
ArrayResize(CLOSE,arper,arper);
ArrayResize(TIME,arper,arper);
//--
ArraySetAsSeries(OPEN,true);
ArraySetAsSeries(HIGH,true);
ArraySetAsSeries(LOW,true);
ArraySetAsSeries(CLOSE,true);
ArraySetAsSeries(TIME,true);
//--
ArrayInitialize(OPEN,0.0);
ArrayInitialize(HIGH,0.0);
ArrayInitialize(LOW,0.0);
ArrayInitialize(CLOSE,0.0);
ArrayInitialize(TIME,0);
//--
RefreshPrice(xtf,arper);
//--
int co=CopyOpen(SPC,xtf,0,arper,OPEN);
int ch=CopyHigh(SPC,xtf,0,arper,HIGH);
int cl=CopyLow(SPC,xtf,0,arper,LOW);
int cc=CopyClose(SPC,xtf,0,arper,CLOSE);
int ct=CopyTime(SPC,xtf,0,arper,TIME);
//--
return;
//---
} //-end UpdatePrice()
//---------//
Function Explanation
Detailed Breakdown:
1. Free Previously Allocated Arrays:
ArrayFree(OPEN), ArrayFree(HIGH), ArrayFree(LOW), ArrayFree(CLOSE), ArrayFree(TIME): These lines free the memory allocated for the arrays to ensure there are no memory leaks and to prepare for new data.
2. Resize Arrays:
ArrayResize(OPEN, arper, arper), etc.: These lines resize the arrays to hold arper number of elements. The arper variable is indeed the number of bars (periods) used to resize the arrays in the UpdatePrice function. This ensures the arrays can hold the necessary amount of price data for analysis.
3. Set Arrays as Series:
ArraySetAsSeries(OPEN, true), etc.: These lines set the arrays to be indexed as series, meaning the most recent data is at the lowest index. This is typical in time series data.
4. Initialize Arrays:
ArrayInitialize(OPEN, 0.0), etc.: These lines initialize the arrays with default values (0.0 for price data, 0 for time data) to ensure they start with clean data.
5. Refresh Price Data:
RefreshPrice(xtf, arper): This call updates the price data for the specified timeframe (xtf) and number of periods (arper). This ensures the EA works with the latest available data.
6. Copy Price Data:
CopyOpen(SPC, xtf, 0, arper, OPEN), etc.: These lines copy the open, high, low, close, and time data from the terminal to the arrays. The CopyOpen, CopyHigh, CopyLow, CopyClose, and CopyTime functions retrieve the respective data for the specified symbol (SPC), timeframe (xtf), and number of periods (arper).
Summary
The UpdatePrice function is crucial for updating the price data arrays used by the Expert Advisor. It ensures that the EA has the latest price information by freeing old data, resizing and initializing arrays, refreshing the data, and copying the new data into the arrays. This process is essential for accurate analysis and decision-making in the trading logic.
Let's break down the RefreshPrice function of FiboPivotCandleBar Expert Advisor for MT5.
This function retrieves and refreshes the price data for the specified symbol and timeframe, storing it in an array of MqlRates structures. Here’s a detailed breakdown of each part of the code:
MqlRates parray[]: This declares an array of MqlRates structures. Each MqlRates structure contains information about the open, high, low, close prices, volume, and time for each bar.
2. Set the Array as Series:
ArraySetAsSeries(parray, true): This sets the array as a series, meaning it will be indexed from the end (most recent data first). This is typical for handling time series data.
3. Copy Price Data:
CopyRates(SPC, xtf, 0, bars, parray): This function copies the price data for the specified symbol (SPC), timeframe (xtf), and number of bars (bars) into the parray array. It starts from the most recent bar (index 0) and copies the specified number of bars into the array. The function returns the number of bars successfully copied.
Summary
The RefreshPrice function is essential for updating the price data used by the Expert Advisor. It retrieves the latest price data for the specified symbol and timeframe, stores it in an array, and ensures the data is ready for analysis and decision-making. This process is critical for accurate trading based on up-to-date market information.
Let's break down the RefreshTick function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::RefreshTick(void)
This function checks and refreshes the tick data for the specified symbol. Here’s a detailed breakdown of each part of the code:
sc_symbol.Name(SPC): This line sets the name of the symbol for the symbol object sc_symbol using the symbol name stored in SPC.
2. Refresh Rates:
if(sc_symbol.RefreshRates()) return(true): This line attempts to refresh the rates (price data) for the symbol. If successful, it returns true.
3. Return False if Refresh Fails:
return(false): If the rates could not be refreshed, this line returns false.
Summary
The RefreshTick function is crucial for ensuring that the Expert Advisor works with the most recent tick data. It updates the tick data for the specified symbol and returns true if the update is successful, or false if it fails. This ensures that the EA makes trading decisions based on the latest market information.
Let's break down the CurrentSymbolSet function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::CurrentSymbolSet(void)
This function sets up the current trading symbol, ensuring it is fully prepared and synchronized for trading activities. Here’s a detailed breakdown of each part of the code:
sc_symbol.Name(SPC): This line sets the name of the symbol for the symbol object sc_symbol using the symbol name stored in SPC.
2. Check Market Watch:
sc_symbol.CheckMarketWatch(): This ensures that the symbol is listed in the Market Watch. If the symbol is not present, it adds it to the Market Watch.
3. Check Synchronization:
sc_symbol.IsSynchronized(): This checks if the symbol data is synchronized with the server. Synchronized data is essential for accurate trading operations.
4. Set Order Filling Type:
sc_trade.SetTypeFillingBySymbol(SPC): This sets the type of order filling allowed for the symbol, ensuring that the EA uses the correct method for executing trades.
5. Refresh Symbol Data:
sc_symbol.Refresh(): This refreshes the symbol to get the latest data, including trading conditions and symbol properties.
6. Refresh Rates:
sc_symbol.RefreshRates(): This refreshes the price data (rates) for the symbol to ensure the EA has the most current market information.
Summary
The CurrentSymbolSet function is crucial for setting up the current trading symbol. It ensures that the symbol is in the Market Watch, synchronized, and refreshed with the latest data. Additionally, it sets the correct order filling type, making sure that the EA is prepared to trade accurately and efficiently.
Let's break down the Pips function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::Pips(void)
This function sets up the pip value and related parameters for the trading symbol. Here’s a detailed breakdown of each part of the code:
CurrentSymbolSet(): Calls the CurrentSymbolSet function to ensure the symbol is set up and synchronized.
2. Get the Point Value and Number of Digits for the Symbol:
point = sc_symbol.Point(): Retrieves the point value of the symbol, which represents the minimum price change.
dgts = (int)sc_symbol.Digits(): Retrieves the number of digits after the decimal point for the symbol.
3. Set Pip Value:
xpip = 10.0: Sets a multiplier for the pip value.
pip = point * xpip: Calculates the pip value using the point value and the multiplier.
Summary
The Pips function calculates and sets the pip value for the trading symbol. It first ensures that the symbol is correctly set and synchronized, then retrieves the point value and the number of digits for the symbol. Finally, it calculates the pip value using a predefined multiplier. This setup is crucial for accurate pip calculations in trading operations.
Let's break down the IFNewBarsB function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::IFNewBarsB(void)
This function checks for the presence of a new bar in the timeframe being used to make buy orders. Here’s a detailed breakdown of each part of the code:
bool SFPCB::IFNewBarsB(void) // New bar check buy order
{
//---
bool Nb=false;
//--
TbarB=iTime(SPC,TFt,0);
if(TbarB!=PbarB) Nb=true;
//--
return(Nb);
//---
} //-end IFNewBarsB()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Return Variable:
bool Nb = false;: Initializes a boolean variable Nb to false. This variable will indicate whether a new bar is detected.
2.Get Current Bar Time:
TbarB = iTime(SPC, TFt, 0);: This line retrieves the opening time of the most recent bar in the specified timeframe (TFt) for the symbol (SPC). The iTime function gets the opening time of the bar at the given index (in this case, the most recent bar at index 0).
3. Check for New Bar:
if(TbarB != PbarB) Nb = true;: This line compares the current bar time (TbarB) with the previous bar time (PbarB). If they are different, it means a new bar has appeared, and Nb is set to true.
4. Return Result:
return(Nb);: Returns the value of Nb, indicating whether a new bar has been detected.
Summary
The IFNewBarsB function is used to detect the presence of a new bar for making buy orders. It compares the time of the most recent bar with the time of the previous bar. If they are different, it indicates that a new bar has appeared, and the function returns true. This detection is crucial for the EA to make trading decisions based on new market data.
Let's break down the IFNewBarsS function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::IFNewBarsS(void)
bool SFPCB::IFNewBarsS(void) // New bar check sell order
{
//---
bool Nb=false;
//--
TbarS=iTime(SPC,TFt,0);
if(TbarS!=PbarS) Nb=true;
//--
return(Nb);
//---
} //-end IFNewBarsS()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Return Variable:
bool Nb = false;: Initializes a boolean variable Nb to false. This variable will indicate whether a new bar is detected.
2. Get Current Bar Time:
TbarS = iTime(SPC, TFt, 0);: This line retrieves the opening time of the most recent bar in the specified timeframe (TFt) for the symbol (SPC). The iTime function gets the opening time of the bar at the given index (in this case, the most recent bar at index 0).
3. Check for New Bar:
if(TbarS != PbarS) Nb = true;: This line compares the current bar time (TbarS) with the previous bar time (PbarS). If they are different, it means a new bar has appeared, and Nb is set to true.
4. Return Result:
return(Nb);: Returns the value of Nb, indicating whether a new bar has been detected.
Summary
The IFNewBarsS function is used to detect the presence of a new bar for making sell orders. It compares the time of the most recent bar with the time of the previous bar. If they are different, it indicates that a new bar has appeared, and the function returns true. This detection is crucial for the EA to make trading decisions based on new market data.
Let's break down the DirectionMove function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::DirectionMove(const ENUM_TIMEFRAMES stf)
This function determines the price direction (up or down) of the most recent bar in the specified timeframe. Here’s a detailed breakdown of each part of the code:
int SFPCB::DirectionMove(const ENUM_TIMEFRAMES stf) // Bar Price Direction
{
//---
int ret=0;
int rise=1,
down=-1;
//--
Pips();
double difud=sc_symbol.NormalizePrice(1.5*pip);
UpdatePrice(stf);
//--
if(CLOSE[0]>OPEN[0]+difud) ret=rise;
if(CLOSE[0]<OPEN[0]-difud) ret=down;
//--
return(ret);
//---
} //-end DirectionMove()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result indicating the direction of the bar. It's initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) directions.
2. Calculate Pip Value:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
3. Normalize Price Difference:
double difud = sc_symbol.NormalizePrice(1.5 * pip);: Calculates a normalized price difference (difud) of 1.5 pips. This value is used to determine if the bar has moved significantly up or down.
4. Update Price Data:
UpdatePrice(stf);: Calls the UpdatePrice function to update the price data for the specified timeframe (stf).
5. Determine Direction:
if(CLOSE[0] > OPEN[0] + difud) ret = rise;: If the close price of the most recent bar (CLOSE[0]) is greater than the open price plus the normalized difference (OPEN[0] + difud), it indicates a rising bar, so ret is set to rise (1).
if(CLOSE[0] < OPEN[0] - difud) ret = down;: If the close price of the most recent bar (CLOSE[0]) is less than the open price minus the normalized difference (OPEN[0] - difud), it indicates a falling bar, so ret is set to down (-1).
6. Return Result:
return(ret);: Returns the direction of the bar (1 for rise, -1 for down, and 0 if no significant movement).
Summary
The DirectionMove function determines the direction of the most recent bar in the specified timeframe. It calculates the pip value, normalizes the price difference, updates the price data, and then checks if the bar's close price is significantly higher or lower than its open price to determine the direction. This function is essential for identifying market trends and making trading decisions.
Let's break down the BarDirection function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::BarDirection(const ENUM_TIMEFRAMES stf)
This function determines the price direction of the most recent bar in the specified timeframe using the Linear Weighted Moving Average (LWMA). Here’s a detailed breakdown of each part of the code:
int SFPCB::BarDirection(const ENUM_TIMEFRAMES stf) // LWMA Price Direction on Bar
{
//---
int ret=0;
int rise=1,
down=-1;
int br=2;
double LWMA2T[];
ArrayResize(LWMA2T,br,br);
ArraySetAsSeries(LWMA2T,true);
CopyBuffer(hMATrF,0,0,br,LWMA2T);
//--
UpdatePrice(stf);
//--
if(OPEN[0]<LWMA2T[0]) ret=rise;
if(OPEN[0]>LWMA2T[0]) ret=down;
//--
return(ret);
//---
} //-end BarDirection()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result indicating the direction of the bar. It's initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) directions.
int br = 2;: Specifies the number of bars to use for the LWMA calculation.
2. Create and Resize LWMA Array:
double LWMA2T[];: Declares an array to hold LWMA values.
ArrayResize(LWMA2T, br, br);: Resizes the array to hold br number of elements.
ArraySetAsSeries(LWMA2T, true);: Sets the array as a series, meaning it will be indexed from the end (most recent data first).
3. Copy LWMA Values to Array:
CopyBuffer(hMATrF, 0, 0, br, LWMA2T);: Copies the LWMA values from the indicator buffer (hMATrF) to the array. This gets the LWMA values for the specified number of bars.
4. Update Price Data:
UpdatePrice(stf);: Calls the UpdatePrice function to update the price data for the specified timeframe (stf).
5. Determine Direction:
if (OPEN[0] < LWMA2T[0]) ret = rise;: If the open price of the most recent bar (OPEN[0]) is less than the LWMA value (LWMA2T[0]), it indicates a rising bar, so ret is set to rise (1).
if (OPEN[0] > LWMA2T[0]) ret = down;: If the open price of the most recent bar (OPEN[0]) is greater than the LWMA value (LWMA2T[0]), it indicates a falling bar, so ret is set to down (-1).
6. Return Result:
return(ret);: Returns the direction of the bar (1 for rise, -1 for down, and 0 if the bar is neutral).
Summary
The BarDirection function determines the direction of the most recent bar using the Linear Weighted Moving Average (LWMA). It creates an array to store LWMA values, updates the price data, and compares the open price of the bar with the LWMA value to determine if the bar is rising or falling. This function helps the EA identify market trends based on moving average calculations.
Let's break down the PricePercentMove function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::PricePercentMove(const ENUM_TIMEFRAMES stf, int shift)
This function calculates the percentage price movement of a bar in the specified timeframe and determines the price direction. Here’s a detailed breakdown of each part of the code:
int SFPCB::PricePercentMove(const ENUM_TIMEFRAMES stf,int shift) // Price Bar Direction in percent
{
//---
int ret=0;
int rise=1,
down=-1;
//--
int br=shift+3;
double hasil=0.0;
double move=5.0;
UpdatePrice(stf);
//--
double CL[];
ArrayResize(CL,br,br);
ArraySetAsSeries(CL,true);
//--
for(int x=br-1; x>=shift; x--)
CL[x]=CLOSE[x];
//--
double close_now = CL[shift];
double close_prev = CL[shift+1];
//--
if((close_now==0 || close_now==EMPTY_VALUE) || (close_prev==0 || close_prev==EMPTY_VALUE)) hasil=0.0;
else hasil=NormalizeDouble((close_now / close_prev * 100) - 100,3);
hasil=NormalizeDouble(hasil*100,3); // because its value less than 1 then multiplied with 100.
//--
if(hasil>move) ret=rise;
if(hasil<-move) ret=down;
//--
return(ret);
//---
} //-end PricePercentMove()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result indicating the direction of the price move. It's initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) directions.
int br = shift + 3;: Specifies the number of bars to use for the calculation, based on the provided shift value.
double hasil = 0.0;: Variable to store the calculated percentage change in price.
double move = 5.0;: Threshold value for considering a significant move.
2. Update Price Data:
UpdatePrice(stf);: Calls the UpdatePrice function to update the price data for the specified timeframe (stf).
3. Create and Resize Close Price Array:
double CL[];: Declares an array to hold close prices.
ArrayResize(CL, br, br);: Resizes the array to hold br number of elements.
ArraySetAsSeries(CL, true);: Sets the array as a series, meaning it will be indexed from the end (most recent data first).
4. Populate Close Price Array:
The loop populates the CL array with close prices from the most recent bars, starting from the shift index.
5. Calculate Percentage Change:
double close_now = CL[shift];: Retrieves the current close price.
double close_prev = CL[shift + 1];: Retrieves the previous close price.
If either the current or previous close price is zero or an empty value, hasil is set to 0.0.
Otherwise, the percentage change (hasil) is calculated using the formula: ((close_now / close_prev * 100) - 100).
hasil is further adjusted and normalized for easier comparison.
6. Determine Direction:
if (hasil > move) ret = rise;: If the percentage change is greater than the threshold (move), it indicates a rising price, so ret is set to rise (1).
if (hasil < -move) ret = down;: If the percentage change is less than the negative threshold (-move), it indicates a falling price, so ret is set to down (-1).
7. Return Result:
return(ret);: Returns the direction of the price move (1 for rise, -1 for down, and 0 if no significant movement).
Summary
The PricePercentMove function calculates the percentage price movement of a bar and determines its direction. It updates the price data, calculates the percentage change between the current and previous close prices, and determines if the price has moved significantly up or down based on a predefined threshold. This function is essential for identifying significant price movements and making trading decisions.
Let's break down the ZigZagDirection function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::ZigZagDirection(const ENUM_TIMEFRAMES ztf)
This function determines the direction of price movement using the ZigZag indicator in the specified timeframe. Here’s a detailed breakdown of each part of the code:
int zh = 0, zl = 0, zz = 0;: These variables will hold the high point, low point, and the direction result respectively.
double ExtHi[], ExtLo[];: Arrays to hold the high and low values from the ZigZag indicator.
2. Resize and Initialize Arrays:
ArrayResize(ExtHi, arper, arper);, ArrayResize(ExtLo, arper, arper);: Resize the arrays to hold arper number of elements.
ArraySetAsSeries(ExtHi, true);, ArraySetAsSeries(ExtLo, true);: Set the arrays as series, meaning they will be indexed from the end (most recent data first).
ArrayInitialize(ExtHi, 0.0);, ArrayInitialize(ExtLo, 0.0);: Initialize the arrays with zeroes.
3. Copy Buffer Values Based on Timeframe:
For PERIOD_H1:
CopyBuffer(hZZm60, 1, 0, arper, ExtHi);, CopyBuffer(hZZm60, 2, 0, arper, ExtLo);: Copy the high and low values from the ZigZag indicator buffers for the H1 timeframe.
UpdatePrice(TFT60);: Update the price data for the H1 timeframe.
Find High and Low Points:
The loop iterates through the price data to find where the high and low points match the ZigZag high and low values.
Determine Direction:
Based on the positions of the high and low points, the direction is determined and set in zz.
For PERIOD_M30:
CopyBuffer(hZZm30, 1, 0, arper, ExtHi);, CopyBuffer(hZZm30, 2, 0, arper, ExtLo);: Copy the high and low values from the ZigZag indicator buffers for the M30 timeframe.
UpdatePrice(TFT30);: Update the price data for the M30 timeframe.
Find High and Low Points:
The loop iterates through the price data to find where the high and low points match the ZigZag high and low values.
Determine Direction:
Based on the positions of the high and low points, the direction is determined and set in zz.
4. Return Result:
return (zz);: Returns the direction of the ZigZag indicator (1 for uptrend, -1 for downtrend, 2 and -2 for other specific conditions).
Summary
The ZigZagDirection function uses the ZigZag indicator to determine the price direction. It copies the high and low values from the ZigZag indicator buffers, updates the price data, finds the high and low points, and determines the direction based on these points. This function is essential for identifying market trends and making informed trading decisions.
Let's break down the WeightedClosePrice function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::WeightedClosePrice(void)
This function calculates the direction of price movement based on the weighted close price and a 20-period Simple Moving Average (SMA) in the 60-minute timeframe. Here’s a detailed breakdown of each part of the code:
int wp = 0;: This variable will hold the result indicating the direction of the price move. It's initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) directions.
int br = 3;: Specifies the number of bars to use for the calculation.
2. Create and Resize SMA Array:
double SMA5s20[];: Declares an array to hold SMA values.
ArrayResize(SMA5s20, br, br);: Resizes the array to hold br number of elements.
ArraySetAsSeries(SMA5s20, true);: Sets the array as a series, meaning it will be indexed from the end (most recent data first).
3. Copy SMA Values to Array:
CopyBuffer(hiMA20, 0, 0, br, SMA5s20);: Copies the SMA values from the indicator buffer (hiMA20) to the array. This gets the SMA values for the specified number of bars.
4. Update Price Data:
UpdatePrice(TFT60);: Calls the UpdatePrice function to update the price data for the 60-minute timeframe (TFT60).
5. Calculate Weighted Close Prices:
double fpCls0 = (HIGH[0] + LOW[0] + CLOSE[0] + CLOSE[0]) / 4;: Calculates the weighted close price for the most recent bar.
double fpCls1 = (HIGH[1] + LOW[1] + CLOSE[1] + CLOSE[1]) / 4;: Calculates the weighted close price for the previous bar.
6. Calculate Differences:
double hlcc0 = fpCls0 - SMA5s20[0];: Calculates the difference between the weighted close price of the most recent bar and the corresponding SMA value.
double hlcc1 = fpCls1 - SMA5s20[1];: Calculates the difference between the weighted close price of the previous bar and the corresponding SMA value.
7. Determine Direction:
if (hlcc0 > hlcc1) wp = rise;: If the difference for the most recent bar (hlcc0) is greater than the difference for the previous bar (hlcc1), it indicates a rising trend, so wp is set to rise (1).
if (hlcc0 < hlcc1) wp = down;: If the difference for the most recent bar (hlcc0) is less than the difference for the previous bar (hlcc1), it indicates a falling trend, so wp is set to down (-1).
8. Return Result:
return (wp);: Returns the direction of the price move (1 for rise, -1 for down, and 0 if no significant movement).
Summary
The WeightedClosePrice function calculates the direction of price movement based on the weighted close price and a 20-period Simple Moving Average (SMA) in the 60-minute timeframe. It creates an array to store SMA values, updates the price data, calculates the weighted close prices, and determines if the price is rising or falling based on the differences between the weighted close prices and the SMA values. This function is essential for identifying market trends and making trading decisions.
Let's break down the MA5Trend function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::MA5Trend(void)
This function determines the trend direction based on a combination of the 5-period Exponential Moving Average (EMA) and the 20-period Simple Moving Average (SMA) values. Here’s a detailed breakdown of each part of the code:
int m5t = 0;: This variable will hold the result indicating the trend direction. It's initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) trends.
2. Create and Resize Moving Average Arrays:
double EMA5e02[], SMA5s20[], MAONs10[], MAONs62[];: Declares arrays to hold moving average values.
ArrayResize(EMA5e02, arper, arper);, etc.: Resizes the arrays to hold arper number of elements.
ArraySetAsSeries(EMA5e02, true);, etc.: Sets the arrays as series, meaning they will be indexed from the end (most recent data first).
3. Copy Buffer Values for EMA and SMA:
CopyBuffer(hiMA02, 0, 0, arper, EMA5e02);: Copies the 5-period EMA values from the indicator buffer (hiMA02) to the array.
CopyBuffer(hiMA20, 0, 0, arper, SMA5s20);: Copies the 20-period SMA values from the indicator buffer (hiMA20) to the array.
4. Calculate Simple Moving Averages on the SMA Buffer:
SimpleMAOnBuffer(arper, 0, 0, 10, SMA5s20, MAONs10);: Calculates the 10-period simple moving average on the SMA buffer and stores it in MAONs10.
SimpleMAOnBuffer(arper, 0, 0, 62, SMA5s20, MAONs62);: Calculates the 62-period simple moving average on the SMA buffer and stores it in MAONs62.
5. Calculate Differences Between Moving Averages:
double ma10620 = MAONs10[0] - MAONs62[0];: Calculates the difference between the 10-period and 62-period moving averages for the most recent bar.
double ma10621 = MAONs10[1] - MAONs62[1];: Calculates the difference for the previous bar.
double ma20100 = SMA5s20[0] - MAONs10[0];: Calculates the difference between the 20-period SMA and the 10-period moving average for the most recent bar.
double ma20101 = SMA5s20[1] - MAONs10[1];: Calculates the difference for the previous bar.
6. Determine Trend Conditions:
Several boolean variables (ma5xupn, ma5xupc, ma5xupb, ma5xdnn, ma5xdnc, ma5xdna) are used to check different conditions based on the EMA and SMA values, and the differences calculated earlier. These conditions help to identify whether the trend is rising or falling.
7. Set Trend Direction:
if (ma5xupn || ma5xupc || ma5xupb) { m5t = rise; }: If any of the rising trend conditions are met, m5t is set to rise (1).
if (ma5xdnn || ma5xdnc || ma5xdna) { m5t = down; }: If any of the falling trend conditions are met, m5t is set to down (-1).
8. Return Result:
return (m5t);: Returns the trend direction (1 for rise, -1 for down, and 0 if no significant trend is detected).
Summary
The MA5Trend function determines the trend direction based on a combination of the 5-period Exponential Moving Average (EMA) and the 20-period Simple Moving Average (SMA) values. It creates arrays to store moving average values, updates the price data, calculates the differences between various moving averages, and evaluates several conditions to identify whether the trend is rising or falling. This function helps the EA identify market trends and make informed trading decisions.
Let's break down the CombineIndicators function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::CombineIndicators(void)
This function combines the signals from various indicators to determine the overall trading signal. Here’s a detailed breakdown of each part of the code:
int SFPCB::CombineIndicators(void) // Fungction for combine all indicators signal
{
//---
int ret=0;
int rise1=1,
down1=-1;
int rise2=2,
down2=-2;
int br=3;
bool ArrUp=false,
ArrDn=false;
//--
int zzM30=ZigZagDirection(TFT30);
int zzM60=ZigZagDirection(TFT60);
int ma5mv=MA5Trend();
int wgprc=WeightedClosePrice();
//--
double MACDM[],
MACDS[];
//--
ArrayResize(MACDM,br,br);
ArrayResize(MACDS,br,br);
ArraySetAsSeries(MACDM,true);
ArraySetAsSeries(MACDS,true);
//--
CopyBuffer(hiMACD,0,0,br,MACDM);
CopyBuffer(hiMACD,1,0,br,MACDS);
//--
double mcdm0=MACDM[0];
double mcdm1=MACDM[1];
double mcds0=MACDS[0];
double mcds1=MACDS[1];
double macd0=mcdm0-mcds0;
double macd1=mcdm1-mcds1;
//--
if(((zzM60==rise1)&&(zzM30==rise1))||((macd0>macd1)&&(mcdm0>mcdm1))) {ArrUp=true; ArrDn=false;}
if(((zzM60==down1)&&(zzM30==down1))||((macd0<macd1)&&(mcdm0<mcdm1))) {ArrUp=true; ArrDn=false;}
if(((ArrUp)&&(zzM60==rise2))||((mcdm0<mcdm1)&&(macd0<macd1))) {ArrDn=true; ArrUp=false;}
if(((ArrDn)&&(zzM60==down2))||((mcdm0>mcdm1)&&(macd0>macd1))) {ArrUp=true; ArrDn=false;}
if((mcdm0>=mcdm1)&&(mcdm0>mcds0)&&(mcds0>mcds1)) {ArrUp=true; ArrDn=false;}
if((mcdm0<=mcdm1)&&(mcdm0<mcds0)&&(mcds0<mcds1)) {ArrDn=true; ArrUp=false;}
if(ma5mv==rise1) {ArrUp=true; ArrDn=false;}
if(ma5mv==down1) {ArrDn=true; ArrUp=false;}
//--
if((ArrUp)&&(wgprc==rise1)) ret=rise1;
if((ArrDn)&&(wgprc==down1)) ret=down1;
//--
return(ret);
//---
} //-end CombineIndicators()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result of the combined signal. It's initialized to 0.
int rise1 = 1, down1 = -1;: Constants to represent rising (1) and falling (-1) signals.
int rise2 = 2, down2 = -2;: Additional constants to represent stronger rising (2) and falling (-2) signals.
int br = 3;: Specifies the number of bars to use for the calculation.
bool ArrUp = false, ArrDn = false;: Flags to indicate upward (true) or downward (true) signals.
2. Get Signals from Various Indicators:
int zzM30 = ZigZagDirection(TFT30);: Retrieves the ZigZag direction signal for the 30-minute timeframe.
int zzM60 = ZigZagDirection(TFT60);: Retrieves the ZigZag direction signal for the 60-minute timeframe.
int ma5mv = MA5Trend();: Retrieves the trend signal based on 5-period moving averages.
int wgprc = WeightedClosePrice();: Retrieves the weighted close price signal.
3. Create and Resize MACD Arrays:
double MACDM[], MACDS[];: Declares arrays to hold MACD values.
ArrayResize(MACDM, br, br);, ArrayResize(MACDS, br, br);: Resizes the arrays to hold br number of elements.
ArraySetAsSeries(MACDM, true);, ArraySetAsSeries(MACDS, true);: Sets the arrays as series, meaning they will be indexed from the end (most recent data first).
4. Copy MACD Buffer Values:
CopyBuffer(hiMACD, 0, 0, br, MACDM);: Copies the MACD main line values from the indicator buffer (hiMACD) to the array.
CopyBuffer(hiMACD, 1, 0, br, MACDS);: Copies the MACD signal line values from the indicator buffer (hiMACD) to the array.
5. Calculate MACD Values:
double mcdm0 = MACDM[0];: Retrieves the most recent MACD main line value.
double mcdm1 = MACDM[1];: Retrieves the previous MACD main line value.
double mcds0 = MACDS[0];: Retrieves the most recent MACD signal line value.
double mcds1 = MACDS[1];: Retrieves the previous MACD signal line value.
double macd0 = mcdm0 - mcds0;: Calculates the most recent MACD histogram value.
Several conditions check the combined signals from the ZigZag, MACD, MA5Trend, and WeightedClosePrice indicators to set the flags ArrUp and ArrDn.
7. Final Decision Based on Combined Signals:
The final trading signal is determined based on the combined signals and assigned to ret.
8. Return Result:
return(ret);: Returns the combined signal (1 for rise, -1 for down, and 0 if no clear signal is detected).
Summary
The CombineIndicators function combines signals from various indicators, including ZigZag, MACD, MA5Trend, and WeightedClosePrice, to determine the overall trading signal. It evaluates these signals using a series of conditions, sets flags for upward or downward signals, and makes a final decision based on the combined results. This function is crucial for making informed trading decisions by considering multiple indicator signals.
Let's break down the GetOpenPosition function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::GetOpenPosition(void)
This function generates a signal for opening a trading position based on the combined results of multiple indicators. Here’s a detailed breakdown of each part of the code:
int SFPCB::GetOpenPosition(void) // Signal Open Position
{
//---
int ret=0;
int rise=1,
down=-1;
//--
int FPCB=CombineIndicators();
int BPrD=BarDirection(TFt);
int PPmv=PricePercentMove(TFt,0);
//--
if(BPrD==rise && FPCB==rise && PPmv==rise) ret=rise;
if(BPrD==down && FPCB==down && PPmv==down) ret=down;
//--
return(ret);
//---
} //-end GetOpenPosition()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result indicating whether to open a buy or sell position. It is initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) signals.
2. Get Combined Indicator Signal:
int FPCB = CombineIndicators();: Calls the CombineIndicators function to get a combined signal from multiple indicators.
3. Get Bar Direction Signal:
int BPrD = BarDirection(TFt);: Calls the BarDirection function to get the direction signal of the bar in the specified timeframe (TFt).
4. Get Price Percent Move Signal:
int PPmv = PricePercentMove(TFt, 0);: Calls the PricePercentMove function to get the price percent move signal in the specified timeframe (TFt), using a shift value of 0.
5. Determine Open Position Signal:
if (BPrD == rise && FPCB == rise && PPmv == rise) ret = rise;: If the bar direction, combined indicators, and price percent move signals all indicate a rise, ret is set to rise (1).
if (BPrD == down && FPCB == down && PPmv == down) ret = down;: If the bar direction, combined indicators, and price percent move signals all indicate a fall, ret is set to down (-1).
6. Return Result:
return (ret);: Returns the open position signal (1 for buy, -1 for sell, and 0 if no clear signal is detected).
Summary
The GetOpenPosition function determines whether to open a buy or sell position based on the signals from multiple indicators. It retrieves signals from the combined indicators, bar direction, and price percent move functions, and sets the open position signal if all the indicators align in the same direction. This function is crucial for making informed trading decisions and ensuring that the EA opens positions based on comprehensive market analysis.
Let's break down the GetCloseInWeakSignal function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::GetCloseInWeakSignal(int exis)
This function generates a signal to close a position in profit when a weak counter signal is detected. Here’s a detailed breakdown of each part of the code:
int SFPCB::GetCloseInWeakSignal(int exis) // Signal Indicator Position Close in profit
{
//---
int ret=0;
int rise=1,
down=-1;
//--
int BPrD=BarDirection(TFt);
int PPmv=PricePercentMove(TFt,0);
//--
if(exis==down && BPrD==rise && PPmv==rise) ret=rise;
if(exis==rise && BPrD==down && PPmv==down) ret=down;
//--
return(ret);
//---
} //-end GetCloseInWeakSignal()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result indicating whether to close the position. It is initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) signals.
2. Get Bar Direction Signal:
int BPrD = BarDirection(TFt);: Calls the BarDirection function to get the direction signal of the bar in the specified timeframe (TFt).
3. Get Price Percent Move Signal:
int PPmv = PricePercentMove(TFt, 0);: Calls the PricePercentMove function to get the price percent move signal in the specified timeframe (TFt), using a shift value of 0.
4. Determine Close Position Signal:
if (exis == down && BPrD == rise && PPmv == rise) ret = rise;: If the existing position is down (exis == down), but both the bar direction and price percent move signals indicate a rise, ret is set to rise (1), signaling a close of the down position.
if (exis == rise && BPrD == down && PPmv == down) ret = down;: If the existing position is up (exis == rise), but both the bar direction and price percent move signals indicate a fall, ret is set to down (-1), signaling a close of the up position.
5. Return Result:
return (ret);: Returns the close position signal (1 for closing a down position and opening a rise, -1 for closing an up position and opening a fall, and 0 if no signal is detected).
Summary
The GetCloseInWeakSignal function evaluates specific conditions to determine if a position should be closed based on a weak trading signal. It initializes variables, gets the bar direction and price percent move, evaluates conditions to identify a weak signal, and returns a value indicating whether to close the position.
By assessing the direction of the bar and the price percent move, this function helps in making informed decisions about closing positions to minimize losses or lock in profits.
Let's break down the PARSAR05 function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::PARSAR05(void)
This function determines the direction of the price movement using the Parabolic SAR indicator in the 5-minute timeframe. Here’s a detailed breakdown of each part of the code:
int SFPCB::PARSAR05(void) // formula Parabolic SAR M5
{
//---
int ret=0;
int rise=1,
down=-1;
int br=2;
//--
double PSAR[];
ArrayResize(PSAR,br,br);
ArraySetAsSeries(PSAR,true);
CopyBuffer(hPar05,0,0,br,PSAR);
//--
RefreshPrice(TFT05,br);
double HIG0=iHigh(SPC,TFT05,0);
double LOW0=iLow(SPC,TFT05,0);
//--
if(PSAR[0]<LOW0)
ret=rise;
if(PSAR[0]>HIG0)
ret=down;
//--
return(ret);
//---
} //-end PARSAR05()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Variables:
int ret = 0;: This variable will hold the result indicating the direction of the price move. It's initialized to 0.
int rise = 1, down = -1;: Constants to represent rising (1) and falling (-1) signals.
int br = 2;: Specifies the number of bars to use for the calculation.
2. Create and Resize Parabolic SAR Array:
double PSAR[];: Declares an array to hold Parabolic SAR values.
ArrayResize(PSAR, br, br);: Resizes the array to hold br number of elements.
ArraySetAsSeries(PSAR, true);: Sets the array as a series, meaning it will be indexed from the end (most recent data first).
3. Copy Parabolic SAR Values to Array:
CopyBuffer(hPar05, 0, 0, br, PSAR);: Copies the Parabolic SAR values from the indicator buffer (hPar05) to the array. This gets the Parabolic SAR values for the specified number of bars.
4. Refresh Price Data:
RefreshPrice(TFT05, br);: Calls the RefreshPrice function to update the price data for the 5-minute timeframe (TFT05).
5. Get Highest and Lowest Prices of the Most Recent Bar:
double HIG0 = iHigh(SPC, TFT05, 0);: Retrieves the highest price of the most recent bar.
double LOW0 = iLow(SPC, TFT05, 0);: Retrieves the lowest price of the most recent bar.
6. Determine Direction:
if (PSAR[0] < LOW0) ret = rise;: If the Parabolic SAR value for the most recent bar (PSAR[0]) is below the lowest price of the bar (LOW0), it indicates a rising trend, so ret is set to rise (1).
if (PSAR[0] > HIG0) ret = down;: If the Parabolic SAR value for the most recent bar (PSAR[0]) is above the highest price of the bar (HIG0), it indicates a falling trend, so ret is set to down (-1).
7. Return Result:
return (ret);: Returns the direction of the price move (1 for rise, -1 for down, and 0 if no significant movement is detected).
Summary
The PARSAR05 function determines the direction of the price movement using the Parabolic SAR indicator in the 5-minute timeframe. It creates an array to store Parabolic SAR values, updates the price data, retrieves the highest and lowest prices of the most recent bar, and determines if the price is rising or falling based on the Parabolic SAR values. This function helps the EA identify short-term trends and make trading decisions accordingly.
Let's break down the OpenBuy function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::OpenBuy(void)
This function attempts to open a buy order in the market and provides detailed feedback on the success or failure of the operation. Here’s a detailed breakdown of each part of the code:
ResetLastError(): Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Variables:
bool buyopen = false;: Initializes a flag to indicate if the buy order is successfully opened.
string ldComm = GetCommentForOrder() + "_Buy";: Generates the comment for the buy order.
double ldLot = MLots();: Retrieves the lot size for the order.
ENUM_ORDER_TYPE type_req = ORDER_TYPE_BUY;: Sets the order type to buy.
3. Initialize Trade Structures:
MqlTradeRequest req = {}, MqlTradeResult res = {}, MqlTradeCheckResult check = {};: Initializes the trade request, result, and check structures.
ZeroMemory(req); ZeroMemory(res); ZeroMemory(check);: Sets the structures to zero.
4. Set Up Current Symbol:
CurrentSymbolSet(): Calls the CurrentSymbolSet function to ensure the symbol is set up and synchronized for trading.
5. Calculate Stop Loss and Take Profit:
double SL = OrderSLSet(type_req, sc_symbol.Bid());: Calculates the Stop Loss level.
double TP = OrderTPSet(type_req, sc_symbol.Ask());: Calculates the Take Profit level.
6. Refresh Tick Data and Attempt Buy Order:
if (RefreshTick()) buyopen = sc_trade.Buy(ldLot, SPC, sc_symbol.Ask(), SL, TP, ldComm);: Refreshes the tick data and attempts to open a buy order. If successful, buyopen is set to true.
7. Get Last Error Code:
int error = GetLastError();: Retrieves the last error code.
8. Handle Result:
Success:
If the buy order is successfully opened or there are no errors, it constructs a success message and sends an alert. It also updates the last bar time (PbarB).
Failure:
If the order fails to open, it checks the result details and sends an alert with the failure reason.
9. Return Result:
return (buyopen);: Returns whether the buy order was successfully opened.
Summary
The OpenBuy function attempts to open a buy order and provides feedback on the success or failure of the operation. It sets up the current symbol, calculates SL and TP levels, refreshes the tick data, and attempts to open the buy order. It then handles the result, sending alerts and updating relevant information based on whether the order was successful or not.
Let's break down the OpenSell function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::OpenSell(void)
This function attempts to open a sell order in the market and provides detailed feedback on the success or failure of the operation. Here’s a detailed breakdown of each part of the code:
ResetLastError(): Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Variables:
bool selopen = false;: Initializes a flag to indicate if the sell order is successfully opened.
string sdComm = GetCommentForOrder() + "_Sell";: Generates the comment for the sell order.
double sdLot = MLots();: Retrieves the lot size for the order.
ENUM_ORDER_TYPE type_req = ORDER_TYPE_SELL;: Sets the order type to sell.
3. Initialize Trade Structures:
MqlTradeRequest req = {}, MqlTradeResult res = {}, MqlTradeCheckResult check = {};: Initializes the trade request, result, and check structures.
ZeroMemory(req); ZeroMemory(res); ZeroMemory(check);: Sets the structures to zero.
4. Set Up Current Symbol:
CurrentSymbolSet(): Calls the CurrentSymbolSet function to ensure the symbol is set up and synchronized for trading.
5. Calculate Stop Loss and Take Profit:
double SL = OrderSLSet(type_req, sc_symbol.Ask());: Calculates the Stop Loss level.
double TP = OrderTPSet(type_req, sc_symbol.Bid());: Calculates the Take Profit level.
6. Refresh Tick Data and Attempt Sell Order:
if (RefreshTick()) selopen = sc_trade.Sell(sdLot, SPC, sc_symbol.Bid(), SL, TP, sdComm);: Refreshes the tick data and attempts to open a sell order. If successful, selopen is set to true.
7. Get Last Error Code:
int error = GetLastError();: Retrieves the last error code.
8. Handle Result:
Success:
If the sell order is successfully opened or there are no errors, it constructs a success message and sends an alert. It also updates the last bar time (PbarS).
Failure:
If the order fails to open, it checks the result details and sends an alert with the failure reason.
9. Return Result:
return (selopen);: Returns whether the sell order was successfully opened.
Summary
The OpenSell function attempts to open a sell order and provides feedback on the success or failure of the operation. It sets up the current symbol, calculates SL and TP levels, refreshes the tick data, and attempts to open the sell order. It then handles the result, sending alerts and updating relevant information based on whether the order was successful or not.
Let's break down the OrderSLSet function of FiboPivotCandleBar Expert Advisor for MT5.
This function sets the Stop Loss (SL) level for an order based on its type (buy or sell) and the specified price. Here’s a detailed breakdown of each part of the code:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
3. Refresh Tick Data:
RefreshTick();: Calls the RefreshTick function to update the tick data for the current symbol.
4. Set SL Based on Order Type:
For Buy Orders:
case (ORDER_TYPE_BUY):: Handles the case for buy orders.
if (use_sl == Yes && autosl == Yes): If using automatic SL, sets the SL to atprice - 38 * pip.
if (use_sl == Yes && autosl == No): If using manual SL, sets the SL to atprice - SLval * pip.
else slv = 0.0;: If SL is not used, sets the SL to 0.0.
For Sell Orders:
case (ORDER_TYPE_SELL):: Handles the case for sell orders.
if (use_sl == Yes && autosl == Yes): If using automatic SL, sets the SL to atprice + 38 * pip.
if (use_sl == Yes && autosl == No): If using manual SL, sets the SL to atprice + SLval * pip.
else slv = 0.0;: If SL is not used, sets the SL to 0.0.
5. Return Result:
return (slv);: Returns the calculated SL value.
Summary
The OrderSLSet function calculates the Stop Loss (SL) level for an order based on its type (buy or sell) and the specified price. It initializes the SL value, calculates the pip value, refreshes the tick data, and sets the SL based on whether automatic or manual SL is being used. This function is essential for setting appropriate SL levels to manage risk in trading.
Let's break down the OrderTPSet function of FiboPivotCandleBar Expert Advisor for MT5.
This function sets the Take Profit (TP) level for an order based on its type (buy or sell) and the specified price. Here’s a detailed breakdown of each part of the code:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
3. Refresh Tick Data:
RefreshTick();: Calls the RefreshTick function to update the tick data for the current symbol.
4. Set TP Based on Order Type:
For Buy Orders:
case (ORDER_TYPE_BUY):: Handles the case for buy orders.
if (use_tp == Yes && autotp == Yes): If using automatic TP, sets the TP to atprice + 50 * pip.
if (use_tp == Yes && autotp == No): If using manual TP, sets the TP to atprice + TPval * pip.
else tpv = 0.0;: If TP is not used, sets the TP to 0.0.
For Sell Orders:
case (ORDER_TYPE_SELL):: Handles the case for sell orders.
if (use_tp == Yes && autotp == Yes): If using automatic TP, sets the TP to atprice - 50 * pip.
if (use_tp == Yes && autotp == No): If using manual TP, sets the TP to atprice - TPval * pip.
else tpv = 0.0;: If TP is not used, sets the TP to 0.0.
5. Return Result:
return (tpv);: Returns the calculated TP value.
Summary
The OrderTPSet function calculates the Take Profit (TP) level for an order based on its type (buy or sell) and the specified price. It initializes the TP value, calculates the pip value, refreshes the tick data, and sets the TP based on whether automatic or manual TP is being used. This function is essential for setting appropriate TP levels to manage profits in trading.
Let's break down the CheckOpenPMx function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::CheckOpenPMx(void)
This function checks the currently open trades and updates various counters and profit values for buy and sell positions. Here’s a detailed breakdown of each part of the code:
int totalorder = PositionsTotal();: Retrieves the total number of open positions.
xtto = totalorder;: Stores the total number of open positions.
xob = 0;: Initializes the counter for buy positions.
xos = 0;: Initializes the counter for sell positions.
profitb = 0;: Initializes the total profit for buy positions.
profits = 0;: Initializes the total profit for sell positions.
double pos_profit = 0.0;: Variable to store the profit of a position.
double pos_swap = 0.0;: Variable to store the swap of a position.
double pos_comm = 0.0;: Variable to store the commission of a position.
2. Iterate Through Open Positions:
for (int i = 0; i < totalorder && !IsStopped(); i++): Loop through all open positions, checking each one unless the trading is stopped.
3. Get Position Details:
string position_symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
long magic = sc_position.Magic();: Retrieves the magic number of the current position.
4. Check if Position Belongs to the EA:
if (position_symbol == SPC && magic == magicEA): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
5. Determine Position Type and Update Counters:
For Buy Positions:
if (opstype == POSITION_TYPE_BUY): Checks if the position is a buy position.
xob++;: Increments the counter for buy positions.
pos_profit = sc_position.Profit();: Retrieves the profit of the position.
pos_swap = sc_position.Swap();: Retrieves the swap of the position.
pos_comm = sc_position.Commission();: Retrieves the commission of the position.
profitb += NormalizeDouble(pos_profit + pos_swap + pos_comm, 2);: Updates the total profit for buy positions.
PbarB = iTime(SPC, TFt, 0);: Updates the last bar time for buy positions.
For Sell Positions:
if (opstype == POSITION_TYPE_SELL): Checks if the position is a sell position.
xos++;: Increments the counter for sell positions.
pos_profit = sc_position.Profit();: Retrieves the profit of the position.
pos_swap = sc_position.Swap();: Retrieves the swap of the position.
pos_comm = sc_position.Commission();: Retrieves the commission of the position.
profits += NormalizeDouble(pos_profit + pos_swap + pos_comm, 2);: Updates the total profit for sell positions.
PbarS = iTime(SPC, TFt, 0);: Updates the last bar time for sell positions.
6. Return Statement:
return;: The function returns after processing all open positions.
Summary
The CheckOpenPMx function checks the currently open trades and updates various counters and profit values for buy and sell positions. It iterates through all open positions, checks if they belong to the Expert Advisor by matching the symbol and magic number, and updates the relevant counters and profit values accordingly. This function helps keep track of the number of open positions and their respective profits.
Let's break down the TSPrice function of FiboPivotCandleBar Expert Advisor for MT5.
double SFPCB::TSPrice(ENUM_POSITION_TYPE ptype, int TS_type)
This function calculates the Trailing Stop (TS) price for a position based on its type (buy or sell) and the specified TS type. Here’s a detailed breakdown of each part of the code:
int br = 2;: Specifies the number of bars to use for the calculation.
double pval = 0.0;: Initializes the TS price value to 0.0.
2. Calculate Pip Value:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
3. Set TS Based on TS Type:
For TS Type 0: If Use Automatic Trailing (No)
case 0:: Handles the case for TS type 0.
RefreshTick();: Calls the RefreshTick function to update the tick data for the current symbol.
if (ptype == POSITION_TYPE_BUY): If the position type is buy, calculates the TS price as sc_symbol.Bid() - TSval * pip.
if (ptype == POSITION_TYPE_SELL): If the position type is sell, calculates the TS price as sc_symbol.Ask() + TSval * pip.
For TS Type 1: If Use Automatic Trailing (Yes)
case 1:: Handles the case for TS type 1.
double MTren[];: Declares an array to hold moving trend values.
ArrayResize(MTren, br);: Resizes the array to hold br number of elements.
ArraySetAsSeries(MTren, true);: Sets the array as a series, meaning it will be indexed from the end (most recent data first).
CopyBuffer(hMATrS, 0, 0, br, MTren);: Copies the moving trend values from the indicator buffer (hMATrS) to the array.
RefreshPrice(TFt, br);: Calls the RefreshPrice function to update the price data for the specified timeframe (TFt).
Calculate TS Price Based on Moving Trend:
if (ptype == POSITION_TYPE_BUY && (MTren[0] < sc_symbol.NormalizePrice(iLow(SPC, TFt, 0) - TSval * pip))): If the position type is buy and the moving trend value is less than the normalized price, sets the TS price to the moving trend value.
if (ptype == POSITION_TYPE_SELL && (MTren[0] > sc_symbol.NormalizePrice(iHigh(SPC, TFt, 0) + TSval * pip))): If the position type is sell and the moving trend value is greater than the normalized price, sets the TS price to the moving trend value.
4. Return Result:
return (pval);: Returns the calculated TS price value.
Summary
The TSPrice function calculates the Trailing Stop (TS) price for a position based on its type (buy or sell) and the specified TS type. It initializes the TS price value, calculates the pip value, refreshes the tick data, and sets the TS price based on either the current bid/ask price or the moving trend value. This function is essential for setting appropriate TS levels to manage risk and protect profits in trading.
Let's break down the ModifySLTP function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::ModifySLTP(int TS_type)
This function modifies the Stop Loss (SL) and Take Profit (TP) levels for open positions based on their type (buy or sell) and the specified trailing stop type. Here’s a detailed breakdown of each part of the code:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Trade Structures:
MqlTradeRequest req = {}; MqlTradeResult res = {}; MqlTradeCheckResult check = {};: Initializes the trade request, result, and check structures.
3. Determine Trailing Stop Type:
int TRSP = (Close_by_Opps == No && TS_type == 1) ? 0 : TS_type;: Determines the trailing stop type based on the input and configuration.
4. Initialize Modification Flag:
bool modist = false;: Initializes a flag to indicate if the modification is successful.
5. Calculate Pip Value:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
6. Get Total Open Positions:
int total = PositionsTotal();: Retrieves the total number of open positions.
7. Iterate Through Open Positions:
for (int i = total - 1; i >= 0; i--): Loop through all open positions in reverse order.
8. Get Position Details:
string symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
if (symbol == SPC && sc_position.Magic() == magicEA): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
9. Modify SL and TP for Buy Positions:
if (opstype == POSITION_TYPE_BUY): Checks if the position is a buy position.
Retrieves current price, trailing stop price, open price, stop loss, profit, swap, and commission values.
Calculates net profit, modification start price, minimum stop loss for modification, new stop loss, and new take profit values.
Checks if modification is allowed based on current price, stop loss, and profit.
if (modbuy && netp > minprofit): If modification is allowed and net profit is greater than minimum profit, modifies the position.
10. Modify SL and TP for Sell Positions:
if (opstype == POSITION_TYPE_SELL): Checks if the position is a sell position.
Retrieves current price, trailing stop price, open price, stop loss, profit, swap, and commission values.
Calculates net profit, modification start price, minimum stop loss for modification, new stop loss, and new take profit values.
Checks if modification is allowed based on current price, stop loss, and profit.
if (modsel && netp > minprofit): If modification is allowed and net profit is greater than minimum profit, modifies the position.
11. Return Result:
return (modist);: Returns whether the modification was successful.
Summary
The ModifySLTP function modifies the Stop Loss (SL) and Take Profit (TP) levels for open positions based on their type (buy or sell) and the specified trailing stop type. It initializes trade structures, determines the trailing stop type, calculates pip value, retrieves position details, and iterates through open positions to modify SL and TP values based on current price, profit, and other parameters. This function helps manage risk and protect profits by adjusting SL and TP levels dynamically.
Let's break down the CloseBuyPositions function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::CloseBuyPositions(void)
This function iterates over all open positions and attempts to close those that are buy positions for the specified symbol, providing feedback on the success of each operation. Here’s a detailed breakdown of each part of the code:
bool SFPCB::CloseBuyPositions(void)
{
//---
//--
ResetLastError();
bool buyclose=false;
int total=PositionsTotal(); // number of open positions
ENUM_POSITION_TYPE closetype = POSITION_TYPE_BUY;
ENUM_ORDER_TYPE type_req = ORDER_TYPE_SELL;
//--
MqlTradeRequest req={};
MqlTradeResult res={};
MqlTradeCheckResult check={};
//--
//--- iterate over all open positions
for(int i=total-1; i>=0; i--)
{
if(sc_position.SelectByIndex(i))
{
//--- Parameters of the order
string position_Symbol = PositionGetSymbol(i);
ulong position_ticket = PositionGetTicket(i);
ENUM_POSITION_TYPE type = sc_position.PositionType();
//--- if the MagicNumber matches
if((position_Symbol==SPC) && (sc_position.Magic()==magicEA))
{
//--
if(type==closetype)
{
RefreshTick();
buyclose=sc_trade.PositionClose(position_Symbol,slip);
//--- output information about the closure
PrintFormat("Close Buy #%I64d %s %s",position_ticket,position_Symbol,EnumToString(type));
if(buyclose) PbarB=iTime(SPC,TFt,0);
}
}
}
}
//---
return(buyclose);
//----
} //-end CloseBuyPositions()
//---------//
Function Explanation
Detailed Breakdown:
1. Reset Last Error:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Variables:
bool buyclose = false;: Initializes a flag to indicate if any buy position was successfully closed.
int total = PositionsTotal();: Retrieves the total number of open positions.
ENUM_POSITION_TYPE closetype = POSITION_TYPE_BUY;: Sets the type of position to close to "buy".
ENUM_ORDER_TYPE type_req = ORDER_TYPE_SELL;: Sets the order type to "sell" (to close a buy position).
3. Initialize Trade Structures:
MqlTradeRequest req = {}; MqlTradeResult res = {}; MqlTradeCheckResult check = {};: Initializes the trade request, result, and check structures.
4. Iterate Through Open Positions:
for (int i = total - 1; i >= 0; i--): Loop through all open positions in reverse order.
5. Get Position Details:
if (sc_position.SelectByIndex(i)): Selects the position by index.
string position_Symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
ulong position_ticket = PositionGetTicket(i);: Retrieves the ticket number of the current position.
ENUM_POSITION_TYPE type = sc_position.PositionType();: Retrieves the type of the current position.
6. Check if Position Matches EA Criteria:
if ((position_Symbol == SPC) && (sc_position.Magic() == magicEA)): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
7. Close Buy Positions:
if (type == closetype): Checks if the position is a buy position.
RefreshTick();: Calls the RefreshTick function to update the tick data.
buyclose = sc_trade.PositionClose(position_Symbol, slip);: Attempts to close the buy position.
PrintFormat("Close Buy #%I64d %s %s", position_ticket, position_Symbol, EnumToString(type));: Prints information about the closure.
if (buyclose) PbarB = iTime(SPC, TFt, 0);: If the position was successfully closed, updates the last bar time for buy positions.
8. Return Result:
return (buyclose);: Returns whether any buy position was successfully closed.
Summary
The CloseBuyPositions function iterates over all open positions and attempts to close those that are buy positions for the specified symbol. It resets the last error, initializes trade structures, retrieves position details, checks if positions match the EA criteria, and closes buy positions if found. This function helps manage open buy positions by closing them when necessary and providing feedback on the success of each closure.
Let's break down the CloseSellPositions function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::CloseSellPositions(void)
This function iterates over all open positions and attempts to close those that are sell positions for the specified symbol, providing feedback on the success of each operation. Here’s a detailed breakdown of each part of the code:
bool SFPCB::CloseSellPositions(void)
{
//---
ResetLastError();
bool sellclose=false;
int total=PositionsTotal(); // number of open positions
ENUM_POSITION_TYPE closetype = POSITION_TYPE_SELL;
ENUM_ORDER_TYPE type_req = ORDER_TYPE_BUY;
//--
MqlTradeRequest req={};
MqlTradeResult res={};
MqlTradeCheckResult check={};
//--
//--- iterate over all open positions
for(int i=total-1; i>=0; i--)
{
if(sc_position.SelectByIndex(i))
{
//--- Parameters of the order
string position_Symbol = PositionGetSymbol(i);
ulong position_ticket = PositionGetTicket(i);
ENUM_POSITION_TYPE type = sc_position.PositionType();
//--- if the MagicNumber matches
if((position_Symbol==SPC) && (sc_position.Magic()==magicEA))
{
//--
if(type==closetype)
{
RefreshTick();
sellclose=sc_trade.PositionClose(position_Symbol,slip);
//--- output information about the closure
PrintFormat("Close Sell #%I64d %s %s",position_ticket,position_Symbol,EnumToString(type));
if(sellclose) PbarS=iTime(SPC,TFt,0);
}
}
}
}
//---
return(sellclose);
//----
} //-end CloseSellPositions()
//---------//
Function Explanation
Detailed Breakdown:
1. Reset Last Error:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Variables:
bool sellclose = false;: Initializes a flag to indicate if any sell position was successfully closed.
int total = PositionsTotal();: Retrieves the total number of open positions.
ENUM_POSITION_TYPE closetype = POSITION_TYPE_SELL;: Sets the type of position to close to "sell".
ENUM_ORDER_TYPE type_req = ORDER_TYPE_BUY;: Sets the order type to "buy" (to close a sell position).
3. Initialize Trade Structures:
MqlTradeRequest req = {}; MqlTradeResult res = {}; MqlTradeCheckResult check = {};: Initializes the trade request, result, and check structures.
4. Iterate Through Open Positions:
for (int i = total - 1; i >= 0; i--): Loop through all open positions in reverse order.
5. Get Position Details:
if (sc_position.SelectByIndex(i)): Selects the position by index.
string position_Symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
ulong position_ticket = PositionGetTicket(i);: Retrieves the ticket number of the current position.
ENUM_POSITION_TYPE type = sc_position.PositionType();: Retrieves the type of the current position.
6. Check if Position Matches EA Criteria:
if ((position_Symbol == SPC) && (sc_position.Magic() == magicEA)): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
7. Close Sell Positions:
if (type == closetype): Checks if the position is a sell position.
RefreshTick();: Calls the RefreshTick function to update the tick data.
sellclose = sc_trade.PositionClose(position_Symbol, slip);: Attempts to close the sell position.
PrintFormat("Close Sell #%I64d %s %s", position_ticket, position_Symbol, EnumToString(type));: Prints information about the closure.
if (sellclose) PbarS = iTime(SPC, TFt, 0);: If the position was successfully closed, updates the last bar time for sell positions.
8. Return Result:
return (sellclose);: Returns whether any sell position was successfully closed.
Summary
The CloseSellPositions function iterates over all open positions and attempts to close those that are sell positions for the specified symbol. It resets the last error, initializes trade structures, retrieves position details, checks if positions match the EA criteria, and closes sell positions if found. This function helps manage open sell positions by closing them when necessary and providing feedback on the success of each closure.
Let's break down the CloseAllProfit function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::CloseAllProfit(void)
This function attempts to close all profitable positions based on specific criteria, providing feedback on the success of each operation. Here’s a detailed breakdown of each part of the code:
bool SFPCB::CloseAllProfit(void)
{
//----
ResetLastError();
//--
int up=1,
dw=-1;
bool orclose=false;
string isgood="trend is still good";
//--
MqlTradeRequest req={};
MqlTradeResult res={};
MqlTradeCheckResult check={};
//--
int ttlorder=PositionsTotal(); // number of open positions
//--
int hps=PARSAR05();
orclose=false;
//--
for(int i=ttlorder-1; i>=0; i--)
{
string position_Symbol = PositionGetSymbol(i);
ENUM_POSITION_TYPE type = sc_position.PositionType();
if((position_Symbol==SPC) && (sc_position.Magic()==magicEA))
{
double pos_profit = sc_position.Profit();
double pos_swap = sc_position.Swap();
double pos_comm = sc_position.Commission();
double cur_profit = NormalizeDouble(pos_profit+pos_swap+pos_comm,2);
ulong position_ticket = PositionGetTicket(i);
//---
if(type==POSITION_TYPE_BUY && cur_profit>0.02 && hps==dw)
{
RefreshTick();
orclose = sc_trade.PositionClose(position_Symbol,slip);
//--- output information about the closure
PrintFormat("Close #%I64d %s %s",position_ticket,position_Symbol,EnumToString(type));
if(orclose) PbarB=iTime(SPC,TFt,0);
}
else if(hps==up) PrintFormat("Not Closed yet #%I64d %s %s",position_ticket,position_Symbol,isgood);
if(type==POSITION_TYPE_SELL && cur_profit>0.02 && hps==up)
{
RefreshTick();
orclose = sc_trade.PositionClose(position_Symbol,slip);
//--- output information about the closure
PrintFormat("Close #%I64d %s %s",position_ticket,position_Symbol,EnumToString(type));
if(orclose) PbarS=iTime(SPC,TFt,0);
}
else if(hps==dw) PrintFormat("Not Closed yet #%I64d %s %s",position_ticket,position_Symbol,isgood);
}
}
//--
return(orclose);
//----
} //-end CloseAllProfit()
//---------//
Function Explanation
Detailed Breakdown:
1. Reset Last Error:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Variables:
int up = 1, dw = -1;: Constants to represent upward (1) and downward (-1) trends.
bool orclose = false;: Initializes a flag to indicate if any position was successfully closed.
string isgood = "trend is still good";: A message to indicate that the trend is still favorable.
3. Initialize Trade Structures:
MqlTradeRequest req = {}, MqlTradeResult res = {}, MqlTradeCheckResult check = {};: Initializes the trade request, result, and check structures.
4. Get Total Open Positions:
int ttlorder = PositionsTotal();: Retrieves the total number of open positions.
5. Get Parabolic SAR Signal:
int hps = PARSAR05();: Calls the PARSAR05 function to get the Parabolic SAR signal.
6. Iterate Through Open Positions:
for (int i = ttlorder - 1; i >= 0; i--): Loop through all open positions in reverse order.
7. Get Position Details:
string position_Symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
ENUM_POSITION_TYPE type = sc_position.PositionType();: Retrieves the type of the current position.
8. Check if Position Matches EA Criteria:
if ((position_Symbol == SPC) && (sc_position.Magic() == magicEA)): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
9. Calculate Current Profit:
double pos_profit = sc_position.Profit();: Retrieves the profit of the position.
double pos_swap = sc_position.Swap();: Retrieves the swap of the position.
double pos_comm = sc_position.Commission();: Retrieves the commission of the position.
double cur_profit = NormalizeDouble(pos_profit + pos_swap + pos_comm, 2);: Calculates the current profit.
10. Close Profitable Buy Positions if Trend is Down:
if (type == POSITION_TYPE_BUY && cur_profit > 0.02 && hps == dw): Checks if the position is a buy, profitable, and the trend is down.
RefreshTick();: Calls the RefreshTick function to update the tick data.
orclose = sc_trade.PositionClose(position_Symbol, slip);: Attempts to close the buy position.
PrintFormat("Close #%I64d %s %s", position_ticket, position_Symbol, EnumToString(type));: Prints information about the closure.
if (orclose) PbarB = iTime(SPC, TFt, 0);: If the position was successfully closed, updates the last bar time for buy positions.
11. Close Profitable Sell Positions if Trend is Up:
if (type == POSITION_TYPE_SELL && cur_profit > 0.02 && hps == up): Checks if the position is a sell, profitable, and the trend is up.
RefreshTick();: Calls the RefreshTick function to update the tick data.
orclose = sc_trade.PositionClose(position_Symbol, slip);: Attempts to close the sell position.
PrintFormat("Close #%I64d %s %s", position_ticket, position_Symbol, EnumToString(type));: Prints information about the closure.
if (orclose) PbarS = iTime(SPC, TFt, 0);: If the position was successfully closed, updates the last bar time for sell positions.
12. Output Information if Position is Not Closed:
else if (hps == up) PrintFormat("Not Closed yet #%I64d %s %s", position_ticket, position_Symbol, isgood);: Prints a message if the position is not closed because the trend is still up.
else if (hps == dw) PrintFormat("Not Closed yet #%I64d %s %s", position_ticket, position_Symbol, isgood);: Prints a message if the position is not closed because the trend is still down.
13. Return Result:
return (orclose);: Returns whether any position was successfully closed.
Summary
The CloseAllProfit function attempts to close all profitable positions based on specific criteria such as the Parabolic SAR signal and current profit. It resets the last error, initializes trade structures, retrieves position details, calculates current profit, and iterates through open positions to close them if they are profitable and match the criteria. This function helps manage open positions by closing them when they are profitable and the market trend indicates a potential reversal.
Let's break down the CheckProfit function of FiboPivotCandleBar Expert Advisor for MT5.
This function checks if any open positions of a specified type are in profit, according to certain criteria. Here’s a detailed breakdown of each part of the code:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
Set Profit Threshold:
double posprofit = sc_symbol.NormalizePrice(5 * pip);: Sets the profit threshold to 5 pips, normalized for the current symbol.
3. Initialize Profit Flag:
bool inprofit = false;: Initializes the flag to indicate if any position is in profit to false.
4. Get Total Open Positions:
int ttlorder = PositionsTotal();: Retrieves the total number of open positions.
5. Iterate Through Open Positions:
for (int i = ttlorder - 1; i >= 0; i--): Loop through all open positions in reverse order.
6. Get Position Details:
string position_Symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
ENUM_POSITION_TYPE type = sc_position.PositionType();: Retrieves the type of the current position.
7. Check if Position Matches EA Criteria:
if ((position_Symbol == SPC) && (sc_position.Magic() == magicEA)): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
8. Calculate Current Profit:
double pos_profit = sc_position.Profit();: Retrieves the profit of the position.
double pos_swap = sc_position.Swap();: Retrieves the swap of the position.
double pos_comm = sc_position.Commission();: Retrieves the commission of the position.
double cur_profit = NormalizeDouble(pos_profit + pos_swap + pos_comm, 2);: Calculates the current profit, normalized to 2 decimal places.
9. Check if Position is in Profit:
if (type == intype && cur_profit > posprofit) inprofit = true;: If the position type matches the specified type and the current profit is greater than the profit threshold, sets the flag to true.
10. Return Result:
return (inprofit);: Returns whether any position is in profit.
Summary
The CheckProfit function checks if any open positions of a specified type are in profit based on a certain profit threshold. It calculates the pip value, sets the profit threshold, retrieves position details, calculates current profit, and iterates through open positions to check if they are in profit. This function helps determine if any positions are profitable and provides a simple boolean result.
Let's break down the CheckLoss function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::CheckLoss(ENUM_POSITION_TYPE intype)
This function checks if any open positions of a specified type are in loss, according to certain criteria. Here’s a detailed breakdown of each part of the code:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
2. Set Loss Threshold:
double posloss = sc_symbol.NormalizePrice(5 * pip);: Sets the loss threshold to 5 pips, normalized for the current symbol.
3. Initialize Loss Flag:
bool inloss = false;: Initializes the flag to indicate if any position is in loss to false.
4. Get Total Open Positions:
int ttlorder = PositionsTotal();: Retrieves the total number of open positions.
5. Iterate Through Open Positions:
for (int i = ttlorder - 1; i >= 0; i--): Loop through all open positions in reverse order.
6. Get Position Details:
string position_Symbol = PositionGetSymbol(i);: Retrieves the symbol of the current position.
ENUM_POSITION_TYPE type = sc_position.PositionType();: Retrieves the type of the current position.
7. Check if Position Matches EA Criteria:
if ((position_Symbol == SPC) && (sc_position.Magic() == magicEA)): Checks if the position belongs to the Expert Advisor (EA) by matching the symbol and magic number.
8. Calculate Current Profit:
double pos_profit = sc_position.Profit();: Retrieves the profit of the position.
double pos_swap = sc_position.Swap();: Retrieves the swap of the position.
double pos_comm = sc_position.Commission();: Retrieves the commission of the position.
double cur_profit = NormalizeDouble(pos_profit + pos_swap + pos_comm, 2);: Calculates the current profit, normalized to 2 decimal places.
9. Check if Position is in Loss:
if (type == intype && cur_profit < -posloss) inloss = true;: If the position type matches the specified type and the current profit is less than the negative loss threshold, sets the flag to true.
10. Return Result:
return (inloss);: Returns whether any position is in loss.
Summary
The CheckLoss function checks if any open positions of a specified type are in loss based on a certain loss threshold. It calculates the pip value, sets the loss threshold, retrieves position details, calculates current profit, and iterates through open positions to check if they are in loss. This function helps determine if any positions are losing and provides a simple boolean result.
Let's break down the CheckProfitLoss function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::CheckProfitLoss(void)
This function checks the profit and loss conditions of open positions and decides whether to close certain positions based on those conditions. Here’s a detailed breakdown of each part of the code:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Initialize Variables:
bool closeinloss = false;: Initializes a flag to indicate if any position was closed in loss.
string isloss = "due stop in loss.";: A message to indicate the reason for closure due to stop loss.
3. Check Conditions for Profit and Loss:
bool BuyProfitSellLoss = (xob > 0 && CheckProfit(POSITION_TYPE_BUY)) && (xos > 0 && CheckLoss(POSITION_TYPE_SELL));: Checks if there are buy positions in profit and sell positions in loss.
bool SellProfitBuyLoss = (xos > 0 && CheckProfit(POSITION_TYPE_SELL)) && (xob > 0 && CheckLoss(POSITION_TYPE_BUY));: Checks if there are sell positions in profit and buy positions in loss.
4. Close Positions Based on Conditions:
Close Sell Positions:
if (BuyProfitSellLoss && !SellProfitBuyLoss): If buy positions are in profit and sell positions are in loss, and the reverse is not true:
if (CloseSellPositions()): Attempts to close sell positions.
PrintFormat("Close Sell %s %s %s", SPC, EnumToString(POSITION_TYPE_BUY), isloss);: Prints a message indicating the closure.
closeinloss = true;: Sets the flag to true if positions were closed.
Close Buy Positions:
if (SellProfitBuyLoss && !BuyProfitSellLoss): If sell positions are in profit and buy positions are in loss, and the reverse is not true:
if (CloseBuyPositions()): Attempts to close buy positions.
PrintFormat("Close Buy %s %s %s", SPC, EnumToString(POSITION_TYPE_SELL), isloss);: Prints a message indicating the closure.
closeinloss = true;: Sets the flag to true if positions were closed.
5. Return Result:
return (closeinloss);: Returns whether any position was closed in loss.
Summary
The CheckProfitLoss function checks the profit and loss conditions of open positions and decides whether to close certain positions based on those conditions. It resets the last error, initializes variables, checks conditions for buy profit and sell loss (and vice versa), and closes positions if the conditions are met. This function helps manage open positions by closing them when necessary to lock in profits or limit losses.
Let's break down the CheckClose function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::CheckClose(void)
This function checks the history of closed deals within a certain timeframe and sends alerts based on whether the closed positions were profitable or not. Here’s a detailed breakdown of each part of the code:
void SFPCB::CheckClose(void)
{
//---
//--
ResetLastError();
Pips();
//--
datetime to=TimeCurrent();
datetime from=to-(60);
closetime=TimeCurrent()-(3); // 3 seconds ago
//--- request the entire history
HistorySelect(from,to);
//--- total number in the list of deals
int deals=HistoryDealsTotal();
//--
datetime deal_time =0; // time of a deal execution
ulong deal_ticket =0; // deal ticket
long deal_magic =0; // deal magic number
long deal_type =0; // Order Type
double deal_price =0.0; // deal/order CLOSE price
double deal_profit =0.0; // deal profit
double deal_swap =0.0; // position swap
double deal_comm =0.0; // position commission
string deal_symbol =""; // symbol of the deal
ENUM_DEAL_ENTRY deal_entry =0; // enum deal entry
double profit_loss =0.0; // Order profit or loss
//--
//--- go through deals in a loop
for(int z=deals-1; z>=0 && !IsStopped(); z--)
{
deal_ticket = HistoryDealGetTicket(z);
deal_symbol = HistoryDealGetString(deal_ticket,DEAL_SYMBOL);
deal_magic = HistoryDealGetInteger(deal_ticket,DEAL_MAGIC);
deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket,DEAL_ENTRY);
deal_type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(deal_ticket,DEAL_TYPE);
//--
if(deal_symbol==SPC && deal_magic==magicEA)
{
if((deal_entry==DEAL_ENTRY_OUT)||(deal_entry==DEAL_ENTRY_OUT_BY))
{
deal_time = (datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME);
if((deal_time>0) && (deal_time>=closetime))
{
deal_price = HistoryDealGetDouble(deal_ticket,DEAL_PRICE);
deal_profit = HistoryDealGetDouble(deal_ticket,DEAL_PROFIT);
deal_swap = HistoryDealGetDouble(deal_ticket,DEAL_SWAP);
deal_comm = HistoryDealGetDouble(deal_ticket,DEAL_COMMISSION);
profit_loss = NormalizeDouble(deal_profit+deal_swap+deal_comm,2);
string xtype = deal_type==DEAL_TYPE_BUY ? "SELL" : deal_type==DEAL_TYPE_SELL ? "BUY": "";
//--
if(profit_loss>0)
{
string ckclose="Close "+xtype+" Position on "+SPC+" at price : "+DoubleToString(deal_price,dgts)+
" OrderCloseTime(): "+TimeToString(deal_time,TIME_DATE|TIME_MINUTES)+
" in profit : "+DoubleToString(profit_loss,2);
Do_Alerts(ckclose);
}
if(profit_loss<=0)
{
string ckclose="Close "+xtype+" Position on "+SPC+" at price : "+DoubleToString(deal_price,dgts)+
" OrderCloseTime(): "+TimeToString(deal_time,TIME_DATE|TIME_MINUTES)+
" in loss : "+DoubleToString(profit_loss,2);
Do_Alerts(ckclose);
}
//--
break;
}
}
}
}
//---
return;
//----
} //-end CheckClose()
//---------//
Function Explanation
Detailed Breakdown:
1. Reset Last Error:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Calculate Pip Value:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
3. Set Time Variables:
datetime to = TimeCurrent();: Gets the current time.
datetime from = to - 60;: Sets the start of the time window to 60 seconds ago.
closetime = TimeCurrent() - 3;: Sets the close time to 3 seconds ago.
4. Request History:
HistorySelect(from, to);: Requests the entire history within the specified time window.
5. Initialize Deal Variables:
Variables such as deal_time, deal_ticket, deal_magic, deal_type, deal_price, deal_profit, deal_swap, deal_comm, deal_symbol, deal_entry, and profit_loss are initialized to hold the details of each deal.
6. Iterate Through Deals:
for (int z = deals - 1; z >= 0 && !IsStopped(); z--): Loops through all deals in reverse order, checking each one unless the trading is stopped.
7. Get Deal Details:
deal_ticket = HistoryDealGetTicket(z);: Retrieves the ticket number of the current deal.
deal_symbol = HistoryDealGetString(deal_ticket, DEAL_SYMBOL);: Retrieves the symbol of the current deal.
deal_magic = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);: Retrieves the magic number of the current deal.
deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket, DEAL_ENTRY);: Retrieves the entry type of the current deal.
deal_type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(deal_ticket, DEAL_TYPE);: Retrieves the type of the current deal.
8. Check if Deal Matches EA Criteria:
if (deal_symbol == SPC && deal_magic == magicEA): Checks if the deal belongs to the Expert Advisor (EA) by matching the symbol and magic number.
9. Check if Deal is Closed:
if ((deal_entry == DEAL_ENTRY_OUT) || (deal_entry == DEAL_ENTRY_OUT_BY)): Checks if the deal is a closed deal.
10. Check Deal Time:
if ((deal_time > 0) && (deal_time >= closetime)): Checks if the deal time is valid and within the specified time window.
11. Get Deal Details:
Retrieves the close price, profit, swap, and commission of the deal, and calculates the total profit or loss.
12. Send Alerts:
Profit:
if (profit_loss > 0): If the deal was profitable, constructs and sends an alert message with the profit details.
Loss:
else: If the deal was not profitable, constructs and sends an alert message with the loss details.
13. Return Statement:
return;: The function returns after processing all deals.
Summary
The CheckClose function checks the history of closed deals within a specified timeframe and sends alerts based on whether the closed positions were profitable or not. It resets the last error, calculates the pip value, sets time variables, requests history, retrieves deal details, checks if deals match EA criteria, and sends alerts for profitable or unprofitable deals. This function helps keep track of closed positions and provides feedback on their performance.
Let's break down the TodayOrders function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::TodayOrders(void)
This function tracks today's orders and calculates the floating and closed profits for the current trading day. Here’s a detailed breakdown of each part of the code:
void SFPCB::TodayOrders(void)
{
//---
//--
ResetLastError();
//--
datetime from=StringToTime(ReqDate(ThisTime(day),0,0));
datetime to=TimeCurrent();
//--- request the entire history
HistorySelect(from,to);
//--- total number in the list of deals
int deals=HistoryDealsTotal();
//--
datetime deal_time =0; // time of a deal execution
ulong deal_ticket =0; // deal ticket
long deal_magic =0; // deal magic number
long deal_type =0; // Order Type
double deal_price =0.0; // deal/order CLOSE price
double deal_profit =0.0; // deal profit
double deal_swap =0.0; // position swap
double deal_comm =0.0; // position commission
ENUM_DEAL_ENTRY deal_entry =0; // enum deal entry
//--
string pos_symbol =""; // Position symbol
fixclprofit =0.0; // Order Close profit
floatprofit =0.0; // float position profit
oBm=0; // Order buy
oSm=0; // Order sell
//--
int totalorder=PositionsTotal();
//--
for(int i=0; i<totalorder && !IsStopped(); i++)
{
pos_symbol = PositionGetSymbol(i);
long magic = sc_position.Magic();
if(sc_position.Symbol() == pos_symbol && magic==magicEA)
{
//--
ENUM_POSITION_TYPE opstype = sc_position.PositionType();
if(opstype == POSITION_TYPE_BUY) {oBm++; floatprofit += sc_position.Profit();}
if(opstype == POSITION_TYPE_SELL) {oSm++; floatprofit += sc_position.Profit();}
//--
}
}
xtto=oBm+oSm;
//--
//--- go through deals in a loop
for(int z=0; z<deals && !IsStopped(); z++)
{
deal_ticket = HistoryDealGetTicket(z);
deal_magic = HistoryDealGetInteger(deal_ticket,DEAL_MAGIC);
deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket,DEAL_ENTRY);
deal_type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(deal_ticket,DEAL_TYPE);
if(deal_magic==magicEA)
{
if((deal_entry==DEAL_ENTRY_OUT)||(deal_entry==DEAL_ENTRY_OUT_BY))
{
deal_time = (datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME);
//--
if((deal_time>0) && (deal_time>=from))
{
deal_profit = HistoryDealGetDouble(deal_ticket,DEAL_PROFIT);
deal_swap = HistoryDealGetDouble(deal_ticket,DEAL_SWAP);
deal_comm = HistoryDealGetDouble(deal_ticket,DEAL_COMMISSION);
//--
fixclprofit += NormalizeDouble(deal_profit+deal_swap+deal_comm,2);
}
}
}
}
//---
return;
//----
} //-end TodayOrders()
//---------//
Function Explanation
Detailed Breakdown:
1. Reset Last Error:
ResetLastError();: Resets the last error code to ensure any previous errors do not affect the current operation.
2. Set Time Variables:
datetime from = StringToTime(ReqDate(ThisTime(day), 0, 0));: Converts the start of the day to a datetime format.
datetime to = TimeCurrent();: Gets the current time.
3. Request History:
HistorySelect(from, to);: Requests the entire history within the specified time window.
4. Total Number of Deals:
int deals = HistoryDealsTotal();: Retrieves the total number of deals in the history.
5. Initialize Deal Variables:
Variables such as deal_time, deal_ticket, deal_magic, deal_type, deal_price, deal_profit, deal_swap, deal_comm, deal_entry, pos_symbol, fixclprofit, floatprofit, oBm, and oSm are initialized to hold the details of each deal and various metrics.
6. Get Total Open Positions:
int totalorder = PositionsTotal();: Retrieves the total number of open positions.
7. Process Open Positions:
for (int i = 0; i < totalorder && !IsStopped(); i++): Loops through all open positions.
Retrieves position details and updates metrics such as oBm, oSm, and floatprofit.
8. Update Total Orders:
xtto = oBm + oSm;: Updates the total number of orders.
9. Process Deals in History:
for (int z = 0; z < deals && !IsStopped(); z++): Loops through all deals in the history.
Retrieves deal details and updates metrics such as fixclprofit.
10. Return Statement:
return;: The function returns after processing all deals and open positions.
Summary
The TodayOrders function retrieves and processes all orders placed within the current day, updating various metrics related to orders and profits. It resets the last error, sets time variables, requests history, retrieves position and deal details, updates metrics, and processes both open positions and historical deals. This function helps keep track of the day's trading activity and provides insights into profits and order counts.
Let's break down the MLots function of FiboPivotCandleBar Expert Advisor for MT5.
double SFPCB::MLots(void)
This function calculates the lot size for a given trade based on the current symbol and various risk parameters. Here’s a detailed breakdown of each part of the code:
string symbx = SPC;: Sets the symbol used for the calculations.
double Lsize = 0.0;: Initializes the lot size to 0.
double sym_Lm = 0.0;: Initializes the maximum lot size based on the symbol.
string sym_use = "";: Initializes the symbol to be used for further calculations.
int pil;: Variable to determine the type of currency.
int Lpair;: Position of USD in the symbol.
int xsym = -1;: Helper variable for symbol calculations.
2. Extract Currency Parts:
string sCur1 = StringSubstr(symbx, posCur1, 3);: Extracts the first currency part from the symbol.
string sCur2 = StringSubstr(symbx, posCur2, 3);: Extracts the second currency part from the symbol.
3. Determine Currency Type:
Based on sCur1, sets pil to the corresponding value to determine the currency type.
4. Set Symbol for Calculations:
switch (pil): Sets sym_use based on the currency type determined.
5. Find USD in Symbol:
Lpair = StringFind(sym_use, "USD", 0);: Finds the position of USD in sym_use.
6. Set Current Symbol:
CurrentSymbolSet();: Sets the current symbol for trading.
7. Get Contract and Account Details:
Retrieves contract size, free margin, leverage, and bid price for the symbol.
8. Get Maximum and Minimum Lot Sizes:
double Lmaxs = SymbolInfoDouble(symbx, SYMBOL_VOLUME_MAX);: Retrieves the maximum lot size allowed.
double Lmins = SymbolInfoDouble(symbx, SYMBOL_VOLUME_MIN);: Retrieves the minimum lot size allowed.
9. Calculate Risk and Percentage Use:
double useRisk = (Risk / 100.0);: Calculates the risk percentage to be used.
double PctUse = ((100.0 - Risk) / 100.0);: Calculates the percentage of the account to use.
10. Calculate Lot Sizes Based on Margin and Leverage:
double NZ1 = NonZeroDiv(AFMar * AFLev, csize);: Calculates the lot size based on account free margin and leverage.
double NZ2 = NonZeroDiv(AFMar * AFLev, symbid);: Calculates the lot size based on account free margin and bid price.
11. Determine Maximum Lot Size:
Based on the position of USD in the symbol, determines sym_Lm.
12. Normalize and Adjust Lot Size:
Normalizes and adjusts the lot size based on useRisk and LotPS.
13. Set Final Lot Size Based on Risk:
If mmlot is DynamLot, adjusts the lot size based on PctUse.
Otherwise, sets the lot size to Lots.
14. Ensure Lot Size within Bounds:
Ensures the lot size is within the minimum and maximum bounds.
15. Return Final Lot Size:
Returns the final calculated and normalized lot size.
Summary
The MLots function calculates the lot size for a given trade based on the current symbol and various risk parameters. It initializes variables, extracts currency parts, determines the currency type, sets the symbol for calculations, retrieves contract and account details, calculates risk and percentage use, determines the maximum lot size, normalizes and adjusts the lot size, and ensures it is within bounds. This function helps manage risk by calculating the appropriate lot size for trading.
Let's break down the LotDig function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::LotDig(void)
This function determines the number of decimal places to use for lot sizes based on the step size of the lot volume for the current symbol. Here’s a detailed breakdown of each part of the code:
double lots_step = SymbolInfoDouble(SPC, SYMBOL_VOLUME_STEP);: Retrieves the lot step size for the current symbol (SPC). The lot step size indicates the smallest increment by which the lot size can be adjusted.
1. Get Lot Step Size:
double lots_step = SymbolInfoDouble(SPC, SYMBOL_VOLUME_STEP);: Retrieves the lot step size for the current symbol (SPC). The lot step size indicates the smallest increment by which the lot size can be adjusted.
2. Determine Decimal Places:
if (lots_step == 0.01) ldig = 2;: If the lot step size is 0.01, sets the number of decimal places (ldig) to 2.
if (lots_step == 0.1) ldig = 1;: If the lot step size is 0.1, sets the number of decimal places (ldig) to 1.
if (lots_step == 1.0) ldig = 0;: If the lot step size is 1.0, sets the number of decimal places (ldig) to 0.
3. Return Result:
return (ldig);: Returns the number of decimal places to use for lot sizes.
Summary
The LotDig function determines the number of decimal places to use for lot sizes based on the step size of the lot volume for the current symbol. It retrieves the lot step size, checks its value, and sets the number of decimal places accordingly. This function ensures that the lot sizes are formatted correctly based on the smallest allowable increment.
Let's break down the NonZeroDiv function of FiboPivotCandleBar Expert Advisor for MT5.
This function performs a safe division of two values, ensuring that division by zero is handled appropriately. Here’s a detailed breakdown of each part of the code:
ouble resval = 0.0;: Initializes the result value (resval) to 0.0.
2. Check for Division by Zero:
if (val1 == 0.0 || val2 == 0.0): Checks if either of the input values (val1 or val2) is 0.0.
resval = 0.00;: If either value is zero, sets the result value to 0.00.
else: If neither value is zero:
resval = val1 / val2;: Performs the division and assigns the result to resval.
3. Return Result:
return (resval);: Returns the result of the division.
Summary
The NonZeroDiv function performs a safe division of two values, ensuring that division by zero is handled appropriately. It initializes the result value, checks if either value is zero, performs the division if possible, and returns the result. This function is essential for preventing runtime errors due to division by zero, providing a robust way to handle division operations.
Let's break down the TradeInfo function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::TradeInfo(void)
This function writes comments on the chart to provide detailed information about the current trading status, account details, and recent order activities. Here’s a detailed breakdown of each part of the code:
Pips();: Calls the Pips function to calculate the pip value and related parameters for the symbol.
2. Calculate Spread:
double spread = SymbolInfoInteger(SPC, SYMBOL_SPREAD) / xpip;: Calculates the spread for the symbol.
3. Calculate Remaining Time:
rem = zntm - TimeCurrent();: Calculates the remaining time until a specific event.
4. Get Position Time Zone:
string postime = PosTimeZone();: Gets the position time zone.
5. Prepare Waiting Message:
string eawait = " - Waiting for active time..!";: Prepares a waiting message.
6. Initialize Comment String:
string comm = "";: Initializes the comment string.
7. Update Today's Orders:
TodayOrders();: Calls the TodayOrders function to update the order information.
8. Build Comment String:
Constructs the comment string with various details such as server date and time, broker information, expert name, account details, trading pairs, order details, and profit information.
9. Include Time Remaining if Applicable:
If the current time is before zntm, includes the remaining time in the comment string.
10. Display Comment on Chart:
Comment(comm);: Displays the comment string on the chart.
ChartRedraw(0);: Redraws the chart to update the displayed comment.
11. Return Statement:
return;: The function returns after updating the chart with the comment.
Summary
The TradeInfo function writes comments on the chart to provide detailed information about the current trading status, account details, and recent order activities. It calculates the pip value, spread, and remaining time, retrieves position time zone and order information, constructs a comprehensive comment string, and displays it on the chart. This function helps keep track of important trading information and provides a clear overview on the chart.
Let's break down the PosTimeZone function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::PosTimeZone(void)
This function determines the trading session's time zone based on the current time and predefined open and close times. It returns a string indicating whether the trading session is for today, the next day, or spans both days. Here’s a detailed breakdown of each part of the code:
string SFPCB::PosTimeZone(void)
{
//---
string tzpos="";
//--
if(ReqTime(zntm,day)>ThisTime(day))
{
tzpos=tz_opn+ " Next day to " +tz_cls + " Next day";
}
else
if(TimeCurrent()<znop)
{
if(ThisTime(day)==ReqTime(znop,day) && ThisTime(day)==ReqTime(zncl,day))
tzpos=tz_opn+" to " +tz_cls+ " Today";
//else
if(ThisTime(day)==ReqTime(znop,day) && ThisTime(day)<ReqTime(zncl,day))
tzpos=tz_opn+ " Today to " +tz_cls+ " Next day";
}
else
if(TimeCurrent()>=znop && TimeCurrent()<zncl)
{
if(ThisTime(day)<ReqTime(zncl,day))
tzpos=tz_opn+ " Today to " +tz_cls+ " Next day";
else
if(ThisTime(day)==ReqTime(zncl,day))
tzpos=tz_opn+" to " +tz_cls+ " Today";
}
else
if(ThisTime(day)==ReqTime(znop,day) && ThisTime(day)<ReqTime(zncl,day))
{
tzpos=tz_opn+" Today to " +tz_cls+ " Next day";
}
//--
return(tzpos);
//----
} //-end PosTimeZone()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Time Zone String:
string tzpos = "";: Initializes the time zone string to an empty string.
2. Check if Trading Session End Time is in the Next Day:
if (ReqTime(zntm, day) > ThisTime(day)): Checks if the trading session's end time (zntm) is in the next day compared to the current day.
tzpos = tz_opn + " Next day to " + tz_cls + " Next day";: Sets the time zone string to indicate the session spans to the next day.
3. Check if Current Time is Before Session's Open Time:
else if (TimeCurrent() < znop): Checks if the current time is before the session's open time (znop).
Same Day Open and Close:
if (ThisTime(day) == ReqTime(znop, day) && ThisTime(day) == ReqTime(zncl, day)): Checks if both the open and close times are on the same day.
tzpos = tz_opn + " to " + tz_cls + " Today";: Sets the time zone string to indicate the session is for today.
Open Today, Close Next Day:
else if (ThisTime(day) == ReqTime(znop, day) && ThisTime(day) < ReqTime(zncl, day)): Checks if the open time is today and the close time is in the next day.
tzpos = tz_opn + " Today to " + tz_cls + " Next day";: Sets the time zone string to indicate the session spans today and the next day.
Open Today, Close Next Day:
else if (ThisTime(day) == ReqTime(znop, day) && ThisTime(day) < ReqTime(zncl, day)): Checks if the open time is today and the close time is in the next day.
tzpos = tz_opn + " Today to " + tz_cls + " Next day";: Sets the time zone string to indicate the session spans today and the next day.
4. Check if Current Time is Between Session's Open and Close Times:
else if (TimeCurrent() >= znop && TimeCurrent() < zncl): Checks if the current time is between the session's open and close times.
Open Today, Close Next Day:
if (ThisTime(day) < ReqTime(zncl, day)): Checks if the close time is in the next day.
tzpos = tz_opn + " Today to " + tz_cls + " Next day";: Sets the time zone string to indicate the session spans today and the next day.
Same Day Close:
else if (ThisTime(day) == ReqTime(zncl, day)): Checks if the close time is on the same day.
tzpos = tz_opn + " to " + tz_cls + " Today";: Sets the time zone string to indicate the session is for today.
5. Return Result:
return (tzpos);: Returns the determined time zone string.
Summary
The PosTimeZone function determines the trading session's time zone based on the current time and predefined open and close times. It checks if the session spans today or the next day and constructs a string indicating the session's time zone accordingly. This function helps provide clear information about the trading session's timing.
Let's break down the Set_Time_Zone function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::Set_Time_Zone(void)
This function sets the time zones for various trading sessions and calculates the start and end times for each session based on the server time and GMT difference. Here’s a detailed breakdown of each part of the code:
void SFPCB::Set_Time_Zone(void)
{
//---
//-- Server Time==TimeCurrent()
datetime TTS=TimeTradeServer();
datetime GMT=TimeGMT();
//--
MqlDateTime svrtm,gmttm;
TimeToStruct(TTS,svrtm);
TimeToStruct(GMT,gmttm);
int svrhr=svrtm.hour; // Server time hour
int gmthr=gmttm.hour; // GMT time hour
int difhr=svrhr-gmthr; // Time difference Server time to GMT time
//--
int NZSGMT=12; // New Zealand Session GMT/UTC+12
int AUSGMT=10; // Australia Sydney Session GMT/UTC+10
int TOKGMT=9; // Asia Tokyo Session GMT/UTC+9
int EURGMT=0; // Europe London Session GMT/UTC 0
int USNGMT=-5; // US New York Session GMT/UTC-5
//--
int NZSStm=8; // New Zealand Session time start: 08:00 Local Time
int NZSCtm=17; // New Zealand Session time close: 17:00 Local Time
int AUSStm=7; // Australia Sydney Session time start: 07:00 Local Time
int AUSCtm=17; // Australia Sydney Session time close: 17:00 Local Time
int TOKStm=9; // Asia Tokyo Session time start: 09:00 Local Time
int TOKCtm=18; // Asia Tokyo Session time close: 18:00 Local Time
int EURStm=9; // Europe London Session time start: 09:00 Local Time
int EURCtm=19; // Europe London Session time close: 19:00 Local Time
int USNStm=8; // US New York Session time start: 08:00 Local Time
int USNCtm=17; // US New York Session time close: 17:00 Local Time
//--
int nzo = (NZSStm+difhr-NZSGMT)<0 ? 24+(NZSStm+difhr-NZSGMT) : (NZSStm+difhr-NZSGMT);
int nzc = (NZSCtm+difhr-NZSGMT)<0 ? 24+(NZSCtm+difhr-NZSGMT) : (NZSCtm+difhr-NZSGMT);
//--
int auo = (AUSStm+difhr-AUSGMT)<0 ? 24+(AUSStm+difhr-AUSGMT) : (AUSStm+difhr-AUSGMT);
int auc = (AUSCtm+difhr-AUSGMT)<0 ? 24+(AUSCtm+difhr-AUSGMT) : (AUSCtm+difhr-AUSGMT);
//--
int tko = (TOKStm+difhr-TOKGMT)<0 ? 24+(TOKStm+difhr-TOKGMT) : (TOKStm+difhr-TOKGMT);
int tkc = (TOKCtm+difhr-TOKGMT)<0 ? 24+(TOKCtm+difhr-TOKGMT) : (TOKCtm+difhr-TOKGMT);
//--
int euo = (EURStm+difhr-EURGMT)<0 ? 24+(EURStm+difhr-EURGMT) : (EURStm+difhr-EURGMT);
int euc = (EURCtm+difhr-EURGMT)<0 ? 24+(EURCtm+difhr-EURGMT) : (EURCtm+difhr-EURGMT);
//--
int uso = (USNStm+difhr-USNGMT)<0 ? 24+(USNStm+difhr-USNGMT) : (USNStm+difhr-USNGMT);
int usc = (USNCtm+difhr-USNGMT)<0 ? 24+(USNCtm+difhr-USNGMT) : (USNCtm+difhr-USNGMT);
if(usc==0||usc==24) usc=23;
//--
//---Trading on Custom Session
int _days00=ThisTime(day);
int _days10=ThisTime(day);
if(stsescuh>clsescuh) _days10=ThisTime(day)+1;
tmopcu=ReqDate(_days00,stsescuh,stsescum);
tmclcu=ReqDate(_days10,clsescuh,clsescum);
//--
//--Trading on New Zealand Session GMT/UTC+12
int _days01=ThisTime(hour)<nzc ? ThisTime(day)-1 : ThisTime(day);
int _days11=ThisTime(hour)<nzc ? ThisTime(day) : ThisTime(day)+1;
tmop01=ReqDate(_days01,nzo,0); // start: 08:00 Local Time == 20:00 GMT/UTC
tmcl01=ReqDate(_days11,nzc-1,59); // close: 17:00 Local Time == 05:00 GMT/UTC
//--
//--Trading on Australia Sydney Session GMT/UTC+10
int _days02=ThisTime(hour)<auc ? ThisTime(day)-1 : ThisTime(day);
int _days12=ThisTime(hour)<auc ? ThisTime(day) : ThisTime(day)+1;
tmop02=ReqDate(_days02,auo,0); // start: 07:00 Local Time == 21:00 GMT/UTC
tmcl02=ReqDate(_days12,auc-1,59); // close: 17:00 Local Time == 07:00 GMT/UTC
//--
//--Trading on Asia Tokyo Session GMT/UTC+9
int _days03=ThisTime(hour)<tkc ? ThisTime(day) : ThisTime(day)+1;
int _days13=ThisTime(hour)<tkc ? ThisTime(day) : ThisTime(day)+1;
tmop03=ReqDate(_days03,tko,0); // start: 09:00 Local Time == 00:00 GMT/UTC
tmcl03=ReqDate(_days13,tkc-1,59); // close: 18:00 Local Time == 09:00 GMT/UTC
//--
//--Trading on Europe London Session GMT/UTC 00:00
int _days04=ThisTime(hour)<euc ? ThisTime(day) : ThisTime(day)+1;
int _days14=ThisTime(hour)<euc ? ThisTime(day) : ThisTime(day)+1;
tmop04=ReqDate(_days04,euo,0); // start: 09:00 Local Time == 09:00 GMT/UTC
tmcl04=ReqDate(_days14,euc-1,59); // close: 19:00 Local Time == 19:00 GMT/UTC
//--
//--Trading on US New York Session GMT/UTC-5
int _days05=ThisTime(hour)<usc ? ThisTime(day) : ThisTime(day)+1;
int _days15=ThisTime(hour)<=usc ? ThisTime(day) : ThisTime(day)+1;
tmop05=ReqDate(_days05,uso,0); // start: 08:00 Local Time == 13:00 GMT/UTC
tmcl05=ReqDate(_days15,usc,59); // close: 17:00 Local Time == 22:00 GMT/UTC
//--
//--Not Use Trading Time Zone
if(trd_time_zone==No)
{
tmopno=ReqDate(ThisTime(day),0,15);
tmclno=ReqDate(ThisTime(day),23,59);
}
//--
Time_Zone();
//--
return;
//---
} //-end Set_Time_Zone()
//---------//
Function Explanation
Detailed Breakdown:
1. Retrieve Server and GMT Time:
datetime TTS = TimeTradeServer();: Gets the server time.
datetime GMT = TimeGMT();: Gets the GMT time.
2. Convert Time to Structured Format:
MqlDateTime svrtm, gmttm;: Declares structures to hold the server time and GMT time.
TimeToStruct(TTS, svrtm);: Converts the server time to structured time format.
TimeToStruct(GMT, gmttm);: Converts the GMT time to structured time format.
int svrhr = svrtm.hour;: Gets the hour component of the server time.
int gmthr = gmttm.hour;: Gets the hour component of the GMT time.
int difhr = svrhr - gmthr;: Calculates the time difference between the server time and GMT.
3. Define GMT/UTC Offsets for Various Trading Sessions:
Sets GMT offsets for New Zealand, Australia, Asia/Tokyo, Europe/London, and US/New York sessions.
4. Define Local Start and Close Times for Various Trading Sessions:
Sets local start and close times for each session.
5. Calculate Adjusted Start and Close Times for Each Session Based on Server Time Difference:
Adjusts the start and close times for New Zealand, Australia, Asia/Tokyo, Europe/London, and US/New York sessions based on the server time difference and session GMT offsets.
6. Set Custom Trading Session Times:
int _days00 = ThisTime(day);
int _days10 = ThisTime(day);
Adjusts the start and end days if the session crosses midnight.
tmopcu = ReqDate(_days00, stsescuh, stsescum);: Converts the start time to a string.
tmclcu = ReqDate(_days10, clsescuh, clsescum);: Converts the close time to a string.
7. Set Trading Session Times for Each Session:
Similar adjustments and conversions are made for New Zealand, Australia, Asia/Tokyo, Europe/London, and US/New York sessions.
8. Handle Non-Predefined Time Zone:
If trading time zone is not used, sets the open and close times for trading sessions to cover the entire day.
9. Call Time_Zone() Method:
Updates the time zone for the current session.
10. Return Statement:
return;: The function returns after setting the time zones.
1. Key Steps of Set Time Zone:
Retrieve Server and GMT Time:
Fetches the current server time and GMT time.
Converts these times into structured formats to extract the hour component.
2. Calculate Time Difference:
Computes the difference between the server time and GMT to understand the time zone offset.
3. Define Session GMT Offsets:
Sets predefined GMT offsets for major trading sessions: New Zealand, Australia Sydney, Asia Tokyo, Europe London, and US New York.
4. Local Session Start and Close Times:
Defines the start and close times for each trading session in local times.
5. Adjust Session Times:
Adjusts the local start and close times for each session using the server time difference and session GMT offsets.
6. Handle Custom Session Times:
Converts custom session start and end times to datetime format.
Adjusts the start and end days if the session crosses midnight.
7. Convert Times to Datetime:
Converts the adjusted session times to datetime format for accurate timing.
8. Fallback for Non-Predefined Time Zones:
Sets session start and close times to cover the entire day if not using predefined time zones.
Example:
For the New Zealand session:
The function adjusts the session times using GMT+12 offset.
Converts these times based on the server's current hour relative to GMT.
Ensures trading operations align with the correct New Zealand session times.
Purpose:
This function is essential for aligning trading activities with the correct time zones, ensuring that trades are executed within the allowed session times based on server time.
Summary
The Set_Time_Zone function in FiboPivotCandleBar Expert Advisor for MT5 calculates and sets the start and end times for various trading sessions based on the difference between the server time and GMT.
Let's break down the Time_Zone function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::Time_Zone(void)
This function sets the time zones for various trading sessions and determines the start and end times for each session based on the selected session type. Here’s a detailed breakdown of each part of the code:
tz_ses = "";: Initializes the time zone session string to an empty string.
2. Switch Statement to Set Time Zone Based on Selected Session Type:
switch (session): Checks the value of session and sets the time zone based on the selected session type.
Custom Session:
case Cus_Session: If the session type is Cus_Session, it converts the custom session times from strings to datetime and sets the relevant variables.
SesCuOp = StringToTime(tmopcu);: Converts the custom session open time string to datetime.
SesCuCl = StringToTime(tmclcu);: Converts the custom session close time string to datetime.
Sets zntm, znop, and zncl to the custom session open and close times.
Sets tz_ses to "Custom_Session".
Formats the custom session open and close times using the timehr function.
New Zealand Session:
Similar steps are followed for New Zealand, Australia, Asia/Tokyo, Europe/London, and US/New_York sessions. It sets the session open and close times, updates the relevant variables, and formats the times using the timehr function.
3. Set Time Zone if Not Using Predefined Sessions:
if (trd_time_zone == No): Checks if the trading time zone is not using predefined sessions.
Converts the non-predefined session times from strings to datetime and sets the relevant variables.
Sets tz_ses to "Not Use Time Zone".
Formats the non-predefined session open and close times using the timehr function.
4. Return Statement:
return;: The function returns after setting the time zones.
Summary
The Time_Zone function sets the time zones for various trading sessions and determines the start and end times for each session based on the selected session type. It initializes the time zone session string, uses a switch statement to set the time zone based on the selected session type, formats the session open and close times, and sets the time zone if not using predefined sessions. This function helps manage trading activities based on the specified time zones.
Let's break down the Trade_session function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::Trade_session(void)
This function checks if the current time falls within the defined trading session time frames and returns true if trading is allowed, otherwise false. Here’s a detailed breakdown of each part of the code:
bool trd_ses = false;: Initializes the flag indicating if trading is allowed in the current session to false.
ishour = ThisTime(hour);: Gets the current hour.
2. Update Time Zones if Hour has Changed:
if (ishour != onhour) Set_Time_Zone();: Checks if the current hour is different from the last checked hour (onhour) and updates the time zones if needed.
3. Get Current Server Time:
datetime tcurr = TimeCurrent();: Gets the current server time.
4. Switch Statement to Check Current Session Time:
switch (session): Checks the value of session and verifies if the current time (tcurr) falls within the defined trading session time frames.
Custom Session:
case Cus_Session: Checks if the current time is within the custom session open and close times.
if (tcurr >= SesCuOp && tcurr <= SesCuCl) trd_ses = true;: Sets trd_ses to true if the current time is within the custom session time frame.
New Zealand Session:
Similar checks are performed for New Zealand, Australia, Asia/Tokyo, Europe/London, and US/New_York sessions to determine if the current time falls within the respective session time frames.
5. Check Trading Allowed Outside Predefined Time Zones:
if (trd_time_zone == No): Checks if trading is not using predefined time zones.
if (tcurr >= SesNoOp && tcurr <= SesNoCl) trd_ses = true;: Sets trd_ses to true if the current time is within the non-predefined session time frame.
6. Update Last Checked Hour:
onhour = ishour;: Updates the last checked hour.
7. Return Result:
return (trd_ses);: Returns whether trading is allowed in the current session.
Summary
The Trade_session function checks if the current time falls within the defined trading session time frames and returns true if trading is allowed, otherwise false. It initializes variables, updates time zones if the hour has changed, gets the current server time, uses a switch statement to check if the current time is within the trading session, checks if trading is allowed when not using predefined time zones, and returns the result. This function ensures that trading activities occur only within allowed session times.
Let's break down the TradingDay function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::TradingDay(void)
This function returns the name of the current trading day based on the day of the week. Here’s a detailed breakdown of each part of the code:
string SFPCB::TradingDay(void)
{
//---
int trdday=ThisTime(dow);
switch(trdday)
{
case 0: daytrade="Sunday"; break;
case 1: daytrade="Monday"; break;
case 2: daytrade="Tuesday"; break;
case 3: daytrade="Wednesday"; break;
case 4: daytrade="Thursday"; break;
case 5: daytrade="Friday"; break;
case 6: daytrade="Saturday"; break;
}
return(daytrade);
//---
} //-end TradingDay()
//---------//
Function Explanation
Detailed Breakdown:
1. Get Current Day of the Week:
int trdday = ThisTime(dow);: Calls the ThisTime function with dow (day of the week) as the parameter to get the current day of the week.
2. Switch Statement for Day of the Week:
switch (trdday): Checks the value of trdday and sets the daytrade string to the corresponding day of the week.
case 0: daytrade = "Sunday"; break;: Sets daytrade to "Sunday" if trdday is 0.
case 1: daytrade = "Monday"; break;: Sets daytrade to "Monday" if trdday is 1.
case 2: daytrade = "Tuesday"; break;: Sets daytrade to "Tuesday" if trdday is 2.
case 3: daytrade = "Wednesday"; break;: Sets daytrade to "Wednesday" if trdday is 3.
case 4: daytrade = "Thursday"; break;: Sets daytrade to "Thursday" if trdday is 4.
case 5: daytrade = "Friday"; break;: Sets daytrade to "Friday" if trdday is 5.
case 6: daytrade = "Saturday"; break;: Sets daytrade to "Saturday" if trdday is 6.
3. Return Result:
return (daytrade);: Returns the name of the current trading day.
Summary
The TradingDay function returns the name of the current trading day based on the day of the week. It gets the current day of the week, uses a switch statement to set the daytrade string to the corresponding day name, and returns the result. This function provides an easy way to display the current trading day in a readable format.
Let's break down the TradingToday function of FiboPivotCandleBar Expert Advisor for MT5.
bool SFPCB::TradingToday(void)
This function checks whether trading is allowed today based on the day of the week and a predefined trading schedule. It returns true if trading is allowed and false otherwise. Here’s a detailed breakdown of each part of the code:
bool tradetoday = false;: Initializes the flag indicating if trading is allowed today to false.
int trdday = ThisTime(dow);: Calls the ThisTime function with dow (day of the week) as the parameter to get the current day of the week.
hariini = "No";: Initializes the variable indicating if today is a trading day to "No".
2. Set Up Trading Schedule Array:
int ttd[];: Declares an array to hold the trading schedule for each day of the week.
ArrayResize(ttd, 7);: Resizes the array to hold 7 elements (one for each day of the week).
Assigns the trading schedule for each day of the week to the corresponding element in the array:
ttd[0] = ttd0;: Sunday trading schedule.
ttd[1] = ttd1;: Monday trading schedule.
ttd[2] = ttd2;: Tuesday trading schedule.
ttd[3] = ttd3;: Wednesday trading schedule.
ttd[4] = ttd4;: Thursday trading schedule.
ttd[5] = ttd5;: Friday trading schedule.
ttd[6] = ttd6;: Saturday trading schedule.
3. Check Trading Schedule for Today:
if (ttd[trdday] == Yes): Checks if trading is allowed today based on the current day of the week.
tradetoday = true;: Sets the flag indicating trading is allowed today to true.
hariini = "Yes";: Updates the variable indicating today is a trading day to "Yes".
4. Return Result:
return (tradetoday);: Returns whether trading is allowed today.
Summary
The TradingToday function checks whether trading is allowed today based on the day of the week and a predefined trading schedule. It initializes variables, sets up a trading schedule array, checks the schedule for the current day, and returns whether trading is allowed. This function helps manage trading activities by ensuring they only occur on allowed days.
Let's break down the timehr function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::timehr(int hr, int mn)
This function converts hours and minutes into a formatted time string (HH:MM). Here’s a detailed breakdown of each part of the code:
string scon = "";: Initializes the time string to an empty string.
2. Format Minutes:
string men = mn == 0 ? "00" : string(mn);: Checks if the minutes (mn) is 0 and sets men to "00"; otherwise, converts mn to a string.
3. Handle 24-Hour Format for Hours:
int shr = hr == 24 ? 0 : hr;: Checks if the hours (hr) is 24 and sets shr to 0 (to handle 24-hour format); otherwise, uses hr.
4. Format Hours and Construct Time String:
if (shr < 10) scon = "0" + string(shr) + ":" + men;: Checks if shr is less than 10 and prepends a "0" to the hours to maintain a two-digit format, then combines with men.
else scon = string(shr) + ":" + men;: If shr is 10 or greater, directly combines it with men.
5. Return Result:
return (scon);: Returns the formatted time string.
Example Usage:
If hr is 8 and mn is 0, the function will return "08:00".
If hr is 14 and mn is 30, the function will return "14:30".
If hr is 24 and mn is 45, the function will return "00:45".
Summary
The timehr function converts hours and minutes into a formatted time string (HH:MM). It handles the conversion of 0 minutes to "00", formats hours to two digits if less than 10, and ensures the correct representation of 24 hours as 00. This function is essential for displaying time in a consistent and readable format.
Let's break down the ReqDate function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::ReqDate(int d, int h, int m)
This function constructs a formatted date string based on the provided day, hour, and minute, and the current date. Here’s a detailed breakdown of each part of the code:
MqlDateTime mdt;: Declares a structure to hold the current time.
datetime t = TimeCurrent(mdt);: Gets the current time and populates mdt with the structured time.
2. Extract Date and Time Components:
x_year = mdt.year;: Extracts the year from the current time.
x_mon = mdt.mon;: Extracts the month from the current time.
x_day = d;: Sets the day to the provided value (d).
x_hour = h;: Sets the hour to the provided value (h).
x_min = m;: Sets the minute to the provided value (m).
x_sec = mdt.sec;: Extracts the seconds from the current time.
3. Construct Formatted Date String:
string mdr = string(x_year) + "." + string(x_mon) + "." + string(x_day) + " " + timehr(x_hour, x_min);: Constructs the formatted date string using the extracted components and the timehr function to format the hours and minutes.
4. Return Result:
.return (mdr);: Returns the formatted date string.
Summary
The ReqDate function constructs a formatted date string based on the provided day, hour, and minute, as well as the current date. It gets the current time, extracts the relevant date and time components, constructs a formatted string, and returns it. This function helps in generating readable date and time strings for various purposes within the Expert Advisor.
Let's break down the ThisTime function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::ThisTime(const int reqmode)
This function returns a specific component of the current time based on the requested mode. Here’s a detailed breakdown of each part of the code:
int MCEA::ThisTime(const int reqmode)
{
//---
MqlDateTime tm;
TimeCurrent(tm);
int valtm=0;
//--
switch(reqmode)
{
case 0: valtm=tm.year; break; // Return Year
case 1: valtm=tm.mon; break; // Return Month
case 2: valtm=tm.day; break; // Return Day
case 3: valtm=tm.hour; break; // Return Hour
case 4: valtm=tm.min; break; // Return Minutes
case 5: valtm=tm.sec; break; // Return Seconds
case 6: valtm=tm.day_of_week; break; // Return Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)
case 7: valtm=tm.day_of_year; break; // Return Day number of the year (January 1st is assigned the number value of zero)
}
//--
return(valtm);
//---
} //-end ThisTime()
//---------//
Function Explanation
Detailed Breakdown:
1. Get Current Time in Structured Format:
MqlDateTime tm;: Declares a structure to hold the current time.
TimeCurrent(tm);: Gets the current time and populates tm with the structured time.
2. Initialize Return Value:
int valtm = 0;: Initializes the return value to 0.
3. Switch Statement for Requested Time Component:
switch (reqmode): Checks the value of reqmode and sets valtm to the corresponding component of the current time.
case 0: valtm = tm.year; break;: Sets valtm to the current year.
case 1: valtm = tm.mon; break;: Sets valtm to the current month.
case 2: valtm = tm.day; break;: Sets valtm to the current day.
case 3: valtm = tm.hour; break;: Sets valtm to the current hour.
case 4: valtm = tm.min; break;: Sets valtm to the current minute.
case 5: valtm = tm.sec; break;: Sets valtm to the current second.
case 6: valtm = tm.day_of_week; break;: Sets valtm to the current day of the week.
case 7: valtm = tm.day_of_year; break;: Sets valtm to the current day of the year.
4. Return Result:
return (valtm);: Returns the requested component of the current time.
Summary
The ThisTime function returns a specific component of the current time based on the requested mode. It gets the current time, extracts the relevant component using a switch statement, and returns the result. This function allows for easy retrieval of various parts of the current time, such as the year, month, day, hour, minute, second, day of the week, or day of the year.
Let's break down the ReqTime function of FiboPivotCandleBar Expert Advisor for MT5.
int SFPCB::ReqTime(datetime reqtime, const int reqmode)
This function returns a specific component of a given datetime based on the requested mode. Here’s a detailed breakdown of each part of the code:
int MCEA::ReqTime(datetime reqtime,
const int reqmode)
{
MqlDateTime tm;
TimeToStruct(reqtime,tm);
int valtm=0;
//--
switch(reqmode)
{
case 0: valtm=tm.year; break; // Return Year
case 1: valtm=tm.mon; break; // Return Month
case 2: valtm=tm.day; break; // Return Day
case 3: valtm=tm.hour; break; // Return Hour
case 4: valtm=tm.min; break; // Return Minutes
case 5: valtm=tm.sec; break; // Return Seconds
case 6: valtm=tm.day_of_week; break; // Return Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)
case 7: valtm=tm.day_of_year; break; // Return Day number of the year (January 1st is assigned the number value of zero)
}
//--
return(valtm);
//---
} //-end ReqTime()
//---------//
Function Explanation
Detailed Breakdown:
1. Convert Given Datetime to Structured Format:
MqlDateTime tm;: Declares a structure to hold the given datetime.
TimeToStruct(reqtime, tm);: Converts the given datetime (reqtime) and populates tm with the structured time.
2. Initialize Return Value:
int valtm = 0;: Initializes the return value to 0.
3. Switch Statement for Requested Time Component:
switch (reqmode): Checks the value of reqmode and sets valtm to the corresponding component of the given datetime.
case 0: valtm = tm.year; break;: Sets valtm to the year of reqtime.
case 1: valtm = tm.mon; break;: Sets valtm to the month of reqtime.
case 2: valtm = tm.day; break;: Sets valtm to the day of reqtime.
case 3: valtm = tm.hour; break;: Sets valtm to the hour of reqtime.
case 4: valtm = tm.min; break;: Sets valtm to the minute of reqtime.
case 5: valtm = tm.sec; break;: Sets valtm to the second of reqtime.
case 6: valtm = tm.day_of_week; break;: Sets valtm to the day of the week of reqtime.
case 7: valtm = tm.day_of_year; break;: Sets valtm to the day number of the year of reqtime.
4. Return Result:
return (valtm);: Returns the requested component of the given datetime.
Summary
The ReqTime function returns a specific component of a given datetime based on the requested mode. It converts the given datetime to structured format, extracts the relevant component using a switch statement, and returns the result. This function is useful for retrieving various parts of a datetime value, such as the year, month, day, hour, minute, second, day of the week, or day of the year.
Let's break down the AccountMode function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::AccountMode()
This function checks the account trade mode (Demo, Contest, or Real) and returns it as a string. Here’s a detailed breakdown of each part of the code:
string MCEA::AccountMode() // function: to known account trade mode
{
//----
//--- Demo, Contest or Real account
ENUM_ACCOUNT_TRADE_MODE account_type=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_MODE);
//---
trade_mode="";
//--
switch(account_type)
{
case ACCOUNT_TRADE_MODE_DEMO:
trade_mode="Demo";
break;
case ACCOUNT_TRADE_MODE_CONTEST:
trade_mode="Contest";
break;
default:
trade_mode="Real";
break;
}
//--
return(trade_mode);
//----
} //-end AccountMode()
//---------//
Function Explanation
Detailed Breakdown:
1. Check Account Trade Mode:
ENUM_ACCOUNT_TRADE_MODE account_type = (ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_MODE);: Retrieves the account trade mode as an integer using AccountInfoInteger and casts it to the ENUM_ACCOUNT_TRADE_MODE enum type.
2. Initialize Trade Mode String:
trade_mode = "";: Initializes the trade_mode string to an empty string.
3. Switch Statement to Determine Account Type:
switch (account_type): Checks the value of account_type and sets trade_mode to the corresponding account type.
case ACCOUNT_TRADE_MODE_DEMO: trade_mode = "Demo"; break;: Sets trade_mode to "Demo" if the account type is demo.
case ACCOUNT_TRADE_MODE_CONTEST: trade_mode = "Contest"; break;: Sets trade_mode to "Contest" if the account type is contest.
default: trade_mode = "Real"; break;: Sets trade_mode to "Real" for any other account types (default case).
4. Return Result:
return (trade_mode);: Returns the trade_mode string.
Summary
The AccountMode function checks the account trade mode (Demo, Contest, or Real) and returns it as a string. It retrieves the account trade mode, initializes the trade mode string, uses a switch statement to determine the account type, and returns the result. This function helps identify the type of account being used, which can be useful for logging, reporting, or modifying behavior based on the account type.
Let's break down the Do_Alerts function of FiboPivotCandleBar Expert Advisor for MT5.
void SFPCB::Do_Alerts(string msgText)
This function sends various types of alerts (print, pop-up, email, and push notifications) with a given message. Here’s a detailed breakdown of each part of the code:
Print("--- " + SPC + ": " + msgText + "\n--- at: ", TimeToString(TimeCurrent(), TIME_DATE | TIME_MINUTES));: Prints the alert message to the terminal with the current date and time.
2. Check if Pop-up Alerts are Enabled:
if (alerts == Yes): Checks if pop-up alerts are enabled.
Alert("--- " + SPC + ": " + msgText + "--- at: ", TimeToString(TimeCurrent(), TIME_DATE | TIME_MINUTES));: Shows a pop-up alert with the message and current date and time if enabled.
3. Check if Email Alerts are Enabled:
if (UseEmailAlert == Yes): Checks if email alerts are enabled.
SendMail(expname, "--- " + SPC + " " + TF2Str(PERIOD_CURRENT) + ": " + msgText + "\n--- at: " + TimeToString(TimeCurrent(), TIME_DATE | TIME_MINUTES));: Sends an email with the alert message and current date and time if enabled.
4. Check if Push Notifications are Enabled:
if (UseSendnotify == Yes): Checks if push notifications are enabled.
SendNotification(expname + "--- " + SPC + " " + TF2Str(PERIOD_CURRENT) + ": " + msgText + "\n--- at: " + TimeToString(iTime(SPC, 0, 0), TIME_DATE | TIME_MINUTES));: Sends a push notification with the alert message and current date and time if enabled.
5. Return from the Function:
return;: The function returns after sending the alerts.
Summary
The Do_Alerts function sends various types of alerts (print, pop-up, email, and push notifications) with a given message. It prints the alert message to the terminal, shows a pop-up alert if enabled, sends an email if enabled, and sends a push notification if enabled. This function ensures that important alerts are communicated through multiple channels based on the user's preferences.
Let's break down the TF2Str function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::TF2Str(ENUM_TIMEFRAMES period)
This function converts an enumeration value representing a time frame into its corresponding string representation. Here’s a detailed breakdown of each part of the code:
string MCEA::TF2Str(ENUM_TIMEFRAMES period)
{
//---
switch(period)
{
//--
case PERIOD_M1: return("M1");
case PERIOD_M2: return("M2");
case PERIOD_M3: return("M3");
case PERIOD_M4: return("M4");
case PERIOD_M5: return("M5");
case PERIOD_M6: return("M6");
case PERIOD_M10: return("M10");
case PERIOD_M12: return("M12");
case PERIOD_M15: return("M15");
case PERIOD_M20: return("M20");
case PERIOD_M30: return("M30");
case PERIOD_H1: return("H1");
case PERIOD_H2: return("H2");
case PERIOD_H3: return("H3");
case PERIOD_H4: return("H4");
case PERIOD_H6: return("H6");
case PERIOD_H8: return("H8");
case PERIOD_H12: return("H12");
case PERIOD_D1: return("D1");
case PERIOD_W1: return("W1");
case PERIOD_MN1: return("MN1");
//--
}
return(string(period));
//---
} //-end TF2Str()
//---------//
Function Explanation
Detailed Breakdown:
1. Switch Statement to Convert Enumeration Value to String:
switch (period): Checks the value of the period parameter, which is of type ENUM_TIMEFRAMES.
Minute Time Frames:
case PERIOD_M1: return("M1");: Returns "M1" for the 1-minute time frame.
case PERIOD_M2: return("M2");: Returns "M2" for the 2-minute time frame.
case PERIOD_M3: return("M3");: Returns "M3" for the 3-minute time frame.
case PERIOD_M4: return("M4");: Returns "M4" for the 4-minute time frame.
case PERIOD_M5: return("M5");: Returns "M5" for the 5-minute time frame.
case PERIOD_M6: return("M6");: Returns "M6" for the 6-minute time frame.
case PERIOD_M10: return("M10");: Returns "M10" for the 10-minute time frame.
case PERIOD_M12: return("M12");: Returns "M12" for the 12-minute time frame.
case PERIOD_M15: return("M15");: Returns "M15" for the 15-minute time frame.
case PERIOD_M20: return("M20");: Returns "M20" for the 20-minute time frame.
case PERIOD_M30: return("M30");: Returns "M30" for the 30-minute time frame.
Hour Time Frames:
case PERIOD_H1: return("H1");: Returns "H1" for the 1-hour time frame.
case PERIOD_H2: return("H2");: Returns "H2" for the 2-hour time frame.
case PERIOD_H3: return("H3");: Returns "H3" for the 3-hour time frame.
case PERIOD_H4: return("H4");: Returns "H4" for the 4-hour time frame.
case PERIOD_H6: return("H6");: Returns "H6" for the 6-hour time frame.
case PERIOD_H8: return("H8");: Returns "H8" for the 8-hour time frame.
case PERIOD_H12: return("H12");: Returns "H12" for the 12-hour time frame.
Day, Week, and Month Time Frames:
case PERIOD_D1: return("D1");: Returns "D1" for the 1-day time frame.
case PERIOD_W1: return("W1");: Returns "W1" for the 1-week time frame.
case PERIOD_MN1: return("MN1");: Returns "MN1" for the 1-month time frame.
2. Default Return:
return (string(period));: If the period doesn't match any of the specified cases, converts the period to a string and returns it.
Summary
The TF2Str function converts an enumeration value representing a time frame into its corresponding string representation. It uses a switch statement to check the period and returns the appropriate string. This function is useful for converting time frame enumeration values to readable string formats for display or logging.
Let's break down the getUninitReasonText function of FiboPivotCandleBar Expert Advisor for MT5.
string SFPCB::getUninitReasonText(int reasonCode)
This function returns a descriptive string explaining why the expert advisor (EA) was uninitialized based on the provided reason code. Here’s a detailed breakdown of each part of the code:
string MCEA::getUninitReasonText(int reasonCode)
{
//---
string text="";
//---
switch(reasonCode)
{
case REASON_PROGRAM:
text="The EA has stopped working calling by remove function."; break;
case REASON_REMOVE:
text="Program "+__FILE__+" was removed from chart"; break;
case REASON_RECOMPILE:
text="Program recompiled."; break;
case REASON_CHARTCHANGE:
text="Symbol or timeframe was changed"; break;
case REASON_CHARTCLOSE:
text="Chart was closed"; break;
case REASON_PARAMETERS:
text="Input-parameter was changed"; break;
case REASON_ACCOUNT:
text="Account was changed"; break;
case REASON_TEMPLATE:
text="New template was applied to chart"; break;
case REASON_INITFAILED:
text="The OnInit() handler returned a non-zero value."; break;
case REASON_CLOSE:
text="Terminal closed."; break;
default: text="Another reason"; break;
}
//--
return text;
//---
} //-end getUninitReasonText()
//---------//
Function Explanation
Detailed Breakdown:
1. Initialize Text String:
string text = "";: Initializes the text string to an empty string.
2. Switch Statement to Determine Uninitialization Reason:
switch (reasonCode): Checks the value of reasonCode and sets the text string to the corresponding uninitialization reason.
REASON_PROGRAM:
case REASON_PROGRAM: text = "The EA has stopped working calling by remove function."; break;: Sets text to indicate the EA was stopped by the remove function.
REASON_REMOVE:
case REASON_REMOVE: text = "Program " + __FILE__ + " was removed from chart"; break;: Sets text to indicate the program was removed from the chart.
REASON_RECOMPILE:
case REASON_RECOMPILE: text = "Program recompiled."; break;: Sets text to indicate the program was recompiled.
REASON_CHARTCHANGE:
case REASON_CHARTCHANGE: text = "Symbol or timeframe was changed"; break;: Sets text to indicate the symbol or timeframe was changed.
REASON_CHARTCLOSE:
case REASON_CHARTCLOSE: text = "Chart was closed"; break;: Sets text to indicate the chart was closed.
REASON_PARAMETERS:
case REASON_PARAMETERS: text = "Input-parameter was changed"; break;: Sets text to indicate an input parameter was changed.
REASON_ACCOUNT:
case REASON_ACCOUNT: text = "Account was changed"; break;: Sets text to indicate the account was changed.
REASON_TEMPLATE:
case REASON_TEMPLATE: text = "New template was applied to chart"; break;: Sets text to indicate a new template was applied to the chart.
REASON_INITFAILED:
case REASON_INITFAILED: text = "The OnInit() handler returned a non-zero value."; break;: Sets text to indicate the OnInit handler returned a non-zero value.
REASON_CLOSE:
case REASON_CLOSE: text = "Terminal closed."; break;: Sets text to indicate the terminal was closed.
Default Case:
default: text = "Another reason"; break;: Sets text to a generic message for any other reason.
3. Return Result:
return text;: Returns the descriptive string explaining the uninitialization reason.
Summary
The getUninitReasonText function returns a descriptive string explaining why the expert advisor (EA) was uninitialized based on the provided reason code. It initializes a string, uses a switch statement to determine the uninitialization reason, and returns the result. This function helps provide clear and readable explanations for various uninitialization scenarios, making it easier to understand why the EA stopped.
Thank you for reading this article A Comprehensive Guide to FiboPivotCandleBar: Functions and Performance of the EA for MT5
See you in the next article on Expert Advisor programs or indicators for MetaTrader 4 and MetaTrader 5.
If you are subscribed to my YouTube Channel, and would like to receive the source program of this article, please send a request via the Contact Us form page, and I will send it to your email, source code:
Expert Advisor: ExpFPCB_MT5
Indicator: FiboPivotCandleBarMT5
Don't forget to stop by and subscribe to Forex Home Experts YouTube Channel: