How to solve the warning: "possible loss of data due to type conversion" in MQL5 - type-conversion

I wrote this sample code for learning purposes but I can't seem to solve the warning message of "possible loss of data due to type conversion".
I have tried to search online but I can't seem to find a solution on how to pass the value of the MQL5 built-in functions without getting this warning.
The iAMA built-in function of MQL5 returns an integer and this integer is getting assigned to a variable of type integer (as shown in the sample code below). I am not sure why there is a data loss warning if both of them are integers.
Note: The code is compiling and running well but for educational purposes, I would like to understand how to solve this warning message.
Your help will be much appreciated!
Here is the code:
// --- Information Properties
#property description "Adaptive Moving Average Function Test"
//--- Core Properties
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
// --- Styling & Labels Properties
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlack
#property indicator_width1 2
#property indicator_label1 "Adaptive Moving Average"
//--- Constant Variables
const int ama_period = 34;
const int ama_fast_ma = 2;
const int ama_slow_ma = 34;
//--- Global Variables
double ama_src = PRICE_MEDIAN;
//--- Buffers
double ama_buffer[];
//--- Handles
int ama_buffer_handle;
//+------------------------------------------------------------------+
//| Indicator Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Buffers Assignment
SetIndexBuffer(0, ama_buffer, INDICATOR_DATA);
//--- Accuracy Setting
IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
//--- First Bar Setting
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, ama_period - 1);
//--- Line Shifts Calculations
PlotIndexSetInteger(0, PLOT_SHIFT, 0);
//--- Labels Calculations
PlotIndexSetString(0, PLOT_LABEL, "AMA");
//--- Handles Calculations
ama_buffer_handle = iAMA(NULL, 0, ama_period, ama_fast_ma, ama_slow_ma, 0, ama_src);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| OnCalculate 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(rates_total < ama_period)
{
return(0);
}
//--- Troubleshooting: Data Calculation
int calculated = BarsCalculated(ama_buffer_handle);
if(calculated < rates_total)
{
Print("Not all data of ama_buffer_handle is calculated (", calculated, " bars). Error ", GetLastError());
return(0);
}
//--- Troubleshooting: Data Copying
int to_copy;
if(prev_calculated > rates_total || prev_calculated < 0)
{
to_copy = rates_total;
}
else
{
to_copy = rates_total - prev_calculated;
if(prev_calculated > 0)
{
to_copy++;
}
}
//--- Copy & Validate Buffers
if(CopyBuffer(ama_buffer_handle, 0, 0, to_copy, ama_buffer) <= 0)
{
Print("getting ama_buffer_handle is failed! Error ", GetLastError());
return(0);
}
if(IsStopped())
{
return(0);
}
return(rates_total);
}

After reviewing back the documentation, I found out that I need to pass an ENUM_APPLIED_PRICE to the iAMA function instead of a double variable. That resolves the problem.
As in: ENUM_APPLIED_PRICE ama_src = PRICE_MEDIAN;

You should Flag your own Answer as solved,
to be fair for everybody.
Thank you.

Related

STM32 Read event from remoteControlEvent_t and parse data. Values are wrong with passing

I have small problem with adding and reading values.
Define variables
#define ADC_BIT_MASK 0x0FFF
static TaskHandle_t remoteControlTaskHandle = NULL;
typedef enum
{
...
rcEvent_FreshADC = 0x80000000,
...
}
Code for notify task. adc12bitVal_pedal value is for example 100 and adc12bitVal_lr value for example 1000. I am shifting adc12bitVal_lr to the left that I can pass params ...
static void remoteControl_FreshADC(uint16_t adc12bitVal_pedal, uint16_t adc12bitVal_lr)
{
if(remoteControlTaskHandle != NULL)
{
xTaskNotify(remoteControlTaskHandle,
(rcEvent_FreshADC | (adc12bitVal_pedal & ADC_BIT_MASK) | (adc12bitVal_lr & ADC_BIT_MASK)<<12),
eSetValueWithOverwrite);
}
}
and then remoteControlHandleEvent which handle an event. Here I have problem with adcVal_lr which should be 1000 but is for example 52123. I need to shift 12 to the left that I get correct value. Or this is wrong?
returnCode_t remoteControlHandleEvent(remoteControlEvent_t event)
{
if(event & rcEvent_motorControlACK)
{
uint8_t ackNum = (uint8_t) ( ((event >> MOTOR_CONTROL_ACK_BIT_POS) & MOTOR_CONTROL_ACK_BIT_MASK));
printf("CONF: %u\n", (unsigned int)ackNum);
}
if(event & rcEvent_FreshADC)
{
...
// Value is 100
uint16_t adcVal_pedal = (uint16_t)(event & ADC_BIT_MASK);
// DOESN'T WORK VALUE IS 52123 instead of 1000
uint16_t adcVal_lr = (uint16_t)((event & ADC_BIT_MASK)<<12);
...
}
}
I don't understand and know why wrong value for
uint16_t adcVal_lr = (uint16_t)((event & ADC_BIT_MASK)<<12);
Thnak you for all comments and help.
You are shifting left (up) twice. To extract a value that you shifted left you need to shift right (down). You also apply the mask before shifting, when it should be after.
uint16_t adcVal_lr = (uint16_t)((event >> 12) & ADC_BIT_MASK);

Not getting decreasing gas in a C++ program

Ok, so I have this program that is suppose to simulate an "Uber" driver picking up and dropping off customers and informing him of how far he has driven and how much gas he should have felt. I basically have it all worked out but for the life of me I can't get the gas to go down it stays at a static number. I know it is probably something so simple its dumb but I can't see it.
in my FuelGauge.h
#ifndef FuelGauge_h
#define FuelGauge_h
#define MAXG 15
// Class FuelGauge definition
class FuelGauge
{
// Data member
static int gallons;
public:
// Overloading -- operator
void operator --()
{
--gallons;
}// End of function
// Function to return gallons
int getGallons()
{
return gallons;
}// End of function
};// End of class
// Initializes static data member
int FuelGauge::gallons = MAXG;
#endif /* FuelGauge_hpp */
in my Car.h
#ifndef Car_h
#define Car_h
#include "FuelGauge.h"
#include "Odometer.h"
// Class car definition
class Car
{
public:
// Declares object as data member using deligation
FuelGauge *fg;
Odometer *om;
// Overloads >> operator
friend std::istream & operator >>(std::istream &is, Car &c)
{
int no;
// Loops till valid mileage entered by the user
do
{
// Accepts mileage
std::cin>>no;
// Checks if the mileage is zero or negative show error message
if(no <= 0)
std::cout<<"\n Invalid response, mileage should be greater than 0. \n Please reenter data.";
// Otherwise come out of the loop
else
break;
}while(1);
// Loops till no
for(int x = 0; x < no; x++)
// Increase the mileage by one
++*c.om;
// Checks if the current mileage is greater than or equals to 24 and entered mileage is less than 24
if(c.om->getCurrentMileage() >= 24 && no < 24)
// Decrement by one
--*c.fg;
// Otherwise
else
{
// Calculate the remainder
int rem = (no / 24);
// Loops till remainder
for(int x = 0; x < rem; x++)
// Decrease by one
--*c.fg;
}// End of else
// return istream object
return is;
}// End of function
// Overload << operator
friend std::ostream & operator <<(std::ostream &os, Car &c)
{
// Checks if the current gallon is less than or equals to zero
if(c.fg->getGallons() <= 0)
{
// Display message and stop
std::cout<<"\n Drove "<<c.om->getCurrentMileage()<<" miles I'm out of gas.";
exit(0);
}// End of if condition
// Otherwise display total mileage traveled and fuel left
else
std::cout<<"\n Drove "<<c.om->getCurrentMileage()<<" miles now I have "<<c.fg->getGallons()<<" gallons left.";
return os;
}// End of function
};// End of class
#endif /* Car_hpp */
and lastly Main.cpp
#include<iostream>
#include<stdlib.h>
#include "FuelGauge.h"
#include "Odometer.h"
#include "Car.h"
using namespace std;
// main function definition
int main()
{
int customer = 1;
// Creates car object
Car cc;
// Loops till = 0 fuel available
do
{
// Accepts data and displays data using object
cout<<"\n How far away is customer #"<<customer<<"? ";
cin>>cc;
cout<<cc;
cout<<"\n How far does customer #"<<customer<<" need to go?";
cin>>cc;
cout<<cc;
}while(static_cast<void>(customer++),1);// End of do - while
}// End of main function
I believe that problem is in my FuelGauge.h but I'm not seeing it. If someone would be so kind to look it over and let me know if they see anything I would greatly appreciate it.

How to close all trades in an MQL5 code ( script, EA )?

Struggling in writing a CLOSE ALL TRADES code in MQL5 as part of my Expert Advisor.
Code or any idea about closing all trades in MQL5 will be very helpful.
As I am new to EA writing, please be little easy in writing.
Welcome to the Wild Worlds of MQL4/5
You may get inspired by this raw example, as the MQL5 has changed the way, how the Terminal / Server interaction is controlled:
#define ID_OWN_MAG_NUM 9999999 // ALWAYS: use MagicNumber of the expert, to avoid MIX
//+----------------------
//| Closing all positions, MATCHING this ID_OWN_MAG_NUM ( avoid deleting others ...
//+----------------------
void OnStart()
{ // .DEF + .INIT the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total = PositionsTotal(); // .GET number of open positions
for ( int i = total - 1; i >= 0; i-- ) // .ITER over all open positions
{ // .GET params of the order:
ulong position_ticket = PositionGetTicket( i ); // - ticket of the position
string position_symbol = PositionGetString( POSITION_SYMBOL ); // - symbol
int digits = (int) SymbolInfoInteger( position_symbol,
SYMBOL_DIGITS
); // - number of decimal places
ulong magic = PositionGetInteger( POSITION_MAGIC ); // - MagicNumber of the position
double volume = PositionGetDouble( POSITION_VOLUME ); // - volume of the position
ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE) PositionGetInteger( POSITION_TYPE ); // - type of the position
PrintFormat( "Tkt[#%I64u] %s %s %.2f %s MagNUM[%I64d]", // .GUI: print details about the position
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString( PositionGetDouble( POSITION_PRICE_OPEN ), digits ),
magic
);
if ( magic == ID_OWN_MAG_NUM ) // .IF MATCH:
{ ZeroMemory( request ); // .CLR data
ZeroMemory( result ); // .CLR data
// .SET:
request.action = TRADE_ACTION_DEAL; // - type of trade operation
request.position = position_ticket; // - ticket of the position
request.symbol = position_symbol; // - symbol
request.volume = volume; // - volume of the position
request.deviation = 5; // - allowed deviation from the price
request.magic = EXPERT_MAGIC; // - MagicNumber of the position
if ( type == POSITION_TYPE_BUY )
{ request.price = SymbolInfoDouble( position_symbol, SYMBOL_BID );
request.type = ORDER_TYPE_SELL;
}
else
{
request.price = SymbolInfoDouble( position_symbol, SYMBOL_ASK );
request.type = ORDER_TYPE_BUY;
}
PrintFormat( "WILL TRY: Close Tkt[#%I64d] %s %s", position_ticket,
position_symbol,
EnumToString( type )
);
if ( !OrderSend( request,result ) )
PrintFormat( "INF: OrderSend(Tkt[#%I64d], ... ) call ret'd error %d", position_ticket,
GetLastError()
);
PrintFormat( "INF: Tkt[#%I64d] retcode=%u deal=%I64u order=%I64u", position_ticket,
result.retcode,
result.deal,
result.order
);
}
}
}
//+------------------------------------------------------------------+
This works for me - closes all market Buys and/or Sells positions for a symbol. Suggest test on demo netting and hedging accounts for validation and clarifications.
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
trade.PositionClose(ticket);
}
or
if(abc == xyz)
{
CloseBuySellSymbol(0);
}
void CloseBuySellSymbol()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
trade.PositionClose(ticket);
}
}
if run in void OnTick() execution is subject to tick delay
if used in void OnChartEvent() execution is instantaneous
Simpler than that:
//positions
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong positionticket = PositionGetTicket(i);
trade.PositionClose(positionticket,-1);
Print("eliminando posiciĆ³n "+positionticket);
}
//orders
for(int i=OrdersTotal()-1;i>=0;i--)
{
ulong orderticket = OrderGetTicket(i);
trade.OrderDelete(orderticket);
Print("eliminando operation "+orderticket);
}
Trading is done by sending orders to open positions using the OrderSend() function, as well as to place, modify or delete pending orders. Each trade order refers to the type of the requested operation.
#define EXPERT_MAGIC 123456 // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Closing all positions |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total=PositionsTotal(); // number of open positions
//--- iterate over all open positions
for(int i=total-1; i>=0; i--)
{
//--- parameters of the order
ulong position_ticket=PositionGetTicket(i); // ticket of the position
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number of decimal places
ulong magic=PositionGetInteger(POSITION_MAGIC); // MagicNumber of the position
double volume=PositionGetDouble(POSITION_VOLUME); // volume of the position
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // type of the position
//--- output information about the position
PrintFormat("#%I64u %s %s %.2f %s [%I64d]",
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
magic);
//--- if the MagicNumber matches
if(magic==EXPERT_MAGIC)
{
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.position =position_ticket; // ticket of the position
request.symbol =position_symbol; // symbol
request.volume =volume; // volume of the position
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the position
//--- set the price and order type depending on the position type
if(type==POSITION_TYPE_BUY)
{
request.price=SymbolInfoDouble(position_symbol,SYMBOL_BID);
request.type =ORDER_TYPE_SELL;
}
else
{
request.price=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
request.type =ORDER_TYPE_BUY;
}
//--- output information about the closure
PrintFormat("Close #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, output the error code
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
//---
}
}
}
//+------------------------------------------------------------------+
More examples at MQL5 documentation:
https://www.mql5.com/en/docs/constants/tradingconstants/enum_trade_request_actions

Simple OS kernel -- screen output long string array issue

I am following the steps in: "Writing a Simple Operating System from Scratch". I got the basic kernel up and running, but got a strange error when I try to output a very long string.
The following code output all "0"s. But when I use a shorter "msg" string, then the screen prints "x".
I wonder if anybody can help me, thanks much! (I am testing it in Bochs in windows 8).
Here is the kernel.c
void start ()
{
// Create a pointer to a char , and point it to the first text cell of
// video memory (i.e. the top - left of the screen )
unsigned char *video_memory = ( unsigned char*) 0xb8000;
// At the address pointed to by video_memory , store the character 'X'
// (i.e. display 'X' in the top - left of the screen ).
// this string: the outputs are "0"s.
const char msg[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzAbcdefghijkAbcdefghijklmnopqrstuvwxyzA";
// this string: output are "x"s.
//const char msg[] = "abcdefghijklmnopqrstuvwxyzabcdefghijk";
int i = 0;
int offset = 0;
while(i<85)
{
// Test if msg points to the right memory
if(msg[i]==0)
{
video_memory[offset] = '0';
}
else
{
video_memory[offset] = 'x';
}
video_memory[offset+1] = 0x02; // Green color
i = i + 1;
offset = offset + 2;
//set_cursor(offset);
}
}

print floats from audio input callback function

I'm working on a university project that involves a lot of programming in C, especially with Portaudio & ALSA. At the moment i'm trying to make a callback function to pass audio through, standard input/output job. I was wondering if anybody could tell me how to print the floats from my inputBuffer to display in real time in the terminal? Here is the internal structure of my callback function so far.
Thanks very much for your help in advance!
#define SAMPLE_RATE (44100)
#define PA_SAMPLE_TYPE paFloat32
#define FRAMES_PER_BUFFER (64)
typedef float SAMPLE;
static int audio_callback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
SAMPLE *out = (SAMPLE*)outputBuffer;
const SAMPLE *in = (const SAMPLE*)inputBuffer;
unsigned int i;
(void) timeInfo; /* Prevent unused variable warnings. */
(void) statusFlags;
(void) userData;
if( inputBuffer == NULL )
{
for( i=0; i<framesPerBuffer; i++ )
{
*out++ = *in++; /* left - clean */
*out++ = *in++; /* right - clean */
}
}
return paContinue;
}