How to calculate the swap (rollover) in mt5 in term of account currency - metatrader4

Backgound:
using mt5
"swap" (rollover) price is defined in points (0.00001/0.001) - 5-digit broker
account currency: USD
The question is: how to calculate the "swap value" in terms of acc. currency in mt5. With other words, how many cents i will paid for one day rollover?
Currently have this "mql5" script:
#include <Trade\SymbolInfo.mqh>
void OnStart() {
CSymbolInfo sym; // symbol informations object
sym.Name( ChartSymbol() ); // get the object for the current chart symbol
if( sym.SwapMode() == SYMBOL_SWAP_MODE_POINTS) {
double lot = 0.1;
double swapUSD_long = sym.SwapLong() * 0; // need help here
double swapUSD_short = sym.SwapShort() * 0; // need help here
PrintFormat(
"symbol: %s swap_long: %.2f swap_short: %.2f swapUSD_long: %.2f swapUSD_short: %.2f",
sym.Name(),
sym.SwapLong(),
sym.SwapShort(),
swapUSD_long,
swapUSD_short
);
}
}
When attaching the script to EURAUD, it prints to terminal:
symbol: EURAUD swap_long: -10.80 swap_short: 6.80 swapUSD_long: 0.00
swapUSD_short: 0.00
so: the rollover price is 6.8 points for the short position. How to convert it to USD with current rate? For this need:
find the pair with the acc currency (in this case need find AUDUSD)
get the rate of AUDUSD sym.Bid() or sym.Ask()
and ...
simply need some help ;)

If I understand right your question, you can use the TickValueProfit and TickValueLoss. If the swap to some direction is negative (you will pay) use the TickvalueLoss and when positive use TickValueProfit.
You can make a function for this like the next:
double swap_value_currency(double value_point, double tickprofit, double tickloss)
{
if( value_point == 0.0 ) { return(0.0); }
if( value_point < 0.0 ) {
return( val * tickloss );
}
return( value_point * tickprofit);
}
The swap_value_currency returns the swap value depending on winning or losing for one standard lot.
so your fragment of code can be:
if( sym.SwapMode() == SYMBOL_SWAP_MODE_POINTS)
{
double swval_long = swap_value_currency(sym.SwapLong(), sym.TickValueProfit(), sym.TickValueLoss());
double swval_short= swap_vallue_currency(sym.SwapShort(), sym.TickValueProfit(), sym.TickValueLoss() );
}
and because this is for one standard lot, you need multiply it with your lot size...

Related

Kotlin/Java formatting Double values

My current formatting is this
DecimalFormat("#,##0.00").format(value)
I need to handle values like this
0.00 //ok
0.45 //ok
0.002 //Need to show 0.002 or 0.0020
0.0003 //Need to show 0.0003 or 0.00030
0.00004 //Need to show 0.00004 or 0.000040
0.00234567 //Need to show 0.0023
But sure the above code will not work on fractional part where a non zero value started at thousandth place else I will just ended up displaying 0.00 as if it is totally a zero value. I still want the above formatting with comma when dealing with whole number but also allowing me to format when non zero starts beyond hundredths place.
Further sample
0.0492 // 0.04 or 0.05 much better
700.356 // 700.35 or 700.36 much better
54232.542234 // 54,232.54
Try multiplying the number by 10 until you know you got to two non zero digits. This way you will get the number of decimal points you have to round up.
After that you use the NumberFormat to format the number like this:
val format = NumberFormat.getInstance()
format.maximumFractionDigits = nrOfDecimalPoints
val formattedNumber = format.format(yourNumber)
This way you will keep the thousands separator "," and the decimal will be cut off after two non zero digits.
EDIT
This is how the custom function looks like:
private fun customFormat(number: Double): String{
var temp = number - number.toInt()
temp *= 100
var nrDec = 2
if (number <= 0.0){
return "0.00"
}
if (temp >= 1.0){
val format = NumberFormat.getInstance(Locale.US)
format.maximumFractionDigits = nrDec
return format.format(number)
}
while (temp < 1.0 && nrDec < 15){
temp *= 10
nrDec ++
}
if((temp * 10 % 10) != 0.0){
nrDec++
}
val format = NumberFormat.getInstance(Locale.US)
format.maximumFractionDigits = nrDec
return format.format(number)
}
You can do it like this in order to cut of tailing 0:
public static void main(String []args){
double number1 = 0.2;
double number2 = 1.55;
double number3 = 0.00005;
double number4 = 0.50000;
DecimalFormat df = new DecimalFormat("###,##0.00#########");
System.out.println(df.format(number1)); // 0.20
System.out.println(df.format(number2)); // 1.55
System.out.println(df.format(number3)); // 0.00005
System.out.println(df.format(number4)); // 0.50
}
You just need to know how far your decimal digits should be checked.

Returning the smallest value within an Array List

I need to write a method that returns me the smallest distance (which is a whole number value) within an Array List called "babyTurtles". There are 5 turtles within this array list and they all move a random distance each time the program is ran.
I've been trying to figure out how to do it for an hour and all I've accomplished is making myself frustrated and coming here.
p.s.
In my class we wrote this code to find the average distance moved by the baby turtles:
public double getAverageDistanceMovedByChildren() {
if (this.babyTurtles.size() == 0) {
return 0;
}
double sum = 0;
for (Turtle currentTurtle : this.babyTurtles) {
sum = sum + currentTurtle.getDistanceMoved();
}
double average = sum / this.babyTurtles.size();
return average;
}
That's all I've got to work on, but I just can't seem to find out how to do it.
I'd really appreciate it if you could assist me.
This will give you the index in the array list of the smallest number:
int lowestIndex = distanceList.indexOf(Collections.min(distanceList));
You can then get the value using this:
int lowestDistance = distanceList.get(lowestIndex);

Compare two CGSize's to best persentage

Need your help, I have input CGSize (for example): 200x300. And array with other CGSize's = [20x20, 100x100, 150x150, 200x100, 200x250, 300x300...].
Please help me to find best item in array that have best compare percentage (for example its 200x250)...
I tried to use for enumerator, for example:
CGSize inputSize = CGSizeMake(200, 300);
for (int i = 0; i < array.count; i++)
{
CGSize concurentSize = CGSizeZero;
switch (i)
{
case 0:
{
concurentSize.width = 20;
concurentSize.height = 20;
}
and so on...
float differencePercentWidth = ( concurentSize.width / inputSize.width ) * 100.0;
float differencePercentHeight = ( concurentSize.height / inputSize.height ) * 100.0;
if (differencePercentWidth > 90 && differencePercentHeight > 90)
{
// FOUND best CGSize... stop
break.
}
}
But, its not working, it differencePercentWidth/differencePercentHeight can be > 100 =(
I need some of method or function that can compare 2 CGSize's in percent match... For example: size 200x300 is best matches with size 200x250... Something like:
float matchesInPerсent = CGSizeCompare(firstCGSize, secondCGSize);
//matchesInPerсent = 0.6; // in percents
Please help, sorry for my english, if you need more details, please let me know. Thanks.
Try the similar logic to calculate the maximum number in the array, but need to less then one finite value. In this cases calculate maximum percentage average of size.width and size.height, the maximum percentage which is closes to 1 is the winner. If you need the upper value of the 100% as well then you need to insert the logic to take that value below the 100% and run the same logic on those sizes as well.
Here is code which will give you closest percentage size from the array.
/*
sizes : array of the sizes represented in NSValue format
size: The size for which you need closest value.
*/
- (CGSize)bestMatch:(NSArray *)sizes withSize:(CGSize)size {
float bestMatch = 0.0;
CGSize bestMatchSize = CGSizeZero;
for (NSValue *value in sizes) {
float percentage = (value.CGSizeValue.width/size.width + value.CGSizeValue.height/size.height)/2;
//If you need greater then 100% and closes to the size
if (percentage > 1.0) {
percentage = -1*(percentage - 2);
}
if (bestMatch < percentage && percentage < 1) {
bestMatch = percentage;
bestMatchSize = value.CGSizeValue;
}
}
//If you need best match you can return bestMatch which is closest in percentage
return bestMatchSize;
}

velocity of a joint between two frames using kinect sdk

I'm stack for along time in this problem and i will really appreciate if any one could help me in that.
I asked many times in many forums, i've searched alot but no answer that really helped me.
i'm developping an application where i have to calculate the velocity of a joint of skeleton body using vs c# 2012 and kinect sdk 1.7
i have first to be sure of the logic of things before asking this question so,
if I understood correctly, the delta_time i'm looking for to calculate velocity, is not the duration of one frame (1/30s) but it must be calculated from two instants:
1- the instant when detecting and saving the "joint point" in the first frame
2- the instant when detecting and saving the same "joint point" in the next frame
if it's not true, thank you for clarifying things.
starting from this hypothesis, i wrote a code to :
detectiong a person
tracking the spine joint ==> if it's is tracked then saving its coordinates into a list (I reduced the work for the moment on the Y axis to simplify)
pick up the time when saving the coordinates
increment the framecounter (initially equal to zero)
if the frame counter is > 1 calculate velocity ( x2 - x1)/(T2 - T1) and save it
here is a piece of the code:
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
double msNow;
double msPast;
double diff;
TimeSpan currentTime;
TimeSpan lastTime = new TimeSpan(0);
List<double> Sylist = new List<double>();
private int framecounter = 0;
private void KinectSensorOnAllFramesReady(object sender, AllFramesReadyEventArgs allFramesReadyEventArgs)
{
Skeleton first = GetFirstSkeleton(allFramesReadyEventArgs);
if (first == null) // if there is no skeleton
{
txtP.Text = "No person detected"; // (Idle mode)
return;
}
else
{
txtP.Text = "A person is detected";
skeletonDetected = true;
/// look if the person is totally detected
find_coordinates(first);
/*******************************
* time computing *
/*******************************/
currentTime = stopWatch.Elapsed;
msNow = currentTime.Seconds * 1000 + currentTime.Milliseconds;
if (lastTime.Ticks != 0)
{
msPast = lastTime.Seconds * 1000 + lastTime.Milliseconds;
diff = msNow - msPast;
}
lastTime = currentTime;
}
//framecounter++;
}
void find_coordinates(Skeleton first)
{
//*modification 07052014 *****/
Joint Spine = first.Joints[JointType.Spine];
if (Spine.TrackingState == JointTrackingState.Tracked)
{
double Sy = Spine.Position.Y;
/*******************************
* time starting *
/*******************************/
stopWatch.Start();
Sylist.Add(Sy);
framecounter++;
}
else
return;
if (framecounter > 1)
{
double delta_Distance = Sylist[Sylist.Count] - Sylist[Sylist.Count - 1];
}
}
to be honnest, i dont really know how ti use timespan and stopwatch in this context ( i mean when there are frames to process many times/s)
i will be thankfull for any help !
First:
The SkeletonFrame has a property called Timespamp that you can use. It's better to use that one than to create your own timesystem because the timestamp is directly generated by the Kinect.
Second:
Keep track of the previous Timestamp and location.
Then it's just a matter of calculation.
(CurrentLocation - PreviousLocation) = Distance difference
(CurrentTimestamp - PreviousTimestamp) = Time taken to travel the distance.
For example you would get 0.1 meter per 33 miliseconds.
So you can get the meters per seconds like this = (1 second / time taken to travel) * distance difference. In the example this is = (1000/33)*0.1 = 3.03 meter per second.

Rounding with significant digits

In Xcode /Objective-C for the iPhone.
I have a float with the value 0.00004876544. How would I get it to display to two decimal places after the first significant number?
For example, 0.00004876544 would read 0.000049.
I didn't run this through a compiler to double-check it, but here's the basic jist of the algorithm (converted from the answer to this question):
-(float) round:(float)num toSignificantFigures:(int)n {
if(num == 0) {
return 0;
}
double d = ceil(log10(num < 0 ? -num: num));
int power = n - (int) d;
double magnitude = pow(10, power);
long shifted = round(num*magnitude);
return shifted/magnitude;
}
The important thing to remember is that Objective-C is a superset of C, so anything that is valid in C is also valid in Objective-C. This method uses C functions defined in math.h.