UPDATE!!!
So I write the update at the top just so I remember this for later.
I found out why SellProfit shows wrong profit.
It turns out the the summing function trigger the first Selltrigger and dosent display it but still keep that value to the end. This means it gives false results.
As you can see in the picture we only have one buySquare and no SellSquare
but the SellProfit comment (up to the left) still shows a sellvalue.
So it count the first selltrigger and the last sellClose as one trade but doesn't display it.
I don't know how to fix this in the code I have now but think I may be able to fix it if I insted look at the text element and try to collect them and sum them that way. It feals like the wrong way to go but all I can think of so far.
So.
I'm working on a Indicator that plots buy/sellsignal entry and closeorder for those.
I'm also working on displaying the profit of that order.
it looks like this.
double SquareStartPrice = 0;
double SquareEndPrice = 0;
double OrderStartPrice = 0;
double BuyProfit = 0;
double SellProfit = 0;
double profit = 0;
and
if(BuySignal && !BuyOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
}
if(BuySignalOut && !BuySignalOut_Bool)
{
SquareEndPrice = Close[i];
BuyProfit += (SquareEndPrice-SquareStartPrice);
//profit = (profit+BuyProfit);
}
if(SellSignal && !SellOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
}
if(SellSignalOut && ! SellSignalOut_Bool)
{
SellProfit += (SquareStartPrice-SquareEndPrice);
profit = (profit+SellProfit);
}
The problem I have is when summing the the SellProfit. It dosen't ad it up correctly but the BuyProfit works (I think).
it looks something like this.
Green Square are BuySignal and the number to the left is the profit.
Red Sqyare are the SellSignal and the number to the left is the profit.
BuyProfit = (15.3) + (-4.38) = 10.92
SellProfit = (-1.07)
If we look at the comment thats under the sympol we see that BuyProfit is correct but not SellProfit.
Where do I start locating where the problem is?
And here is the whole code: (don't know if I can attatch the .mq4 file)
//+------------------------------------------------------------------+
//| Test.mq4 |
//| Copyright 2020, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//#property indicator_separate_window
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
//--- plot EmaTrend
#property indicator_label1 "EmaTrend"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlack
#property indicator_style1 STYLE_SOLID
#property indicator_width1 4
//--- plot EmaShort
#property indicator_label2 "EmaShort"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 4
//--- plot Trend
#property indicator_label3 "Trend"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrGreen
#property indicator_style3 STYLE_SOLID
#property indicator_width3 4
//--- input parameters
//input int LookBack= 5000;
input datetime LookBackTo = D'2020.06.01 00:00:00';
extern double Static_LotSize=0.01;
extern string ____Moving_Average____ = " //////////////////// ";
input int myEmaTrend_Value = 350;
input int myEmaShort_Value = 9;
extern string ____MACD____ = " //////////////////// ";
//input bool myMACD_Bool = true;
input int myMACD_FAST_EMA =12;
input int myMACD_SLOW_EMA =26;
input int myMACD_SIGNAL_SMA =9;
extern string ____RSI____ = " //////////////////// ";
input int myRSI_Period =14;
input int myRSI_High =70;
input int myRSI_Low =30;
extern string ____DeMarker____ = " //////////////////// ";
input int myDeMarker_Period =14;
input double myDeMarker_High =0.70;
input double myDeMarker_Low =0.30;
extern string ____BuySellSignalOut____= " //////////////////// ";
input bool myEma_Bool = true;
input bool myRSI_Bool = false;
input bool myDeMarker_Bool = false;
bool BuyOrder_Bool = false;
bool SellOrder_Bool = false;
bool BuySignalOut_Bool = false;
bool SellSignalOut_Bool = false;
double SquareStartPrice = 0;
double SquareEndPrice = 0;
double OrderStartPrice = 0;
double BuyProfit = 0;
double SellProfit = 0;
double profit = 0;
int objcount=0;
int BuySquareCount=0;
int SellSquareCount=0;
color SquareTextColor=clrBlack;
color InfoTextColor=clrBlack;
int ButtonXSize = 140;
double pipsmultiplier;
//--- indicator buffers
double EmaTrendBuffer[];
double EmaShortBuffer[];
double TrendBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,EmaTrendBuffer);
SetIndexBuffer(1,EmaShortBuffer);
SetIndexBuffer(2,TrendBuffer);
deleteObjects();
if(MarketInfo(Symbol(),MODE_DIGITS)==3 && MarketInfo(Symbol(),MODE_DIGITS)==5)
{
pipsmultiplier=10;
}
else
{
pipsmultiplier=1;
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- initial zero
int limit = rates_total - prev_calculated;
ArraySetAsSeries(EmaTrendBuffer, true);
ArraySetAsSeries(EmaShortBuffer, true);
ArraySetAsSeries(TrendBuffer, true);
SetLabelObject("TestPos1","TestPos1",10,40,InfoTextColor);
int shift=iBarShift(Symbol(),PERIOD_CURRENT,LookBackTo);
Comment("BuyProfit = "+calculatePip(BuyProfit)+ "\n" + "SellProfit = "+calculatePip(SellProfit)+ "\n" +"SHIFT = "+shift);
if(prev_calculated < 1)
{
ArrayInitialize(EmaTrendBuffer, 0);
ArrayInitialize(EmaShortBuffer, 0);
ArrayInitialize(TrendBuffer, 0);
}
else
limit++;
//--- main loop
for(int i = limit-1; i >= 0; i--)
{
if(i >= MathMin(shift-1, rates_total-1-50))
continue; //omit some old rates to prevent "Array out of range" or slow calculation
//Indicator Buffer 1
double myEmaTrend = iMA(Symbol(),PERIOD_CURRENT,myEmaTrend_Value,0,MODE_EMA,PRICE_CLOSE,i);
EmaTrendBuffer[i] = myEmaTrend;
double myEmaTrend_Prev = iMA(Symbol(),PERIOD_CURRENT,myEmaTrend_Value,0,MODE_EMA,PRICE_CLOSE,i+1);
double myEmaShort = iMA(Symbol(),PERIOD_CURRENT,myEmaShort_Value,0,MODE_EMA,PRICE_CLOSE,i);
EmaShortBuffer[i] = myEmaShort;
double myEmaShort_Prev = iMA(Symbol(),PERIOD_CURRENT,myEmaShort_Value,0,MODE_EMA,PRICE_CLOSE,i+1);
double myMACD_Signal = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_SIGNAL,i);
double myMACD_Signal_Prev = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_SIGNAL,i+1);
double myMACD = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_MAIN,i);
double myMACD_Prev = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_MAIN,i+1);
double myRSI = iRSI(Symbol(),PERIOD_CURRENT,myRSI_Period,PRICE_CLOSE,i);
double myRSI_Prev = iRSI(Symbol(),PERIOD_CURRENT,myRSI_Period,PRICE_CLOSE,i+1);
double myDeMarker =iDeMarker(Symbol(),PERIOD_CURRENT,myDeMarker_Period,i);
double myDeMarker_Prev =iDeMarker(Symbol(),PERIOD_CURRENT,myDeMarker_Period,i+1);
bool BuyTrend = myEmaShort>myEmaTrend;
bool BuyTrend_Prev = myEmaShort_Prev>myEmaTrend_Prev;
//----------
bool BuySignal = BuyTrend && BuyTrend_Prev && myMACD_Prev<myMACD_Signal_Prev && myMACD>myMACD_Signal && myMACD_Prev<0 && myMACD<0;
bool BuySignalOut = (myEma_Bool && BuyTrend_Prev && !BuyTrend) ||
(myRSI_Bool && myRSI>myRSI_High && myRSI_Prev<myRSI_High) ||
(myDeMarker_Bool && myDeMarker>myDeMarker_High && myDeMarker_Prev<myDeMarker_High);
//----------
bool SellSignal = !BuyTrend && !BuyTrend_Prev && myMACD_Prev>myMACD_Signal_Prev && myMACD<myMACD_Signal && myMACD_Prev>0 && myMACD>0;
bool SellSignalOut = (myEma_Bool && !BuyTrend_Prev && BuyTrend) ||
(myRSI_Bool && myRSI<myRSI_Low && myRSI_Prev>myRSI_Low) ||
(myDeMarker_Bool && myDeMarker<myDeMarker_Low && myDeMarker_Prev>myDeMarker_Low);
//----------
ObjectSetString(NULL,"TestPos1",OBJPROP_TEXT,"Profit = "+string(calculatePip(profit)));
//----------
if(BuySignal && !BuyOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
SetVlineObject("BuySignal"+string(objcount), Time[i], clrGreen);
SetSquareObject("BuySquare"+string(BuySquareCount), Time[i], SquareStartPrice,Time[i], SquareEndPrice,clrGreen);
objcount++;
BuySquareCount++;
BuyOrder_Bool = true;
SellOrder_Bool = false;
BuySignalOut_Bool = false;
}
if(BuySignalOut && !BuySignalOut_Bool)
{
SetVlineObject("BuySignalOut"+string(objcount), Time[i], clrDarkGreen);
ObjectSet("BuySquare"+string(BuySquareCount-1),OBJPROP_TIME2,Time[i]);
SquareEndPrice = Close[i];
ObjectSet("BuySquare"+string(BuySquareCount-1),OBJPROP_PRICE2,SquareEndPrice);
ObjectSetString(NULL,"BuySquare"+string(BuySquareCount-1)+"text",OBJPROP_TEXT,string(calculatePip(SquareEndPrice-SquareStartPrice)));
BuyProfit += (SquareEndPrice-SquareStartPrice);
//profit = (profit+BuyProfit);
objcount++;
BuyOrder_Bool = false;
BuySignalOut_Bool=true;
//----------
}
if(SellSignal && !SellOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
SetVlineObject("SellSignal"+string(objcount), Time[i], clrRed);
SetSquareObject("SellSquare"+string(SellSquareCount), Time[i], SquareStartPrice,Time[i], SquareEndPrice,clrRed);
objcount++;
SellSquareCount++;
BuyOrder_Bool = false;
SellOrder_Bool = true;
SellSignalOut_Bool = false;
}
if(SellSignalOut && ! SellSignalOut_Bool)
{
SetVlineObject("SellSignalOut"+string(objcount), Time[i], clrDarkRed);
ObjectSet("SellSquare"+string(SellSquareCount-1),OBJPROP_TIME2,Time[i]);
SquareEndPrice = Close[i];
ObjectSet("SellSquare"+string(SellSquareCount-1),OBJPROP_PRICE2,SquareEndPrice);
ObjectSetString(NULL,"SellSquare"+string(SellSquareCount-1)+"text",OBJPROP_TEXT,string(calculatePip(SquareStartPrice-SquareEndPrice)));
SellProfit += (SquareStartPrice-SquareEndPrice);
profit = (profit+SellProfit);
objcount++;
SellOrder_Bool = false;
SellSignalOut_Bool = true;
}
}
return(rates_total);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetVlineObject |
//+------------------------------------------------------------------+
void SetVlineObject(string name, datetime t, color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_VLINE,0,t,0);
ObjectSet(name, OBJPROP_COLOR, colour);
ObjectSet(name, OBJPROP_BACK, false);
ObjectSet(name, OBJPROP_WIDTH, 4);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetSquareObject |
//+------------------------------------------------------------------+
void SetSquareObject(string name, datetime t1, double P1,datetime t2, double P2,color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_RECTANGLE,0,t1,P1,t2,P2);
ObjectSet(name, OBJPROP_CORNER, 1); // Reference corner
ObjectSet(name,OBJPROP_BGCOLOR,colour);
ObjectSet(name,OBJPROP_COLOR,colour);
ObjectCreate(name+"text",OBJ_TEXT,0,t1,P1);
ObjectSet(name+"text",OBJPROP_COLOR,SquareTextColor);
ObjectSet(name+"text",OBJPROP_FONTSIZE,25);
ObjectSet(name+"text", OBJPROP_ANCHOR,4);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetLabelObject |
//+------------------------------------------------------------------+
void SetLabelObject(string name, string text, double P1, double P2,color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_LABEL,0,0,0);
ObjectSetString(NULL,name,OBJPROP_TEXT,text);
ObjectSet(name, OBJPROP_CORNER, 1); // Reference corner
ObjectSet(name, OBJPROP_XDISTANCE, P1);// X coordinate
ObjectSet(name, OBJPROP_YDISTANCE, P2);// Y coordinate
ObjectSet(name,OBJPROP_BGCOLOR,colour);
ObjectSet(name,OBJPROP_COLOR,colour);
ObjectSet(name,OBJPROP_FONTSIZE,25);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetButtonObject |
//+------------------------------------------------------------------+
void SetButtonObject(string name,string text, double P1, double P2,color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_BUTTON,0,0,0,0);
ObjectSet(name, OBJPROP_CORNER, 1);
ObjectSet(name,OBJPROP_XDISTANCE,P1);
ObjectSet(name,OBJPROP_YDISTANCE,P2);
ObjectSet(name,OBJPROP_XSIZE,ButtonXSize);
ObjectSet(name,OBJPROP_YSIZE,40);
ObjectSetString(NULL,name,OBJPROP_TEXT,text);
ObjectSet(name,OBJPROP_COLOR,clrWhite);
ObjectSet(name,OBJPROP_BGCOLOR,colour);
}
}
//+------------------------------------------------------------------+
double calculatePip(double number)
{
double a = Point;
number = NormalizeDouble( (number/a) * (pipsmultiplier),Digits);
number = number * Static_LotSize;
return(number);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
deleteObjects();
//----
return(0);
}
//+------------------------------------------------------------------+
//| Delete CreateObjects |
//+------------------------------------------------------------------+
int deleteObjects()
{
ObjectsDeleteAll(NULL, OBJ_VLINE); // delete all horizontal lines from the 2nd subwindow
ObjectsDeleteAll(NULL, OBJ_RECTANGLE);
ObjectsDeleteAll();
return(0);
}
//+------------------------------------------------------------------+
So what I needed to do was to add a "BuyOrder_Bool" in the Buy/SellSignalOut and that works now.
if(BuySignal && !BuyOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
BuyOrder_Bool = true;
SellOrder_Bool = false;
BuySignalOut_Bool = false;
}
if(BuySignalOut && !BuySignalOut_Bool && BuyOrder_Bool)
{
SquareEndPrice = Close[i];
BuyProfit += (SquareEndPrice-SquareStartPrice);
profit = (profit+BuyProfit);
objcount++;
BuyOrder_Bool = false;
BuySignalOut_Bool=true;
//----------
}
if(SellSignal && !SellOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
objcount++;
SellSquareCount++;
BuyOrder_Bool = false;
SellOrder_Bool = true;
SellSignalOut_Bool = false;
}
if(SellSignalOut && ! SellSignalOut_Bool && SellOrder_Bool)
{
SquareEndPrice = Close[i];
ObjectSet("SellSquare"+string(SellSquareCount-
SellProfit += (SquareStartPrice-SquareEndPrice);
profit = (profit+SellProfit);
objcount++;
SellOrder_Bool = false;
SellSignalOut_Bool = true;
}
}
And here is the whole code:
//+------------------------------------------------------------------+
//| Test.mq4 |
//| Copyright 2020, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//#property indicator_separate_window
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
//--- plot EmaTrend
#property indicator_label1 "EmaTrend"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlack
#property indicator_style1 STYLE_SOLID
#property indicator_width1 4
//--- plot EmaShort
#property indicator_label2 "EmaShort"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 4
//--- plot Trend
#property indicator_label3 "Trend"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrGreen
#property indicator_style3 STYLE_SOLID
#property indicator_width3 4
//--- input parameters
//input int LookBack= 5000;
input datetime LookBackTo = D'2020.05.01 00:00:00';
extern double Static_LotSize=0.01;
extern string ____Moving_Average____ = " //////////////////// ";
input int myEmaTrend_Value = 350;
input int myEmaShort_Value = 9;
extern string ____MACD____ = " //////////////////// ";
//input bool myMACD_Bool = true;
input int myMACD_FAST_EMA =12;
input int myMACD_SLOW_EMA =26;
input int myMACD_SIGNAL_SMA =9;
extern string ____RSI____ = " //////////////////// ";
input int myRSI_Period =14;
input int myRSI_High =70;
input int myRSI_Low =30;
extern string ____DeMarker____ = " //////////////////// ";
input int myDeMarker_Period =14;
input double myDeMarker_High =0.70;
input double myDeMarker_Low =0.30;
extern string ____BuySellSignalOut____= " //////////////////// ";
input bool myEma_Bool = true;
input bool myRSI_Bool = false;
input bool myDeMarker_Bool = false;
extern string ____OtherSettings____= " //////////////////// ";
input bool Vline_Bool = false;
bool BuyOrder_Bool = false;
bool SellOrder_Bool = false;
bool BuySignalOut_Bool = false;
bool SellSignalOut_Bool = false;
double SquareStartPrice = 0;
double SquareEndPrice = 0;
double OrderStartPrice = 0;
double BuyProfit = 0;
double SellProfit = 0;
double profit = 0;
int objcount=0;
int BuySquareCount=0;
int SellSquareCount=0;
color SquareTextColor=clrBlack;
color InfoTextColor=clrBlack;
int ButtonXSize = 140;
double pipsmultiplier;
//--- indicator buffers
double EmaTrendBuffer[];
double EmaShortBuffer[];
double TrendBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,EmaTrendBuffer);
SetIndexBuffer(1,EmaShortBuffer);
SetIndexBuffer(2,TrendBuffer);
deleteObjects();
if(MarketInfo(Symbol(),MODE_DIGITS)==3 && MarketInfo(Symbol(),MODE_DIGITS)==5)
{
pipsmultiplier=10;
}
else
{
pipsmultiplier=1;
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- initial zero
int limit = rates_total - prev_calculated;
ArraySetAsSeries(EmaTrendBuffer, true);
ArraySetAsSeries(EmaShortBuffer, true);
ArraySetAsSeries(TrendBuffer, true);
SetLabelObject("TestPos1","TestPos1",10,40,InfoTextColor);
int shift=iBarShift(Symbol(),PERIOD_CURRENT,LookBackTo);
Comment("BuyProfit = "+string(calculatePip(BuyProfit))+ "\n"
+"SellProfit = "+string(calculatePip(SellProfit))+ "\n"
+"SHIFT = "+string(shift)+ "\n"
//+"Vline_Bool = "+Vline_Bool
);
if(prev_calculated < 1)
{
ArrayInitialize(EmaTrendBuffer, 0);
ArrayInitialize(EmaShortBuffer, 0);
ArrayInitialize(TrendBuffer, 0);
}
else
limit++;
//--- main loop
for(int i = limit-1; i >= 0; i--)
{
if(i >= MathMin(shift-1, rates_total-1-50))
continue; //omit some old rates to prevent "Array out of range" or slow calculation
//Indicator Buffer 1
double myEmaTrend = iMA(Symbol(),PERIOD_CURRENT,myEmaTrend_Value,0,MODE_EMA,PRICE_CLOSE,i);
EmaTrendBuffer[i] = myEmaTrend;
double myEmaTrend_Prev = iMA(Symbol(),PERIOD_CURRENT,myEmaTrend_Value,0,MODE_EMA,PRICE_CLOSE,i+1);
double myEmaShort = iMA(Symbol(),PERIOD_CURRENT,myEmaShort_Value,0,MODE_EMA,PRICE_CLOSE,i);
EmaShortBuffer[i] = myEmaShort;
double myEmaShort_Prev = iMA(Symbol(),PERIOD_CURRENT,myEmaShort_Value,0,MODE_EMA,PRICE_CLOSE,i+1);
double myMACD_Signal = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_SIGNAL,i);
double myMACD_Signal_Prev = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_SIGNAL,i+1);
double myMACD = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_MAIN,i);
double myMACD_Prev = iMACD(Symbol(),PERIOD_CURRENT,myMACD_FAST_EMA,myMACD_SLOW_EMA,myMACD_SIGNAL_SMA,PRICE_CLOSE,MODE_MAIN,i+1);
double myRSI = iRSI(Symbol(),PERIOD_CURRENT,myRSI_Period,PRICE_CLOSE,i);
double myRSI_Prev = iRSI(Symbol(),PERIOD_CURRENT,myRSI_Period,PRICE_CLOSE,i+1);
double myDeMarker =iDeMarker(Symbol(),PERIOD_CURRENT,myDeMarker_Period,i);
double myDeMarker_Prev =iDeMarker(Symbol(),PERIOD_CURRENT,myDeMarker_Period,i+1);
bool BuyTrend = myEmaShort>myEmaTrend;
bool BuyTrend_Prev = myEmaShort_Prev>myEmaTrend_Prev;
//----------
bool BuySignal = BuyTrend && BuyTrend_Prev && myMACD_Prev<myMACD_Signal_Prev && myMACD>myMACD_Signal && myMACD_Prev<0 && myMACD<0;
bool BuySignalOut = (myEma_Bool && BuyTrend_Prev && !BuyTrend) ||
(myRSI_Bool && myRSI>myRSI_High && myRSI_Prev<myRSI_High) ||
(myDeMarker_Bool && myDeMarker>myDeMarker_High && myDeMarker_Prev<myDeMarker_High);
//----------
bool SellSignal = !BuyTrend && !BuyTrend_Prev && myMACD_Prev>myMACD_Signal_Prev && myMACD<myMACD_Signal && myMACD_Prev>0 && myMACD>0;
bool SellSignalOut = (myEma_Bool && !BuyTrend_Prev && BuyTrend) ||
(myRSI_Bool && myRSI<myRSI_Low && myRSI_Prev>myRSI_Low) ||
(myDeMarker_Bool && myDeMarker<myDeMarker_Low && myDeMarker_Prev>myDeMarker_Low);
//----------
ObjectSetString(NULL,"TestPos1",OBJPROP_TEXT,"Profit = "+string(calculatePip(profit)));
//----------
if(BuySignal && !BuyOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
SetVlineObject("BuySignal"+string(objcount), Time[i], clrGreen);
SetSquareObject("BuySquare"+string(BuySquareCount), Time[i], SquareStartPrice,Time[i], SquareEndPrice,clrGreen);
objcount++;
BuySquareCount++;
BuyOrder_Bool = true;
SellOrder_Bool = false;
BuySignalOut_Bool = false;
}
if(BuySignalOut && !BuySignalOut_Bool && BuyOrder_Bool)
{
SetVlineObject("BuySignalOut"+string(objcount), Time[i], clrDarkGreen);
ObjectSet("BuySquare"+string(BuySquareCount-1),OBJPROP_TIME2,Time[i]);
SquareEndPrice = Close[i];
ObjectSet("BuySquare"+string(BuySquareCount-1),OBJPROP_PRICE2,SquareEndPrice);
ObjectSetString(NULL,"BuySquare"+string(BuySquareCount-1)+"text",OBJPROP_TEXT,string(calculatePip(SquareEndPrice-SquareStartPrice)));
BuyProfit += (SquareEndPrice-SquareStartPrice);
profit = (profit+BuyProfit);
objcount++;
BuyOrder_Bool = false;
BuySignalOut_Bool=true;
//----------
}
if(SellSignal && !SellOrder_Bool)
{
SquareStartPrice = Close[i];
SquareEndPrice = Close[i];
SetVlineObject("SellSignal"+string(objcount), Time[i], clrRed);
SetSquareObject("SellSquare"+string(SellSquareCount), Time[i], SquareStartPrice,Time[i], SquareEndPrice,clrRed);
objcount++;
SellSquareCount++;
BuyOrder_Bool = false;
SellOrder_Bool = true;
SellSignalOut_Bool = false;
}
if(SellSignalOut && ! SellSignalOut_Bool && SellOrder_Bool)
{
SetVlineObject("SellSignalOut"+string(objcount), Time[i], clrDarkRed);
ObjectSet("SellSquare"+string(SellSquareCount-1),OBJPROP_TIME2,Time[i]);
SquareEndPrice = Close[i];
ObjectSet("SellSquare"+string(SellSquareCount-1),OBJPROP_PRICE2,SquareEndPrice);
ObjectSetString(NULL,"SellSquare"+string(SellSquareCount-1)+"text",OBJPROP_TEXT,string(calculatePip(SquareStartPrice-SquareEndPrice)));
SellProfit += (SquareStartPrice-SquareEndPrice);
profit = (profit+SellProfit);
objcount++;
SellOrder_Bool = false;
SellSignalOut_Bool = true;
}
}
return(rates_total);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetVlineObject |
//+------------------------------------------------------------------+
void SetVlineObject(string name, datetime t, color colour)
{
if(Vline_Bool && ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_VLINE,0,t,0);
ObjectSet(name, OBJPROP_COLOR, colour);
ObjectSet(name, OBJPROP_BACK, false);
ObjectSet(name, OBJPROP_WIDTH, 4);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetSquareObject |
//+------------------------------------------------------------------+
void SetSquareObject(string name, datetime t1, double P1,datetime t2, double P2,color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_RECTANGLE,0,t1,P1,t2,P2);
ObjectSet(name, OBJPROP_CORNER, 1); // Reference corner
ObjectSet(name,OBJPROP_BGCOLOR,colour);
ObjectSet(name,OBJPROP_COLOR,colour);
ObjectCreate(name+"text",OBJ_TEXT,0,t1,P1);
ObjectSet(name+"text",OBJPROP_COLOR,SquareTextColor);
ObjectSet(name+"text",OBJPROP_FONTSIZE,25);
ObjectSet(name+"text", OBJPROP_ANCHOR,4);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetLabelObject |
//+------------------------------------------------------------------+
void SetLabelObject(string name, string text, double P1, double P2,color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_LABEL,0,0,0);
ObjectSetString(NULL,name,OBJPROP_TEXT,text);
ObjectSet(name, OBJPROP_CORNER, 1); // Reference corner
ObjectSet(name, OBJPROP_XDISTANCE, P1);// X coordinate
ObjectSet(name, OBJPROP_YDISTANCE, P2);// Y coordinate
ObjectSet(name,OBJPROP_BGCOLOR,colour);
ObjectSet(name,OBJPROP_COLOR,colour);
ObjectSet(name,OBJPROP_FONTSIZE,25);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| SetButtonObject |
//+------------------------------------------------------------------+
void SetButtonObject(string name,string text, double P1, double P2,color colour)
{
if(ObjectFind(name) == -1)
{
ObjectCreate(name,OBJ_BUTTON,0,0,0,0);
ObjectSet(name, OBJPROP_CORNER, 1);
ObjectSet(name,OBJPROP_XDISTANCE,P1);
ObjectSet(name,OBJPROP_YDISTANCE,P2);
ObjectSet(name,OBJPROP_XSIZE,ButtonXSize);
ObjectSet(name,OBJPROP_YSIZE,40);
ObjectSetString(NULL,name,OBJPROP_TEXT,text);
ObjectSet(name,OBJPROP_COLOR,clrWhite);
ObjectSet(name,OBJPROP_BGCOLOR,colour);
}
}
//+------------------------------------------------------------------+
double calculatePip(double number)
{
double a = Point;
number = NormalizeDouble( (number/a) * (pipsmultiplier),Digits);
number = number * Static_LotSize;
return(number);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
deleteObjects();
//----
return(0);
}
//+------------------------------------------------------------------+
//| Delete CreateObjects |
//+------------------------------------------------------------------+
int deleteObjects()
{
ObjectsDeleteAll(NULL, OBJ_VLINE); // delete all horizontal lines from the 2nd subwindow
ObjectsDeleteAll(NULL, OBJ_RECTANGLE);
ObjectsDeleteAll();
return(0);
}
//+------------------------------------------------------------------+
Related
I got this indicator for mt4, I would like somebody to help me modify it so I can input an integer to select how many bars should be plotted. normally it will plot infinite bars, I'd like to be able to select the number of MTF bars the indicator should plot. This to eliminate the lag when changin timeframes, I imagine the lag is because of the big amount of MTF candles plotted.
Other change that I would really apreciate, if you see when open and close price is exactly the same it will not create a doji, it will only show wicks, not the classic horizontal line for a doji.
I paid a coder to make this, now he's chargin plus to make this changes, I tried to make them myself copying an indicator that has that function but my coding skills are hugely limited.
Thanks.
//+------------------------------------------------------------------+
//| MTF_Candles.mq4 |
//+------------------------------------------------------------------+
#property copyright "Ab Moncada"
#property version "1.0"
#property strict
#property indicator_chart_window
enum enumTimeFrames{
m1 = PERIOD_M1, //M1
m5 = PERIOD_M5, //M5
m15 = PERIOD_M15, //M15
m30 = PERIOD_M30, //M30
h1 = PERIOD_H1, //H1
h4 = PERIOD_H4, //H4
d1 = PERIOD_D1, //D1
w1 = PERIOD_W1, //W1
mn1 = PERIOD_MN1 //MN1
};
//input ENUM_TIMEFRAMES MTF_Period = PERIOD_H1; //Timeframe
input enumTimeFrames MTF_Period = h1; //Timeframe
input color UpColor = clrGainsboro; //ColorBulls
input color DownColor = clrGainsboro; //ColorBears
input bool LineType = false; //Background
input ENUM_LINE_STYLE LineStyle = STYLE_DOT; //LineStyle
input int LineWidth = 3; //LineWidth
string indiName = "MTF_CandleStick";
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit(){
//--- indicator buffers mapping
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){
objDelete(indiName+IntegerToString(MTF_Period));
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(MTF_Period <= _Period) return(0);
int limit = rates_total - prev_calculated;
if(limit > 0){
objDelete(indiName+IntegerToString(MTF_Period));
limit = rates_total-1;
}
else{
if(MTF_Period < 1440) limit = MTF_Period/_Period;
else limit = 1;
}
for(int i=0; i<limit; i++){
double mtfOpen, mtfClose, mtfHigh, mtfLow;
int first, last=0;
if(MTF_Period < 1440){
if(MathMod(time[i], MTF_Period*60) != 0) continue;
first = i;
for(int t=i-1; t>=0; t--){
if(time[i]+MTF_Period*60 <= time[t]){
last = t+1;
break;
}
}
mtfOpen = open[first];
mtfClose = close[last];
mtfHigh = high[iHighest(NULL, 0, MODE_HIGH, first-last+1, last)];
mtfLow = low[iLowest(NULL, 0, MODE_LOW, first-last+1, last)];
}
else{
if(time[Bars-1] > iTime(NULL, MTF_Period, i)) break;
mtfOpen = iOpen(NULL, MTF_Period, i);
mtfClose = iClose(NULL, MTF_Period, i);
mtfHigh = iHigh(NULL, MTF_Period, i);
mtfLow = iLow(NULL, MTF_Period, i);
first = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i), false);
if(TimeHour(time[first]) != 0) first--;
if(i > 0){
last = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i-1), false);
if(TimeHour(time[last]) == 0) last++;
}
/*
if(MTF_Period == 1440){
first = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i), false);
if(i > 0) last = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i-1), false)+1;
}
else{
first = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i), false)-1;
if(i > 0) last = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i-1), false);
}
*/
}
if(mtfOpen <= mtfClose){
Rectangle(indiName+IntegerToString(MTF_Period)+"_body"+IntegerToString(i), first, mtfOpen, last, mtfClose, UpColor, LineStyle, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_shadow"+IntegerToString(i), (first+last)/2, mtfClose, mtfHigh, UpColor, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_tail"+IntegerToString(i), (first+last)/2, mtfOpen, mtfLow, UpColor, LineWidth);
}
else{
Rectangle(indiName+IntegerToString(MTF_Period)+"_body"+IntegerToString(i), first, mtfOpen, last, mtfClose, DownColor, LineStyle, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_shadow"+IntegerToString(i), (first+last)/2, mtfOpen, mtfHigh, DownColor, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_tail"+IntegerToString(i), (first+last)/2, mtfClose, mtfLow, DownColor, LineWidth);
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
void Rectangle(string name, int index1, double price1, int index2, double price2, color Rcolor, int Rstyle, int Rwidth){
long id = ChartID();
if (ObjectFind(name) != 0) {
ObjectCreate(id, name, OBJ_RECTANGLE, 0, Time[index1], price1, Time[index2], price2);
ObjectSetInteger(id, name, OBJPROP_COLOR, Rcolor);
if(LineType) ObjectSetInteger(id, name, OBJPROP_STYLE, Rstyle);
ObjectSetInteger(id, name, OBJPROP_WIDTH, Rwidth);
ObjectSetInteger(id, name, OBJPROP_BACK, !LineType);
//ObjectSetInteger(id, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(id, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(id, name, OBJPROP_HIDDEN, true);
}
else{
ObjectMove(name, 0, Time[index1], price1);
ObjectMove(name, 1, Time[index2], price2);
}
ChartRedraw(id);
}
void TrendLine(string name, int position, double price1, double price2, color Tcolor, int Twidth){
long id = ChartID();
if (ObjectFind(name) != 0) {
ObjectCreate(id, name, OBJ_TREND, 0, Time[position], price1, Time[position], price2);
ObjectSetInteger(id, name, OBJPROP_COLOR, Tcolor);
ObjectSetInteger(id, name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(id, name, OBJPROP_WIDTH, Twidth);
ObjectSetInteger(id, name, OBJPROP_BACK, true);
ObjectSetInteger(id, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(id, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(id, name, OBJPROP_HIDDEN, true);
}
else{
ObjectMove(name, 0, Time[position], price1);
ObjectMove(name, 1, Time[position], price2);
}
ChartRedraw(id);
}
void objDelete(string basicName){
for(int i=ObjectsTotal();i>=0;i--){
string ObjName = ObjectName(i);
if(StringFind(ObjName, basicName) >=0) ObjectDelete(ObjName);
}
}
I am trying to convert this indicator to PineScript. Couldn't figure out how to get Point variable. Is there any way to achieve the same thing in PineScript?
_Point official definition:
The _Point variable contains the point size of the current symbol in the quote currency.
https://docs.mql4.com/predefined/_point
Updated: Added the indicator code
//| Ticks Volume Indicator |
//| Copyright В© William Blau |
//| Coded/Verified by Profitrader |
//+------------------------------------------------------------------+
#property copyright "Copyright В© 2006, Profitrader."
#property link "profitrader#inbox.ru"
//-----
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Blue
//---- input parameters
extern int r=12;
extern int s=12;
extern int u=5;
//---- buffers
double TVI[];
double UpTicks[];
double DownTicks[];
double EMA_UpTicks[];
double EMA_DownTicks[];
double DEMA_UpTicks[];
double DEMA_DownTicks[];
double TVI_calculate[];
double MyPoint;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init() {
IndicatorShortName("TVI("+r+","+s+","+u+")");
IndicatorBuffers(8);
SetIndexBuffer(0,TVI);
SetIndexBuffer(1,UpTicks);
SetIndexBuffer(2,DownTicks);
SetIndexBuffer(3,EMA_UpTicks);
SetIndexBuffer(4,EMA_DownTicks);
SetIndexBuffer(5,DEMA_UpTicks);
SetIndexBuffer(6,DEMA_DownTicks);
SetIndexBuffer(7,TVI_calculate);
SetIndexStyle(0,DRAW_LINE);
SetIndexLabel(0,"TVI");
if (Digits == 5 || (Digits == 3 && StringFind(Symbol(), "JPY") != -1))
MyPoint = Point*10;
else if (Digits == 6 || (Digits == 4 && StringFind(Symbol(), "JPY") != -1))
MyPoint = Point*100;
else
MyPoint = Point;
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit() {
return(0);
}
//+------------------------------------------------------------------+
//| Ticks Volume Indicator |
//+------------------------------------------------------------------+
int start() {
int i,counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
int limit=Bars-counted_bars;
//----
for(i=0; i=0; i--) {
EMA_UpTicks[i]=iMAOnArray(UpTicks,0,r,0,MODE_EMA,i);
EMA_DownTicks[i]=iMAOnArray(DownTicks,0,r,0,MODE_EMA,i);
}
for(i=limit-1; i>=0; i--) {
DEMA_UpTicks[i]=iMAOnArray(EMA_UpTicks,0,s,0,MODE_EMA,i);
DEMA_DownTicks[i]=iMAOnArray(EMA_DownTicks,0,s,0,MODE_EMA,i);
}
for(i=0; i=0; i--) {
if (iClose(NULL,0,i)==0)
TVI[i]=EMPTY_VALUE;
else
TVI[i]=iMAOnArray(TVI_calculate,0,u,0,MODE_EMA,i);
}
//----
return(0);
}
//+------------------------------------------------------------------+
i have a small expert with mql4 for forex robot
but i have get some problem in getting code when running this code to backtest in metatrader 4
my code details is :
i have 2 ema and when cross up get buy and when cross down get sell
but its problem to get position after crosing 2 ema in backtest.
My stoplose is fix to 10 pip but tp is 0 and we have open trade until next cross from 2 ema and then close pervios position and get new position.
i add test sterategy and show my problem in getting position
#property copyright "Copyright 2018"
#property link "https://www.mql4.com"
#property version "1.00"
#property strict
input int Ema_Fast_Period = 62;
input int Ema_Slow_Period = 30;
input int MagicNumber = 1982;
input double Lots = 0.01;
input double StopLoss = 100;
input double TakeProfit = 0;
double FastMACurrent ,SlowMACurrent ,FastMAPrevious ,SlowMAPrevious;
bool BuyCondition = False, SellCondition = False, CrossPriseWithFastMAUpShado = False, CrossPriseWithFastMADownShado = False;
//---
int Slippage=5;
double OpenPosition = 0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| expert OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(Volume[0]<=1)
{
FastMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
SlowMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
FastMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
SlowMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
//----------------------- BUY CONDITION
BuyCondition = (FastMAPrevious<SlowMAPrevious && FastMACurrent>SlowMACurrent);
//----------------------- SELL CONDITION
SellCondition = (FastMAPrevious>SlowMAPrevious && FastMACurrent<SlowMACurrent);
CrossPriseWithFastMADownShado = ( Low[1]<FastMACurrent && FastMACurrent<Open[1] );
if( BuyCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderClosePrice(), Slippage, clrWhite );
}
BuyCondition = False;
GetBuy();
}
if( SellCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderClosePrice(), Slippage, clrWhite );
}
SellCondition = False;
GetSell();
}
}
}
//+------------------------------------------------------------------+
//| expert Buy Or Sell function |
//+------------------------------------------------------------------+
int GetBuy(){
int getposition = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),0,"Buy",MagicNumber,0,Blue);
return True;
}
int GetSell(){
int getposition = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(StopLoss*Point),0,"Sell",MagicNumber,0,Red);
return True;
}
enter image description here
I edited your code. The main problem in your code is takeprofit!
In GetBuy() and GetSell() Functions you wrote:
Ask+(TakeProfit*Point)
It returns Ask! because your TakeProfit has been set to zero. If you don't want to set Takeprofit You should write:
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),0,"Buy",MagicNumber,0,Blue);
This is the new code:
#property copyright "Copyright 2018"
#property link "https://www.mql4.com"
#property version "1.00"
#property strict
input int Ema_Fast_Period = 62;
input int Ema_Slow_Period = 30;
input int MagicNumber = 1982;
input double Lots = 0.01;
input int StopLoss = 100;
input int TakeProfit = 1000;
double FastMACurrent ,SlowMACurrent ,FastMAPrevious ,SlowMAPrevious;
bool BuyCondition = False, SellCondition = False, CrossPriseWithFastMAUpShado = False, CrossPriseWithFastMADownShado = False;
//---
int Slippage=5;
double OpenPosition = 0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| expert OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(Volume[0]<=1)
{
FastMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
SlowMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
FastMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
SlowMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
//----------------------- BUY CONDITION
BuyCondition = (FastMAPrevious<SlowMAPrevious && FastMACurrent>SlowMACurrent);
//----------------------- SELL CONDITION
SellCondition = (FastMAPrevious>SlowMAPrevious && FastMACurrent<SlowMACurrent);
CrossPriseWithFastMADownShado = ( Low[1]<FastMACurrent && FastMACurrent<Open[1] );
if( BuyCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderType()==OP_SELL ? Ask : Bid, Slippage, clrWhite );
}
if(GetBuy()) BuyCondition = False;
}
if( SellCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderType()==OP_BUY ? Bid : Ask, Slippage, clrWhite );
}
if(GetSell()) SellCondition = False;
}
}
}
//+------------------------------------------------------------------+
//| expert Buy Or Sell function |
//+------------------------------------------------------------------+
bool GetBuy(){
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),Ask+ (TakeProfit*Point),"Buy",MagicNumber,0,Blue);
if(ticket > 0) return true;
return false;
}
bool GetSell(){
int ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(StopLoss*Point),Bid- (TakeProfit*Point),"Sell",MagicNumber,0,Red);
if(ticket > 0) return true;
return false;
}
This is my code trying to generate the ADC Cloud indicator.
At first, it can work if I just generate the cloud.
Currently, I am trying to make the histogram green when it is above zero, otherwise red. Then, I separate the Could array into two buffers, GreenBuffer and RedBuffer. At this step, I stuck in an unknown error.
I can make sure the problem is coming from the ERROR PART, marked by Sharp Sign in Code.
Thank you first!
#property strict
#property indicator_separate_window
#property indicator_buffers 2
//--- input parameters
input int ADX_period=14;
double Cloud[];
double GreenBuffer[];
double RedBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
//SetIndexBuffer(0, GreenBuffer);
SetIndexBuffer(0, Cloud);
SetIndexLabel(0, "Cloud");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrGreen);
//SetIndexBuffer(1, Cloud);
//SetIndexStyle(1, DRAW_HISTOGRAM, 0, 2, clrRed);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int Limit_calc = 0;
int BarCnt = IndicatorCounted();
Limit_calc = Bars - BarCnt;
for (int i = Limit_calc-1; i >= 0 ; i--)
{
double output = iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i)
- iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i);
Cloud[i] = output;
// #########################################
// ###### Error Part #######################
//if (output > 0)
// {
// GreenBuffer[i] = output;
// RedBuffer[i] = 0.00;
// }
//else
// {
// GreenBuffer[i] = 0.00;
// RedBuffer[i] = output;
// }
// ##########################################
}
//Comment(Cloud[1]);
//--- return value of prev_calculated for next call
return(rates_total);
}
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0, GreenBuffer);
SetIndexLabel(0, "Green");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrGreen);
SetIndexBuffer(0, RedBuffer);
SetIndexLabel(0, "Red");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrRed);
//---
return(INIT_SUCCEEDED);
}
int OnCalculate( *** )
{
...
for (int i = Limit_calc-1; i >= 0 ; i--)
{
double output = iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i)
- iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i);
if (output > 0)
{
GreenBuffer[i] = output;
RedBuffer[i] = 0.00;
}
else
{
GreenBuffer[i] = 0.00;
RedBuffer[i] = output;
}
}
...
}
REPAIRED & [PASS]-on-TESTED CODE :
#property strict
#property indicator_separate_window
#property indicator_buffers 2
//--- input parameters
input int ADX_period = 14;
double GreenBuffer[],
RedBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer( 0, GreenBuffer );
SetIndexLabel( 0, "Green" );
SetIndexStyle( 0, DRAW_HISTOGRAM, 0, 2, clrGreen );
SetIndexBuffer( 1, RedBuffer );
SetIndexLabel( 1, "Red" );
SetIndexStyle( 1, DRAW_HISTOGRAM, 0, 2, clrRed );
//---
return( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate( const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
)
{
//---
int BarCnt = IndicatorCounted();
int Limit_calc = Bars - BarCnt;
for ( int i = Limit_calc - 1; i >= 0 ; i-- )
{
double output = iADX( NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i )
- iADX( NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i );
if ( output > 0 ) { GreenBuffer[i] = output; RedBuffer[i] = 0.00; }
else { GreenBuffer[i] = 0.00; RedBuffer[i] = output; }
}
//---
return( rates_total );
}
please help me on How to read iExposure indicator's Profit values from iCustom() function in MQL4?
Thanks
I am using mt4 provided iExposure.mq4 indicator. it has below buffers
SetIndexBuffer(0,ExtMapBuffer);
ExtMapBuffer[Bars-1]=-1;
I need Profit part from iCustom`()
I attached the entire indicator code for your reference.
thanks,
//+------------------------------------------------------------------+
//| iExposureSymbol.mq4 |
//| Copyright 2007-2014, MetaQuotes Software Corp. |
//| http://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright "2007-2014, MetaQuotes Software Corp."
#property link "http://www.mql4.com"
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_minimum 0.0
#property indicator_maximum 0.1
#define SYMBOLS_MAX 1
#define DEALS 0
#define BUY_LOTS 1
#define BUY_PRICE 2
#define SELL_LOTS 3
#define SELL_PRICE 4
#define NET_LOTS 5
#define PROFIT 6
input color InpColor=LightSeaGreen; // Text color
string ExtName="Exposure";
string ExtSymbols[SYMBOLS_MAX];
int ExtSymbolsTotal=0;
double ExtSymbolsSummaries[SYMBOLS_MAX][7];
int ExtLines=-1;
string ExtCols[8]={"Symbol",
"Deals",
"Buy lots",
"Buy price",
"Sell lots",
"Sell price",
"Net lots",
"Profit"};
int ExtShifts[8]={ 10, 80, 130, 180, 260, 310, 390, 460 };
int ExtVertShift=14;
double ExtMapBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
IndicatorShortName(ExtName);
SetIndexBuffer(0,ExtMapBuffer);
SetIndexStyle(0,DRAW_NONE);
IndicatorDigits(0);
SetIndexEmptyValue(0,0.0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
int windex=WindowFind(ExtName);
if(windex>0)
ObjectsDeleteAll(windex);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long& tick_volume[],
const long& volume[],
const int& spread[])
{
string name;
int i,col,line,windex=WindowFind(ExtName);
//----
if(windex<0)
return(rates_total);
//---- header line
if(ExtLines<0)
{
for(col=0; col<8; col++)
{
name="Head_"+string(col);
if(ObjectCreate(name,OBJ_LABEL,windex,0,0))
{
ObjectSet(name,OBJPROP_XDISTANCE,ExtShifts[col]);
ObjectSet(name,OBJPROP_YDISTANCE,ExtVertShift);
ObjectSetText(name,ExtCols[col],9,"Arial",InpColor);
}
}
ExtLines=0;
}
//----
ArrayInitialize(ExtSymbolsSummaries,0.0);
int total=Analyze();
if(total>0)
{
line=0;
for(i=0; i<ExtSymbolsTotal; i++)
{
if(ExtSymbolsSummaries[i][DEALS]<=0) continue;
line++;
//---- add line
if(line>ExtLines)
{
int y_dist=ExtVertShift*(line+1)+1;
for(col=0; col<8; col++)
{
name="Line_"+string(line)+"_"+string(col);
if(ObjectCreate(name,OBJ_LABEL,windex,0,0))
{
ObjectSet(name,OBJPROP_XDISTANCE,ExtShifts[col]);
ObjectSet(name,OBJPROP_YDISTANCE,y_dist);
}
}
ExtLines++;
}
//---- set line
int digits=(int)MarketInfo(ExtSymbols[i],MODE_DIGITS);
double buy_lots=ExtSymbolsSummaries[i][BUY_LOTS];
double sell_lots=ExtSymbolsSummaries[i][SELL_LOTS];
double buy_price=0.0;
double sell_price=0.0;
if(buy_lots!=0) buy_price=ExtSymbolsSummaries[i][BUY_PRICE]/buy_lots;
if(sell_lots!=0) sell_price=ExtSymbolsSummaries[i][SELL_PRICE]/sell_lots;
name="Line_"+string(line)+"_0";
ObjectSetText(name,ExtSymbols[i],9,"Arial",InpColor);
name="Line_"+string(line)+"_1";
ObjectSetText(name,DoubleToStr(ExtSymbolsSummaries[i][DEALS],0),9,"Arial",InpColor);
name="Line_"+string(line)+"_2";
ObjectSetText(name,DoubleToStr(buy_lots,2),9,"Arial",InpColor);
name="Line_"+string(line)+"_3";
ObjectSetText(name,DoubleToStr(buy_price,digits),9,"Arial",InpColor);
name="Line_"+string(line)+"_4";
ObjectSetText(name,DoubleToStr(sell_lots,2),9,"Arial",InpColor);
name="Line_"+string(line)+"_5";
ObjectSetText(name,DoubleToStr(sell_price,digits),9,"Arial",InpColor);
name="Line_"+string(line)+"_6";
ObjectSetText(name,DoubleToStr(buy_lots-sell_lots,2),9,"Arial",InpColor);
name="Line_"+string(line)+"_7";
ObjectSetText(name,DoubleToStr(ExtSymbolsSummaries[i][PROFIT],2),9,"Arial",InpColor);
}
}
//---- remove lines
if(total<ExtLines)
{
for(line=ExtLines; line>total; line--)
{
name="Line_"+string(line)+"_0";
ObjectSetText(name,"");
name="Line_"+string(line)+"_1";
ObjectSetText(name,"");
name="Line_"+string(line)+"_2";
ObjectSetText(name,"");
name="Line_"+string(line)+"_3";
ObjectSetText(name,"");
name="Line_"+string(line)+"_4";
ObjectSetText(name,"");
name="Line_"+string(line)+"_5";
ObjectSetText(name,"");
name="Line_"+string(line)+"_6";
ObjectSetText(name,"");
name="Line_"+string(line)+"_7";
ObjectSetText(name,"");
}
}
//---- to avoid minimum==maximum
ExtMapBuffer[Bars-1]=-1;
//----
return(rates_total);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int Analyze()
{
double profit;
int i,index,type,total=OrdersTotal();
//----
for(i=0; i<total; i++)
{
if(!OrderSelect(i,SELECT_BY_POS)) continue;
type=OrderType();
if(type!=OP_BUY && type!=OP_SELL) continue;
index=SymbolsIndex(OrderSymbol());
if(index<0 || index>=SYMBOLS_MAX) continue;
//----
ExtSymbolsSummaries[index][DEALS]++;
profit=OrderProfit()+OrderCommission()+OrderSwap();
ExtSymbolsSummaries[index][PROFIT]+=profit;
if(type==OP_BUY)
{
ExtSymbolsSummaries[index][BUY_LOTS]+=OrderLots();
ExtSymbolsSummaries[index][BUY_PRICE]+=OrderOpenPrice()*OrderLots();
}
else
{
ExtSymbolsSummaries[index][SELL_LOTS]+=OrderLots();
ExtSymbolsSummaries[index][SELL_PRICE]+=OrderOpenPrice()*OrderLots();
}
}
//----
total=0;
for(i=0; i<ExtSymbolsTotal; i++)
{
if(ExtSymbolsSummaries[i][DEALS]>0) total++;
}
//----
return(total);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int SymbolsIndex(string SymbolName)
{
bool found=false;
int i;
//----
for(i=0; i<ExtSymbolsTotal; i++)
{
if(SymbolName==ExtSymbols[i])
{
found=true;
break;
}
}
//----
if(found)
return(i);
if(ExtSymbolsTotal>=SYMBOLS_MAX)
return(-1);
//----
i=ExtSymbolsTotal;
ExtSymbolsTotal++;
ExtSymbols[i]=Symbol();
ExtSymbolsSummaries[i][DEALS]=0;
ExtSymbolsSummaries[i][BUY_LOTS]=0;
ExtSymbolsSummaries[i][BUY_PRICE]=0;
ExtSymbolsSummaries[i][SELL_LOTS]=0;
ExtSymbolsSummaries[i][SELL_PRICE]=0;
ExtSymbolsSummaries[i][NET_LOTS]=0;
ExtSymbolsSummaries[i][PROFIT]=0;
//----
return(i);
}
//+------------------------------------------------------------------+