What is the difference between init() and OnInit()? - algorithmic-trading

I am learning MQL4. On their reference website, creating a custom indicator is done like as follows:
#property indicator_chart_window
int init(){
return(0);
}
int deinit(){
ObjectsDeleteAll();
return(0);
}
int start(){
return(0);
}
But when I create a new Indicator from inside the MetaEditor, I get another syntax, like this:
int OnInit()
{
//--- indicator buffers mapping
//---
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[])
{
//---
//--- return value of prev_calculated for next call
return(rates_total);
}
Why is it different?
Is there a web link, or book someone can refer me to?
From what I read the best place is the MQL4 website, but it looks different and I am not sure where to turn to now.
Any help will be appreciated. Thanks in advance.

There are some changes to the MQL4 after build 600.
The OnInit() is the Init-event handler. You can still use Init() as it is backward compatible. OnInit() is the newer practice.
Some of the online documentations are outdated and are not yet updated.
This link provide info on the changes: http://docs.mql4.com/mql4changes

Where the observed difference comes from?
An MQL4 language has moved ( somewhere about a MetaTrader4 Terminal LiveUpdate release Build 572 .. 6xx ) a "half-step" towards another generation of the MetaQuotes programming language ( named an MQL5 ).
While MQL4 language has spanned many years and is a mature and stable, both in concept and execution, the "new"-MQL4 introduces things, the "traditional" MQL4 language ( and the code-execution environment ) were not ready to use.
So, the observation you have made, is right due to the "old"-syntax code snippets residing on many web pages and a "new"-syntax, pasted inside a blank/new Indicator template by a "new"-MQL4-IDE.
What to do with that in practice?
Your "new"-syntax will work on any post-Build-572+ MetaTrader4 Terminals. You need not worry about an "incompatible" case, where "new" code would be colliding with an "old"-terminal, as MetaTrader4 Server has an internal setting, which dictates the "oldest"-allowed Terminal the Server is willing to allow to connect and serve. As a matter of fact, that means you will newer be able to connect / run a pre-Build-572 MetaTrader4 Terminal connected to a broker side, where the "new"-code could collide with "old"-syntax rules.
Anyway, for a sake of an MQL4 syntax disambiguation, there is a compiler directive available:
#property strict // read MQL4-IDE Help file for more details

Related

rust imgui, how do you set it up?

I am trying to set up rust imgui for a custom renderer I am porting to rust.
I am stuck on two fronts, getting the peripheral callbacks, and the rendering.
In C++ the setup was farily simple
ImGuiContext* InitImgui(ModuleStorage::ModuleStorage& module, NECore::Gallery& gallery)
{
ImGuiContext* imgui_context = ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
CpuImage font_image(pixels, width, height, 4);
uint font_id = gallery.StoreImage<CpuImage::GetImageData>(
font_image, "__ImguiFont", NECore::ImageFormat::R8G8B8A8_UNORM);
io.Fonts->SetTexID((ImTextureID)(intptr_t)font_id);
ImGui_ImplGlfw_InitForVulkan(module.GetWindow().GetGLFWWindow(), true);
imgui_shader = module.AddShader(
{"./CommonShaders/imgui.vert",
"./CommonShaders/imgui.frag"});
return imgui_context;
}
30 lines of code and we have the initialization done.
Well some issues in rust, io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); does not exist. I assume the equivalent is let font = fonts.build_rgba32_texture();
Assuming that's the case the next issue is setting the texture id, which I cannot find anywhere in the docs or the source code.
io.Fonts->SetTexID((ImTextureID)(intptr_t)font_id);
That function does not exist in the rust bindings. And ImGui_ImplGlfw_InitForVulkan is no where to be found either.
The examples https://github.com/imgui-rs/imgui-rs/blob/main/imgui-examples/examples/support/mod.rs
Seem to be using pre existen renderers and do not do a good job of showing how to integrate the tool onto an existing renderer other than the ones the author chose, which is baffling, one of the biggest selling points of imgui is how simple it is to integrate in pre-existing codebases.
I am at a loss, hwo do you bootstrap the library in rust?

XTestFakeKeyEvent calls get swallowed

I'm trying to spoof keystrokes; to be a bit more precise: I'm replaying a number of keystrokes which should all get sent at a certain time - sometimes several at the same time (or at least as close together as reasonably possible).
Implementing this using XTestFakeKeyEvent, I've come across a problem. While what I've written so far mostly works as it is intended and sends the events at the correct time, sometimes a number of them will fail. XTestFakeKeyEvent never returns zero (which would indicate failure), but these events never seem to reach the application I'm trying to send them to. I suspect that this might be due to the frequency of calls being too high (sometimes 100+/second) as it looks like it's more prone to fail when there's a large number of keystrokes/second.
A little program to illustrate what I'm doing, incomplete and without error checks for the sake of conciseness:
// #includes ...
struct action {
int time; // Time where this should be executed.
int down; // Keydown or keyup?
int code; // The VK to simulate the event for.
};
Display *display;
int nactions; // actions array length.
struct action *actions; // Array of actions we'll want to "execute".
int main(void)
{
display = XOpenDisplay(NULL);
nactions = get_actions(&actions);
int cur_time;
int cur_i = 0;
struct action *cur_action;
// While there's still actions to execute.
while (cur_i < nactions) {
cur_time = get_time();
cur_action = actions + cur_i;
// For each action that is (over)due.
while ((cur_action = actions + cur_i)->time <= cur_time) {
cur_i++;
XTestFakeKeyEvent(display, cur_action->code,
cur_action->down, CurrentTime);
XFlush(display);
}
// Sleep for 1ms.
nanosleep((struct timespec[]){{0, 1000000L}}, NULL);
}
}
I realize that the code above is very specific to my case, but I suspect that this is a broader problem - which is also why I'm asking this here.
Is there a limit to how often you can/should flush XEvents? Could the application I'm sending this to be the issue, maybe failing to read them quickly enough?
It's been a little while but after some tinkering, it turned out that my delay between key down and key up was simply too low. After setting it to 15ms the application registered the actions as keystrokes properly and (still) with very high accuracy.
I feel a little silly in retrospect, but I do feel like this might be something others could stumble over as well.

Setting AUParameter's value from Host App

The Problem
I am trying to get the new AUParameterTree and AUParameter's mechanism working in my Audio Unit V3 test project. The problem is that when I gain a reference to it from the Host App and change its value, the Audio Unit extension's parameter doesn't appear to change.
Here is my approach.
I'm using the new Audio Unit V3 API. I've created an AUParameter in my AUAudioUnit's initWithComponentDescription:
Creating the Parameter
AUParameter *param1 = [AUParameterTree createParameterWithIdentifier:#"frequency"
name:#"Frequency"
address:frequencyAddress
min:500
max:5000
unit:kAudioUnitParameterUnit_Hertz
unitName:nil
flags:0
valueStrings:nil
dependentParameters:nil];
Set a default value..
param1.value = 0.5;
some of the arguments to the Parameter constructor come from...
Some State
I have defined the address as a global constants:
const AudioUnitParameterID frequencyAddress = 0;
And a local variable for an AUValue:
AUValue frequency = 1;
Keep in mind at this point I'm just following the three example projects that use Audio Unit V3 on the entire internet. I find it difficult to piece together how this entire AU parameter dance should go only from reading the docs.
Rendering with the parameter
now when it comes to using the AUValue associated with the AUParameter "param1", (I assume thats how it works?)..
I am then capturing this AUValue ( the local variable which I'm unclear on how it is associated with the actual AUParameter ) .. in my Audio Unit rendering block:
- (AUInternalRenderBlock)internalRenderBlock {
AUValue * param1Capture = &frequency;
return ^AUAudioUnitStatus(AudioUnitRenderActionFlags *actionFlags, const AudioTimeStamp *timestamp, AVAudioFrameCount frameCount, NSInteger outputBusNumber, AudioBufferList *outputData, const AURenderEvent *realtimeEventListHead, AURenderPullInputBlock pullInputBlock) {
// use parameter value
someValue = *param1Capture;
// more dsp stuff..
Controlling Parameter from Host App
This is where the problem arises.
I declare a local reference to an AUParameter:
#interface ViewController (){
AudioEngine *_audioEngine;
AUParameter * _param1;
}
and when my Audio Engine class instantiates my AUAudioUnit it passes it to me:
[_audioEngine setupAUWithComponentDescription:desc andCompletion:^(AUAudioUnit * unit){
_param1 = [unit.parameterTree valueForKey:#"frequency"];
}];
no effect?
Now when I say:
[_param1 setValue: 1000];
The captured AUValue in my rendering block remains the same!
I've either overlooked a bug, a mindless type (I may have introduced a type in this write up of my problem so keep that in mind), or I have fundamentally misunderstood this mechanism.
If I need to provide more context for this problem I can easily push the project to Github.
Thanks in advance.
The problem turned out to have nothing to do with Core Audio and everything to do with a basic language level mistake.
frequency was declared at a file level scope like this:
AUValue frequency = 1;
#implementation MyAudioUnit
#end
My understanding is that frequency is now bound to file scope and not instance scope. Therefore repeated setting of it on different instances was simply overwriting the previous value. Hence, the last assignment was the frequency which would be rendered.

Attempting to store references to c++ vectors returned by reference still giving me copies

Back in '98 I converted my chemical model from objective-c to c++ after replacing my old NeXT, but I didn't really get a chance to learn c++. I'm now rewriting the code into modern c++, which means learning to use containers, smart pointers, and templates.
I need to parse output variables only once up front, rather than at each time step, so I originally produced a pointer array of output variable pointers (float ***outVars). I could run through the list of pointers after each time interval, and since outVars pointed to the original data, they would always provide the current state of the model.
I'm changing code from matrices of naked pointers to matrices of vectors. I haven't been able to return anything but copies of vectors, rather than references to the original vectors. I don't want to modify the vectors, I just need direct read access.
I can't believe I haven't found my answer online yet. Most that I've found online has simply said use std::vector<float> & to return by reference, but clearly that isn't working.
I saw one note that assigning a reference to a non-reference value (I assume they meant variable) will make it copy, so I tried fvec2D &outVar2D; (see the header file below).
I've tried with and without const, no difference.
I've tried returning vector.data(), but assigning it to a new vector was also copying. Maintaining pointers to .data() memory blocks seems be a very bad idea, if I need to resize the original vector.
I've tried wrapping the vector in std::shared_ptr, but found I'd need to wrap each dimension vector in a shared_ptr, which got overly cumbersome real fast.
I saw one suggestion to return vector::iterators. I haven't managed to get that to work yet. Maybe having 2D data is getting in the way of that. I'm still trying to get that to run without crashing when I examine the iterator.
I don't know if using a 1D array would solve this, but calculating every index reference for millions of calls seems suboptimal.
I considered using std::array too but vectors seemed the simplest conversion. Perhaps I should rethink that.
If anyone has any suggestions for how to do this, I'd very much appreciate it.
class chem - manages original matrix concentration
class chem
{
public:
typedef std::vector<float> fvec1D;
typedef std::vector<std::vector<float> > fvec2D;
chem(int xstep, int zstep) : concentration(xstep, fvec1D(zstep, 1.5)) {}
...
const fvec2D &getConc() const { return concentration; }
const fvec1D &getConc(int x) const {return concentration[x]; }
private:
fvec2D concentration;
};
class model - needs read access to chem::concentration
class model
{
public:
typedef std::vector<float> fvec1D;
typedef std::vector<std::vector<float> > fvec2D;
...
private:
fvec2D null2D {{0.0}};
fvec1D null1D {0.0};
fvec2D &outVar2D;// = null2D; // tried this and at ctor
fvec1D &outVar1D;// = null1D;
std::vector<std::unique_ptr<chem> > chemList;
};
model::model() : outVar2D(null2D), outVar1D(null1D)
{
outVar2D = chemList[0]->getConc(); // or
outVar1D = chemList[0]->getConc(1);
}
void model::plot()
{
for (int z=0; z<numZSteps; ++z) {
std::cout << outVar1D[z];
std::cout << outVar2D[1][z];
}
}
void model::run()
{
plot(); // produces init concentration of 1.5 at each z
chemList[0]->changeConc(); // Changes values in concentration
plot(); // STILL produces init conc of 1.5 at each z
}
I don't know if answering my own question is appropriate (please let me know). I know this question will be autodeleted, so I thought I'd present the solution I came up with, because I'm still VERY interested in hearing any suggestions of the best way to do this. I'm still so far down the learning curve I know I can't intuitively see c++ programming techniques.
I gathered from comments that what I was trying won't work, so I wrapped my vectors in shared_ptrs, which I know can work. I created some wrapper classes to manage 2 levels of shared_ptr (one for the multidimensional spatial data, and one for the list of output variables). It also keeps the array-type indexing intact as well as defines behavior for operator=.
I have only included the 2D classes here. I have 4 similar classes to handle the 1D and 3D cases as well.
I know what I'm posting is not great. it's not very elegant, requiring 2 classes for each dimensional case (1D, 2D, 3D data). Perhaps I can simplify it using templates. I've only written very elementary templates so far. Since each class decays (using operator[]) to a unique class I'm not sure if a template will help.
I haven't figured out all the const keyword placements yet - I removed them all for now, out of frustration with the compiler complaints. I'll get that down when I can take the time.
I also don't know exactly what sort of behavior I want for copy and move constructors, though I'm pretty sure I need them for vector resize operations, which I just realized I haven't even implemented yet. The important thing for me here was just to get read access to the vectors across classes, such that when the vectors change it is reflected elsewhere without re-parsing my output variables.
#include <memory>
#include <vector>
namespace MDType {
class fpv2D;
typedef std::vector<float> fvec1D;
typedef std::vector<std::vector<float> > fvec2D;
typedef std::vector<std::vector<std::vector<float> > > fvec3D;
typedef std::shared_ptr<fvec1D> fvec1Dptr;
typedef std::shared_ptr<fvec2D> fvec2Dptr;
typedef std::shared_ptr<fvec3D> fvec3Dptr;
typedef std::vector<fpv2D> fvpv2D;
typedef std::shared_ptr<fvpv2D> fvpv2Dptr;
class fpv2D
{
public:
fpv2D(int x=1, int z=1, float fill=0.0) : theArray(new fvec2D(x, fvec1D(z, fill))) {}
fpv2D(const fpv2D &otherT) = default; // Pretty sure this needs to change
fpv2D( fpv2D &&otherT) {theArray = otherT.data(); }
fvec2Dptr &data() { return theArray; }
fvec1D &operator[](int index) {return theArray->data()[index]; }
void operator=( fpv2D& rhs) { theArray = rhs.data(); }
private:
fvec2Dptr theArray;
};
class fpvpv2D
{
public:
fpvpv2D(int index, int x=1, int z=1, float fill=0.0) : theArray(new fvpv2D(index, fpv2D(x, z, fill))) {}
fpvpv2D(const fpvpv2D &otherT) = default; // Pretty sure this needs to change
fpvpv2D( fpvpv2D &&otherT) {theArray = otherT.data(); }
fvpv2Dptr &data() { return theArray; }
fpv2D &operator[](int index) {return theArray->data()[index]; }
void operator=( fpvpv2D& rhs) { theArray = rhs.data(); }
private:
fvpv2Dptr theArray;
};
}
... so ...
MDType::fpv2D conc(numX, numZ, 1.5);
MDType::fpvpv2D outVar2D(numOutVars, numX, numZ);
outVar2D[1] = conc;
cout << outVar2D[1][3][5]; // prints 1.5
conc[3][5] = 12.0;
cout << outVar2D[1][3][5]; // prints 12.0

How to manipulate DLGTEMPLATE programmatically?

What?
I have a DLGTEMPLATE loaded from a resource DLL, how can I change the strings assigned to the controls at runtime programmatically?
I want to be able to do this before the dialog is created, such that I can tell that the strings on display came from the resource DLL, and not from calls to SetWindowText when the dialog is initialized.
Google has found examples of creating DLGTEMPLATE in code, or twiddling simple style bits but nothing on editing the strings in memory.
How?
I am doing this by hooking the Dialog/Property Sheet creation API's. Which gives me access to the DLGTEMPLATE before the actual dialog is created and before it has a HWND.
Why?
I want to be able to do runtime localization, and localization testing. I already have this implemented for loading string (including the MFC 7.0 wrapper), menus and accelerator tables, but I am struggling to handle dialog/property sheet creation.
Code examples would be the perfect answer, ideally a class to wrap around the DLGTEMPLATE, if I work out my own solution I will post it.
You can't edit the strings in memory. The DLGTEMPLATE structure is a direct file mapping of the relevent bytes of the resource dll. Thats read only.
You are going to need to process the entire DLGTEMPLATE structure and write out a new one with the altered length strings.
It will frankly be easier to just hook the WM_INITDIALOG and alter the strings by interacting with the controls than building a DLGTEMPLATE writer. Because there arn't a lot of those around. Unless you have an additional requirement to actually save altered dialog resources to disk as raw .res files (or attempt to modify the .dll inplace) Id really recommend you avoid this approach.
You say you are already doing this for accellerator tables and menu strings - if you can guarantee that the patched in strings are going to be shorter, then just make a binary copy of the DLGTEMPLATE struct, and write the non trivial scanning code necessary to find each string so you can patch the copy in place.
There is a file out there somewhere (which I think originated at Microsoft but I am not completely sure) called RESFMT.ZIP which explains this with some code examples. Raymond Chen also does some excellent explanations of this on his blog. Note that the format of DIALOGEX and DIALOG controls are different.
As noted in some other answers you would need to create the structure again from the start. This isn't all bad as you already have the basic information. Adding the controls is where is gets hard.
Basically, allocate a largish block of memory into a WORD *lpIn. Then add the structure up on top of that. adding the basic information for the DIALOG (see DLGTEMPLATE) and the controls is pretty obvious as the information is there in MSDN.
The two biggest problems you will encounter are: Making sure that the various part start on an alignment boundary, and interpreting the values of DIALOG controls, especially when to add a just a string or, a string or ordinal. Each control needs to start on an even boundary.
For the first (borrowed from somewhere I think RESFMT.ZIP):
WORD *AlignDwordPtr (WORD *lpIn)
{
ULONG ul;
ul = (ULONG) lpIn;
ul +=3;
ul >>=2;
ul
What I did was build a series of functions like this one following that allowed me to assemble DIALOGS in memory. (My need was so I could have some common code that didn't need an associated RC file for some very basic messages).
Here is an example...
WORD *AddStringOrOrdinalToWordMem( WORD *lpw, char *sz_Or_Ord )
{
LPWSTR lpwsz;
int BufferSize;
if (sz_Or_Ord == NULL)
{
*lpw++ = 0;
}
else
{
if (HIWORD(sz_Or_Ord) == 0) //MAKEINTRESOURCE macro
{
*lpw++ = 0xFFFF;
*lpw++ = LOWORD(sz_Or_Ord);
}
else
{
if (strlen(sz_Or_Ord))
{
lpwsz = ( LPWSTR ) lpw;
BufferSize = MultiByteToWideChar( CP_ACP, 0, sz_Or_Ord, -1, lpwsz, 0 );
MultiByteToWideChar( CP_ACP, 0, sz_Or_Ord, -1, lpwsz, BufferSize );
lpw = lpw + BufferSize;
}
else
{
*lpw++ = 0;
}
}
}
return( lpw );
}
The header file to the complete module included these functions:
WORD *AddControlToDialogTemplateEx(MTDialogTemplateType *dlgtmp,
char *Title,
WORD Id,
char *WinClass,
DWORD Style,
short x,
short y,
short cx,
short cy,
DWORD ExStyle,
int HelpID);
int DestroyDlgTemplateEx(MTDialogTemplateType *dlgtmp);
MTDialogTemplateType *CreateDlgTemplateEx( char *Name, // We use name just for reference, so it can be NULL
short x,
short y,
short cx,
short cy,
DWORD ExtendedStyle,
DWORD Style,
char *Menu,
char *WinClass,
char *Caption,
char *FontTypeFace,
int FontSize,
int FontWeigth,
int FontItalic,
int Charset,
int HelpID,
int NumberOfControls);
Which allowed me to assemble whole dialogs easily from code.
See the API function ::EnumChildWindows( HWND, WNDENUMPROC, LPARAM )
You can call this in a CFormView::Create or CDialog::OnInitDialog to give yourself a chance to replace the control captions. Don't worry, the old strings don't flicker up before you replace them.
In your dialog resource, set the control captions to a key in some kind of dictionary. If you're compiling /clr you can use a managed string table resource. In your callback, look up the translated string in your dictionary and set the control's caption to the translation. Another benefit of /clr and managed string table is that you can automatically look up the right language by Windows (or you) having already set System::Threading::Thread::CurrentThread->CurrentUICulture.
Something like this
CMyDialog::OnInitDialog()
{
::EnumChildWindows(
this->GetSafeHwnd(),
CMyDialog::UpdateControlText,
(LPARAM)this )
}
BOOL CALLBACK CMyDialog::UpdateControlText( HWND hWnd, LPARAM lParam )
{
CMyDialog* pDialog = (CMyDialog*)lParam;
CWnd* pChildWnd = CWnd::FromHandle( hWnd );
int ctrlId = pChildWnd->GetDlgCtrlID();
if (ctrlId)
{
CString curWindowText;
pChildWnd->GetWindowText( curWindowText );
if (!curWindowText.IsEmpty())
{
CString newWindowText = // some look up
pChildWnd->SetWindowText( newWindowText );
}
}
}
You'll have to locate the string you want to modify in the mem buffer that represents the template. The only way to do that is to traverse the whole template. Which is not easy.
Once you've done that, either insert bytes in the buffer if your new string is longer than the original one. Or shrink the buffer if the new string is shorter.
As Chris wrote, it would be much easier to modify the text in WM_INITDIALOG and try to re-phrase you requirement that says you may not call SetWindowText().
Thanks all, I actually had 24 hours rest on the problem, then went with a global windows hook filtering WM_INITDIALOG which was a much simpler method, worked out just fine, no API hooking required, 2 pages of code down to just a few lines.
Thanks for all the answers.

Resources