How to include Fibonacci levels in Expert Advisor (EA)? - mql4

I want to have access to various Fibonacci levels like 23.6%, 38.2%, 50%, 61.8% and 100% in my expert advisor (EA). How can I define those in my EA so that traders can select them via the inputs?
I tried this
input double Fibo=23.6;
However, is this the common approach? Is it possible to set them as predefined?
Thank you for your help!

You can set predefined Fibonacci levels by using enumerations. Either you use enumerations provided by MQL5 or define your own, like this:
//+------------------------------------------------------------------+
//| Enumeration for Fibonacci levels |
//+------------------------------------------------------------------+
enum ENUM_FIBO_LEVELS
{
fib0618 = 0618, // 61.8%
fib1000 = 1000, // 100.0%
fib1382 = 1382, // 138.2%
fib1618 = 1618, // 161.8%
};
Note: If you place a single-line comment, it will be associated with the variable name, as shown in this example.
input ENUM_FIBO_LEVELS FiboValue=fib1618; // Fibonacci level
As a result, users are able to select their preferred Fibonacci level:
To calculate potential support and resistance levels, convert the Fibonacci ENUM level:
(double(FiboValue)/1000)
If you have any further questions, please leave a comment below.

Related

why mql4 show error 130 when we use Stoploss in OrderSend function

I am trying to create a EA in mql4, but in OrderSend function, when i use some value instead of zero it show ordersend error 130. Please help to solve this problem
Code line is
int order = OrderSend("XAUUSD",OP_SELL,0.01,Bid,3,Bid+20*0.01,tp,"",0,0,Red);
error number 130 means Invalid stops.
so that means there is a problem with the stops you set with the ordersend function.
I suggest you set it like that:
int order = OrderSend("XAUUSD",OP_SELL,0.01,Bid,3,Bid+20*Point,tp,"",0,0,Red);
so you could use Point instead of hard coding it.
and to check what is the error number means. I think you could refer to: https://book.mql4.com/appendix/errors
You should know that there exists a minimum Stop Loss Size (mSLS) given in pips. "mSLS" changes with the currency and broker. So, you need to put in the OnInit() procedure of your EA a variable to get it:
int mSLS = MarketInfo(symbol,MODE_STOPLEVEL);
The distance (in pips) from your Order Open Price (OOP) and the Stop-Loss Price (SLP) can not be smaller than mSLS value.
I will try to explain a general algorithm I use for opening orders in my EAs, and then apply the constrain on Stop-Loss level (at step 3):
Step 1. I introduce a flag (f) for the type of operation I will open, being:
f = 1 for Buy, and
f = -1 for Sell
You know that there are mql4 constants OP_SELL=1 and OP_BUY=0 (https://docs.mql4.com/constants/tradingconstants/orderproperties).
Once I have defined f, I set my operation type variable to
int OP_TYPE = int(0.5((1+f)*OP_BUY+(1-f)*OP_SELL));
that takes value OP_TYPE=OP_BUY when f=1, while OP_TYPE=OP_SELL when f=-1.
NOTE: Regarding the color of the orders I put them in an array
color COL[2]= {clrBlue,clrRed};
then, having OP_TYPE, I set
color COLOR=COL[OP_TYPE];
Step 2. Similarly, I set the Order Open Price as
double OOP = int(0.5*((1+f)*Ask+(1-f)*Bid));
which takes value OOP=Ask when f=1, while OOP=Bid when f=-1.
Step 3. Then, given my desired Stop Loss in pips (an external POSITIVE parameter of my EA, I named sl) I make sure that sl > SLS. In other words, I check
if (sl <= mSLS) // I set my sl as the minimum allowed
{
sl = 1 + mSLS;
}
Step 4. Then I calculate the Stop-Loss Price of the order as
double SLP = OOP - f * sl * Point;
Step 5. Given my desired Take Profit in pips (an external POSITIVE parameter of my EA, I named tp) I calculate the Take-Profit Price (TPP) of the order as
double TPP = OOP + f * tp * Point;
OBSERVATION: I can not affirm, but, according to mql4 documentation, the minimum distance rule between the stop-loss limit prices and the open price also applies to the take profit limit price. In this case, a "tp" check-up needs to be done, similar to that of the sl check-up, above. that is, before calculating TPP it must be executed the control lines below
if (tp <= mSLS) // I set my tp as the minimum allowed
{
tp = 1 + mSLS;
}
Step 5. I call for order opening with a given lot size (ls) and slippage (slip) on the operating currency pair (from where I get the Ask and Bid values)
float ls = 0.01;
int slip = 3; //(pips)
int order = OrderSend(Symbol(),OP_TYPE,ls,OOP,slip,SLP,TPP,"",0,0,COLOR);
Note that with these few lines it is easy to build a function that opens orders of any type under your command, in any currency pair you are operating, without receiving error message 130, passing to the function only 3 parameters: f, sl and tp.
It is worth including in the test phase of your EA a warning when the sl is corrected for being less than the allowed, this will allow you to increase its value so that it does not violate the stop-loss minimum value rule, while you have more control about the risk of its operations. Remember that the "sl" parameter defines how much you will lose if the order fails because the asset price ended up varying too much in the opposite direction to what was expected.
I hope I could help!
Whilst the other two answers are not necessarily wrong (and I will not go over the ground they have already covered), for completeness of answers, they fail to mention that for some brokers (specifically ECN brokers) you must open your order first, without setting a stop loss or take profit. Once the order is opened, use OrderModify() to set you stop loss and/or take profit.

Linear Regression Using CEP

What is the best approach to achieve a linear regression using CEP ?. We have tried two different options.
We do want to have the algorithm working in real time.
Basic code for both approach :
create context IntervalSpanning3Seconds start #now end after 30 sec;
create schema measure (
temperature float,
water float,
_hours float,
persons float,
production float
);
#Name("gattering_measures")
insert into measure
select
cast(getNumber(m,"measurement.bsk_mymeasurement.temperature.value"),
float) as temperature,
cast(getNumber(m, "measurement.bsk_mymeasurement.water.value"), float) as water,
cast(getNumber(m, "measurement.bsk_mymeasurement._hours.value"), float) as _hours,
cast(getNumber(m, "measurement.bsk_mymeasurement.persons.value"), float) as persons,
cast(getNumber(m, "measurement.bsk_mymeasurement.production.value"),float) as production
from MeasurementCreated m
where m.measurement.type = "bsk_mymeasurement";
1. Using the function stat:linest
#Name("get_data")
context IntervalSpanning3Seconds
select * from measure.stat:linest(water,production,_hours,persons,temperature)
output snapshot when terminated;
EDIT: The problem here is that it seems like the "get_data" is getting execute by each measurement and not by the entire collection of measurement.
2. Get data and passed a javascript function.
create expression String exeReg(data) [
var f = f(data)
function f(d){
.....
// return the linear regression as a string
}
return f
];
#Name("get_data")
insert into CreateEvent
select
"bsk_outcome_linear_regression" as type,
exeReg(m) as text,
....
from measure m;
EDIT: Here, I would like to know what is the type of the variable that is passed to the exeReg() function and how I should iterate it ? example would be nice.
I'll appreciate any help.
Using JavaScript would mean that the script computes a new result (recomputes) for each collection it receives. Instead of recomputing it the #lineest data window is a good choice. Or you can add a custom aggregation function or custom data window to the engine if there is certain code your want to use. Below is how the script can receive multiple events for the case when a script is desired.
create expression String exeReg(data) [
.... script here...
];
select exeReg(window(*)) ....
from measure#time(10 seconds);

OpenCV partition() underlying algorithm

Does anybody know what algorithm is used here?
I want to implement this function to do detection's windows grouping.
Thank you.
If you look at the OpenCV source code for the partition function, you will see the following comments:
// This function splits the input sequence or set into one or more equivalence classes and
// returns the vector of labels - 0-based class indexes for each element.
// predicate(a,b) returns true if the two sequence elements certainly belong to the same class.
//
// The algorithm is described in "Introduction to Algorithms"
// by Cormen, Leiserson and Rivest, the chapter "Data structures for disjoint sets"
template<typename _Tp, class _EqPredicate> int partition( const vector<_Tp>& _vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate())
{
// ... etc.
}
This gives you both the source code, and the reference for the algorithm.
So, that's Chapter 21 in this book.

How to calculate RPG Level Progression as percentage

I'm designing an RPG game where a user may accumulate experience points (XP) and level up, based on XP. Calculating the current level is trivial; if else seems to be most efficent.
I would like to calculate percent of progression for the current level. Based on the assumption that I have 10 levels, where each level is capped at a somewhat exponential value:
typedef NS_ENUM(NSInteger, RPGLevelCap) {
RPGLevelCap1=499,
RPGLevelCap2=1249,
RPGLevelCap3=2249,
RPGLevelCap4=3499,
RPGLevelCap5=4999,
RPGLevelCap6=6999,
RPGLevelCap7=9999,
RPGLevelCap8=14999,
RPGLevelCap9=19999,
RPGLevelCap10=19999 // Anything beyond previous level is Lvl 10; display as 100%
};
What's an efficient, yet easily understandable way, to calculate a user's level progression based on their current level?
An if else statement is both hard to understand and maintain, but may be fairly efficient:
float levelProgression=0;
// Calculate level progression as a fraction of 1
if(xp <= RPGLevelCap1)
{
levelProgression = ((float)xp / RPGLevelCap1);
}
else if (xp <=RPGLevelCap2)
{
levelProgression = ((float)(xp-RPGLevelCap1) / (RPGLevelCap2-RPGLevelCap1));
}
else if (xp <=RPGLevelCap3)
{
levelProgression = ((float)(xp-RPGLevelCap2) / (RPGLevelCap3-RPGLevelCap2));
}
...
else if (xp>RPGLevelCap10)
{
levelProgression = 1;
}
Given that the level caps are inconsistent...how should I handle this problem?
Hmm. A simple way would be to store the level cap values in an array. Find the player's current level based on the largest value it's less than. (level one is 0 to 499, level two is 500 to 1249, etc.) Use a loop to find the user's level rather than a set of if/else statements.
Then calculate the range of the player's current level, (end_of_range - start_of_range)
0 - 499 = 499
500 - 1249 = 749,
etc.
If a player is at 600 points, he's a level 2 character, in the 500-1249 range.
He's at 600-500 or 100 points into the range. (600-500)/749*100 is the player's percent complete in that range. 13.35% complete, in this example.
There are a few ways you can approach this. My weapon of choice here is to embody the XP values within the concept of LevelData versus using an enum, array of XP values, etc. The benefit of something like this is that for each level, you'll typically have many configurable values (for example level based multipliers) based on level. This way they are all in once place.
In your LevelData, there are different ways you can encode XP. These range from the XP total for the next level, or the beginning and end XP total for the next level. Obviously there are other permutations of this.
I usually use the later, mainly because it prevents me from having to "know" the LevelData for the previous level.
So I would typically have this in JSON
{
"levelData": [
{
"levelStartXP": "0",
"levelUpXP": "250",
"levelUpBonus": 0
},
{
"levelStartXP": "250",
"levelUpXP": "1000",
"levelUpBonus": 50
},
{
"levelStartXP": "1000",
"levelUpXP": "2500",
"levelUpBonus": 100
},
]
}
This is just a boring example. I then of course have a LevelData class which is embodies each level. I also have a LevelDataManager. That manager is used to vend out information per level. Having convenience methods help. For examples, good ones to have are:
- (NSInteger)levelWithXP:(NSInteger)xp; // for a given XP, give me the appropriate level
- (LevelData *)levelDataWithXP:(NSInteger)xp; //for a given XP, give me the appropriate LevelData
- (LevelData *)levelDataWithLevel:(NSInteger)level; // for a given level, give me the appropriate LevelData
- (NSInteger)levelUpXPForLevel:(NSInteger)level; // for a given level, give me the XP value needed for the next level)
I just arbitrarily used NSInteger, use the appropriate data type for your case.
Just what you want to support is really up to you.
The gist of the whole thing is try not to store individual level components. Rather aggregate them in LevelData or some other collection, so you have all the info per level at your disposal and create some form of manager/interface to get you the information you need.
So back to you your question. Let's say we have a class for LevelData (assume it is using the JSON above, and those fields are represented by properties) and a LevelDataManager instance called theLevelDataMgr, you could compute the % based on something like:
LevelData *levelData = [theLevelDataMgr levelDataWithLevel:currLevel]; // currLevel is the current level
float xpDiffInLevel = levelData.levelUpXP - levelStartXP;
float xpInLevel = currXP - levelStartXP; // currXP is the current XP of the user
float pctOfXP = xpInLevel / xpDiffInLevel; // You should add divide by zero check
And yes, if you wanted, you could have the LevelData class contain a method to do this calculation for you to help encapsulate it even better.
Code isn't tested and is listed to just give you a better idea on how to do it. Also, how you decide to store your XP for each level dictates how this would work. This code is based on the method I usually use.

How to implement GKTurnBasedMatchOutcomeCustomRange?

I've looked in the Apple GameKit Programming Guide, as well as the documentation of the GKTurnBasedParticipant to try and figure out how to implement the custom range. Apple docs say:
"Optionally, it may also use an OR operation to include a custom match outcome for your specific game. Game Center does not use the custom value; it exists to allow your game to provide additional information at the end of the match. The custom value must fit in the range provided by the GKTurnBasedMatchOutcomeCustomRange constant."
....
GKTurnBasedMatchOutcomeFourth = 9,
GKTurnBasedMatchOutcomeCustomRange = 0x00FF0000
};
typedef NSInteger GKTurnBasedMatchOutcome;*
I am not sure what to do to make a custom value or string for the outcome of the match. Any help would be appreciated!
Thanks,
Tams
I think you need to start from 1 rather than 0. Thus:
GKTurnBasedMatchOutcomeCustom0 = 1 | GKTurnBasedMatchOutcomeCustomRange
etc
Otherwise, the match is not considered to be over if you use GKTurnBasedMatchOutcomeCustom0.
You may want to check it out for yourself.
To create a custom match outcome enum, adapt the following to your purposes:
typedef enum
{
GKTurnBasedMatchOutcomeCustom0 = 0 | GKTurnBasedMatchOutcomeCustomRange,
GKTurnBasedMatchOutcomeCustom1 = 1 | GKTurnBasedMatchOutcomeCustomRange,
GKTurnBasedMatchOutcomeCustom2 = 2 | GKTurnBasedMatchOutcomeCustomRange,
...
GKTurnBasedMatchOutcomeCustomLast = 65536 | GKTurnBasedMatchOutcomeCustomRange
} GKTurnBasedMatchOutcome_Custom;
For example, GKTurnBasedMatchOutcomeCustom1 will be equal to 0xFF0000.
Essentially, you are allowed a maximum of 0xFFFF+1 (65536 in decimal) custom match outcome states.

Resources