Why my MQL5 indicator is displaying one moving average instead of two? - buffer

I took the code of VIDYA from the examples library of MQL5 and added a second moving average to it; basically, another VIDYA line.
The newly created code is compiling without errors or warnings but only one moving average (VIDYA) is being displayed on the chart instead of two. It seems I am missing something. Your help will be much appreciated!
#property copyright "2009-2020, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property description "Double Variable Index Dynamic Average"
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_type1 DRAW_LINE
#property indicator_color1 Navy
#property indicator_width1 3
#property indicator_label1 "VIDYA 1"
#property indicator_type2 DRAW_LINE
#property indicator_color2 Navy
#property indicator_width2 3
#property indicator_label2 "VIDYA 2"
#property indicator_applied_price PRICE_MEDIAN
//--- input parameters
input int InpPeriodCMO = 9; // Period CMO
input int InpPeriodEMA = 12; // Period EMA
input int InpShift = 0; // Indicator's shift
//--- indicator buffer
double VIDYA_Buffer_1[];
double VIDYA_Buffer_2[];
double ExtF; // smooth factor
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0, VIDYA_Buffer_1, INDICATOR_DATA);
SetIndexBuffer(1, VIDYA_Buffer_2, INDICATOR_DATA);
//--- sets first bar from what index will be drawn
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpPeriodEMA+InpPeriodCMO-1);
PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, InpPeriodEMA+InpPeriodCMO-1);
//--- sets indicator shift
PlotIndexSetInteger(0, PLOT_SHIFT, InpShift);
PlotIndexSetInteger(1, PLOT_SHIFT, InpShift);
//--- name for indicator label
string short_name = StringFormat("VIDYA(%d,%d)", InpPeriodCMO, InpPeriodEMA);
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
PlotIndexSetString(0, PLOT_LABEL, short_name+"1");
PlotIndexSetString(1, PLOT_LABEL, short_name+"2");
//--- calculate smooth factor
ExtF = 2.0/(1.0+InpPeriodEMA);
}
//+------------------------------------------------------------------+
//| Variable Index Dynamic Average |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])
{
if(rates_total < InpPeriodEMA+InpPeriodCMO-1)
return(0);
//---
int i,start;
if(prev_calculated < InpPeriodEMA+InpPeriodCMO-1)
{
start = InpPeriodEMA+InpPeriodCMO-1;
for(i = 0; i<start; i++)
{
VIDYA_Buffer_1[i] = price[i];
VIDYA_Buffer_2[i] = price[i];
}
}
else
start = prev_calculated-1;
//--- main cycle
for(i = start; i<rates_total && !IsStopped(); i++)
{
double mul_CMO = MathAbs(CalculateCMO(i,InpPeriodCMO,price));
//--- calculate VIDYA 1 & 2
VIDYA_Buffer_1[i] = price[i]*ExtF*mul_CMO+VIDYA_Buffer_1[i-1]*(1-ExtF*mul_CMO)*1;
VIDYA_Buffer_2[i] = price[i]*ExtF*mul_CMO+VIDYA_Buffer_2[i-1]*(1-ExtF*mul_CMO)*2;
}
//--- OnCalculate done. Return new prev_calculated.
return(rates_total);
}
//+------------------------------------------------------------------+
//| Chande Momentum Oscillator |
//+------------------------------------------------------------------+
double CalculateCMO(int pos,const int period,const double &price[])
{
double res = 0.0;
double sum_up = 0.0,sum_down = 0.0;
//---
if(pos >= period && pos<ArraySize(price))
{
for(int i = 0; i<period; i++)
{
double diff = price[pos-i]-price[pos-i-1];
if(diff>0.0)
sum_up += diff;
else
sum_down += (-diff);
}
if(sum_up+sum_down != 0.0)
res = (sum_up-sum_down)/(sum_up+sum_down);
}
//---
return(res);
}

Related

How to fix Error 130 on MT4 Expert Advisor Short trades?

I am trying to get this code to trade short. It trades long but give MT4 Error 130 invalid stop loss and is not going short. What do I change so this code goes short?
Code:
string symbol = "EURUSD"; // symbol
double volume = .01; // volume
int slippage = 0; // slippage
double pricelong = Ask; // price
string cmdlong = "OP_BUYLIMIT"; // operation
double stoplosslong = Ask - .0005; // stop loss
double takeprofitlong = Bid + .0005; // take profit
string commentlong="Long"; // comment
color arrow_color_long=Green; // color
double priceshort = Bid; // price
string cmdshort = "OP_SELLLIMIT"; // operation
double stoplossshort = 25; // stop loss
double takeprofitshort = 50; // take profit
string commentshort="Short"; // comment
color arrow_color_short=Red; // color
int magic=0; // magic number
datetime expiration=0; // pending order expiration
orderresults = OrderSend(symbol, cmdshort , volume, priceshort, slippage, stoplossshort, takeprofitshort, commentshort, magic, expiration, arrow_color_short);

How to convert send order from mql4 to mql5

Below is the method I'm using to place an order after three minutes if it doesn't go through. I've converted the larger part of it from mql4 to mql5. It's just the commented part that I'm not sure how I'll change to mql5 since in mql5 send orders return bool's and not int's. I would be glad if I could get help with fixing this remaining part.
void MakeOrders()
{
static datetime lastTime = 0;
datetime currTime = iTime(Symbol(),PERIOD_M3,0);
if (currTime>lastTime)
{
for (int i=ObjectsTotal(0, 0, -1)-1; i>=0; i--)
{
string name = ObjectName(0, i, 0, -1);
if (ObjectGetString(0, name, OBJPROP_NAME, 0)==OBJ_RECTANGLE && ObjectGetString(0,name,OBJPROP_TEXT)=="")
{
double entryPrice=ObjectGetDouble(0,name,OBJPROP_PRICE,1)-3*_Point;
double stopLoss=ObjectGetDouble(0,name,OBJPROP_PRICE,2);
double slDist=fabs(entryPrice-stopLoss);
double dTakeProfit=entryPrice-2*slDist;
MqlTradeRequest request={0};
MqlTradeResult result={0};
//--- parameters of request
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =lotSize; // volume of 0.1 lot
request.type =ORDER_TYPE_BUY_LIMIT; // order type
request.price = entryPrice; // price for opening
//request.deviation=5; // allowed deviation from the price
request.magic =magicnumber; // MagicNumber of the order
request.tp = dTakeProfit;
request.sl = stopLoss;
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError());
/*
int ticketSell = OrderSend(Symbol(),OP_SELLLIMIT,lotSize, entryPrice,0,stopLoss,dTakeProfit,"SellOrder",magicnumber,0,Red);
if (ticketSell>0)
{
ObjectSetText(name,string(ticketSell));
i = ObjectsTotal()-1; // rather than continuing the 'for' loop, we must restart because arrows (ie new objects) were created.
}
*/
}
}
lastTime = currTime;
}
}
if(result.retcode==10009 || result.order>0)
ObjectSetText(name,string(result.order));

Calculate Standard Deviation in MQL from a custom built array

I am trying to calculate the lower 2SD and higher 2SD for a ratio of the price for two instruments, however, it is giving me 0 results. The expected results look like this. enter image description here
I tried to create an array by declaring the array in global scope and then adding values to it, however it is giving me zero as value, I also tried to add values manually to check if it is working but the function StdDev is also giving me same results. Any help to guide me where I am wrong would be deeply appreciated.
These are the codes tried by me, however not giving me any result.
d[z] = iClose(sym1,0,z)/iClose(sym2,0,z);
c = iStdDevOnArray(iClose(sym1,0,z),0,z,0,0,z);
The code I am deploying is as below.
#property indicator_separate_window
#property indicator_buffers 4
extern string sym1 = "AUDUSD";
extern string sym2 = "NZDUSD";
extern int barcount = 500;
//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
//Global Variables
int ArrayIndex;
double ArraySum;
double a = 0;
double b=0;
double c=0;
double lowersd=0;
double highersd=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_LINE,EMPTY,2,clrYellow);
SetIndexBuffer(0,ExtMapBuffer1);
SetIndexStyle(1,DRAW_LINE,EMPTY,2,clrRed);
SetIndexBuffer(1,ExtMapBuffer2);
SetIndexStyle(2,DRAW_LINE,EMPTY,2,clrGreen);
SetIndexBuffer(2,ExtMapBuffer3);
SetIndexStyle(3,DRAW_LINE,EMPTY,2,clrPink);
SetIndexBuffer(3,ExtMapBuffer4);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
//----
for(int z=0;z<barcount;z++)
{
// To calculate the average of the ratio
a=iClose(sym1,0,z)+a;
// Alert(d[0]);
b=iClose(sym2,0,z)+b;
// Below are the dummy data to create the chart
lowersd = 1.04;
highersd = 1.115;
}
for(int i=0;i<barcount;i++)
{
ExtMapBuffer1[i] = iClose(sym1,0,i)/iClose(sym2,0,i);
ExtMapBuffer2[i] = (a/b);
ExtMapBuffer3[i] = lowersd; // these are dummy values i am trying to populate this dynamically using the non working code above.
ExtMapBuffer4[i] = highersd;
}
//----
return(0);
}
You can use this to first initialize the array
double arr[];
ArrayResize(arr, barcount);
arr[z] = iClose(sym1,0,z)/iClose(sym2,0,z);
c=iStdDevOnArray(arr,barcount,barcount,0,MODE_EMA,0);
Then you can put this value in ExtBuffer
ExtMapBuffer3[i] = (a/b)-(c*2);
ExtMapBuffer4[i] = (a/b)+(c*2);

Change an integer value after a time interval ios

I am making a game with powerups. I have 3 powerups. When a powerup is active, I use an integer to identify which one it is, 1, 2, or 3, with 0 representing no active powerups. Once I activate a powerup, I want it to expire after a time interval, say 10 seconds. How do I reset the identifier integer back to 0?
For example, one powerup speeds up the ship. Here is my update method.
-(void) update:(ccTime)dt
{
if (powerupIdentifier == 0)
{
shipSpeed = 100;
}
if (powerupIdentifier == 1)
{
shipSpeed = 200;
}
CCArray* touches = [KKInput sharedInput].touches;
if ([touches count] == 1)
{
//MAKES SHIP MOVE TO TAP LOCATION
KKInput * input = [KKInput sharedInput];
CGPoint tap = [input locationOfAnyTouchInPhase:KKTouchPhaseBegan];
ship.position = ccp( ship.position.x, ship.position.y);
if (tap.x != 0 && tap.y != 0)
{
[ship stopAllActions]; // Nullifies previous actions
int addedx = tap.x - ship.position.x;
int addedy = tap.y - ship.position.y;
int squaredx = pow(addedx, 2);
int squaredy = pow(addedy, 2);
int addedSquares = squaredx + squaredy;
int distance = pow(addedSquares, 0.5);
[ship runAction: [CCMoveTo actionWithDuration:distance/shipSpeed position:tap]];//makes ship move at a constant speed
}
}
}
First, use an enum rather than an int.
typedef NS_ENUM(unsigned short, PowerUp) {
PowerUp_Level0,
PowerUp_Level1,
PowerUp_Level2,
PowerUp_Level3
};
Enum is far more readable, and is a lot more self-documenting then random integers.
Now, say we have a property:
#property (nonatomic, assign) PowerUp powerUp;
We can write a method to reset the power up:
- (void)resetPowerUp {
self.powerUp = PowerUp_Level0;
}
Now, when we've set it to some non-zero value and need to reset it (after 10 seconds), it's as simple as this:
self.powerUp = PowerUp_Level2;
[self performSelector:#selector(resetPowerUp) withObject:nil afterDelay:10.0f];

This sample code has me define something, but I don't want to just yet?

I have some open source code, which includes this:
.h:
#define TILE_ROWS 6
#define TILE_COLUMNS 2
#define TILE_COUNT (TILE_ROWS * TILE_COLUMNS)
#class Tile;
#interface TilesViewController : UIViewController {
#private
CGRect tileFrame[TILE_COUNT];
Tile *tileForFrame[TILE_COUNT];
}
And then throughout the .m, like so:
for (int row = 0; row < TILE_ROWS; ++row) {
for (int col = 0; col < TILE_COLUMNS; ++col) {
and
tileFrame[index] = frame;
and
tileForFrame[index] = tile;
But what i want is to be able to set TILE_ROWS to the outcome of, for example:
float rowsNeeded = ceil(rowsNeededA/TILE_COLUMNS);
So therefore it would need to be later on, but I think the CGRect and Tile can only be defined there. I need help, I'm not sure what to do.
You have to turn the defines into instance variable and to allocate the arrays dynamically:
#class Tile;
#interface TilesViewController : UIViewController {
#private
int tileRows;
int tileColumns;
int tileCount;
CGRect* tileFrame;
Tile** tileForFrame;
}
...
tileColumns = 2;
tileRows = (rowsNeededA + tileColumns - 1) / tileColumns;
tileCount = tileColumns * tileRows;
tileFrame = (CGRect*)malloc(tileCount * sizeof(CGRect));
tileForFrame = (Tile**)malloc(tileCount * sizeof(Tile*));
The for loop then becomes:
for (int row = 0; row < tileCount; ++row) {
for (int col = 0; col < tileCount; ++col) {

Resources