Does ShellExecuteW(...) work only once in MetaTrader 4 or not? - algorithmic-trading

Trying to launch an .exe from MQL4 using ShellExecuteW().
Does this command work only once, or not?
#import "shell32.dll" // MQL4-syntax-wrapper-Bo[#import]Container
// v-------------- caller-side interface to DLL
int ShellExecuteW( int hWnd,
int lpVerb,
string lpFile,
int lpParameters,
int lpDirectory,
int nCmdShow
);
#import // MQL4-syntax-wrapper-Eo[#import]Container
if ( cond == true ){
ShellExecuteW( 0, "open", "D:\\Execute.exe", "", "", 1 );
}

A: a short version
Maybe yes, maybe no.
A: a bit more indepth one [TLDR]
Fact:
MT4 Terminal's process-control / process-management is nothing superior, however it allows you to integrate several lines of control over what happens inside ( and outside ... not only via ShellExecuteW(...) ... ) the MT4 Terminal.
MT4 Terminal supports the following processes per graph ( via built-in threads ):
{ 0 | 1 } occurences of a singleton instance called MQL4-ExpertAdvisor
{ 0 | 1 } occurences of a singleton instance called MQL4-Script
{ 0 | 1 ... n } occurences of a functionally restricted instance called MQL4-TechnicalIndicator
The nature of these instances differs in several ways, however in the closest relation to your question, each of the processes have both a mandatory part and a set of arbitrary parts.
Speaking in the original MQL4 ( one may have noticed, that since Build 7xx MQL4 language syntax has moved closer and closer towards MQL5, thus sometimes got labeled as MQL4.5 :o) )
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
//
// MQL4 code ----------------------------------------------------------<BoF>------
// MQL4 code compiler directives' section -----------------------<BoS>
#import ... // MQL4-syntax-wrapper-Bo[#import]Container
..
.
#import // MQL4-syntax-wrapper-Eo[#import]Container
// MQL4 code compiler directives' section -----------------------<EoS>
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
//
// MQL4 code section ---------------------------- init() / start() / deinit()
//
int init(){ // this part is being run just once,
// right upon an instance activation
}
int start(){ // this part is being run just once, for an MQL4-Script
// right upon an instance activation
// run upon an FX-MarketEvent is being observed
// in an MQL4-ExpertAdvisor
// or
// in an MQL4-TechnicalIndicator
}
...
..
.
//
// MQL4 code ---------------------------------------------------------<EoF>------
//
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
So, the exact location of your deployment code, that (re-)uses the generic DLL-service ( #import-ed for both the compile-time alignment and the dynamic linking upon (re-use) decides how many times the external process has been asked to get invoked.
Nota Bene
There are much smarter ways to integrate MT4 Terminal with external processes or remote processes ( Clouds & Grids ) than just a DLL-based spawn of just another blind & deaf unmanageable <localhost> process.
Typically one needs both process-control and bidirectional communication between / among processes.
Do not hesitate to ask more.
MT4 ( with some additional tools ) can do.

Related

How can flex return multiple terminals at one time

In order to make my question easy to understand I want to use the following example:
The following code is called nonblock do-loop in fortran language
DO 20 I=1, N ! line 1
DO 20 J=1, N ! line 2
! more codes
20 CONTINUE ! line 4
Pay attention that the label 20 at line 4 means the end of both the inner do-loop and the outer do-loop.
I want my flex program to parse the feature correctly: when flex reads the label 20, it will return ENDDO terminal twice.
Firstly, because I also use bison, so every time bison calls yylex() to get one terminal. If I can ask bison to get terminals from yylex() in some cases, and from another function in other cases, maybe I could solve this problem, however, I got no idea here then.
Of course there are some workarounds, for eample, I can use flex's start condition but I don't think it is a good solution. So I ask if there's any way to solve my question without a workaround?
It is easy enough to modify the lexical scanner produced by (f)lex to implement a token queue, but that is not necessarily the optimal solution. (See below for a better solution.) (Also, it is really not clear to me that for your particular problem, fabricating the extra token in the lexer is truly appropriate.)
The general approach is to insert code at the top of the yylex function, which you can do by placing the code immediately after the %% line and before the first rule. (The code must be indented so that it is not interpreted as a rule.) For non-reentrant scanners, this will typically involve the use of a local static variable to hold the queue. For a simple but dumb example, using the C API but compiling with C++ so as to have access to the C++ standard library:
%%
/* This code will be executed each time `yylex` is called, before
* any generated code. It may include declarations, even if compiled
* with C89.
*/
static std::deque<int> tokenq;
if (!tokenq.empty()) {
int token = tokenq.front();
tokenq.pop_front();
return token;
}
[[:digit:]]+ { /* match a number and return that many HELLO tokens */
int n = atoi(yytext);
for (int i = 0; i < n; ++i)
tokenq.push_back(HELLO);
}
The above code makes no attempt to provide a semantic value for the queued tokens; you could achieve that using something like a std::queue<std::pair<int, YYSTYPE>> for the token queue, but the fact that YYSTYPE is typically a union will make for some complications. Also, if that were the only reason to use the token queue, it is obvious that it could be replaced with a simple counter, which would be much more efficient. See, for example, this answer which does something vaguely similar to your question (and take note of the suggestions in Note 1 of that answer).
Better alternative: Use a push parser
Although the token queue solution is attractive and simple, it is rarely the best solution. In most cases, code will be clearer and easier to write if you request bison to produce a "push parser". With a push parser, the parser is called by the lexer every time a token is available. This makes it trivial to return multiple tokens from a lexer action; you just call the parser for each token. Similarly, if a rule doesn't produce any tokens, it simply fails to call the parser. In this model, the only lexer action which actually returns is the <<EOF>> rule, and it only does so after calling the parser with the END token to indicate that parsing is complete.
Unfortunately, the interface for push parsers is not only subject to change, as that manual link indicates; it is also very badly documented. So here is a simple but complete example which shows how it is done.
The push parser keeps its state in a yypstate structure, which needs to be passed to the parser on each call. Since the lexer is called only once for each input file, it is reasonable for the lexer to own that structure, which can be done as above with a local static variable [Note 1]: the parser state is initialized when yylex is called, and the EOF rule deletes the parser state in order to reclaim whatever memory it is using.
It is usually most convenient to build a reentrant push parser, which means that the parser does not rely on the global yylval variable [Note 2]. Instead, a pointer to the semantic value must be provided as an additional argument to yypush_parse. If your parser doesn't refer to the semantic value for the particular token type, you can provide NULL for this argument. Or, as in the code below, you can use a local semantic value variable in the lexer. It is not necessary that every call to the push parser provide the same pointer. In all, the changes to the scanner definition are minimal:
%%
/* Initialize a parser state object */
yypstate* pstate = yypstate_new();
/* A semantic value which can be sent to the parser on each call */
YYSTYPE yylval;
/* Some example scanner actions */
"keyword" { /* Simple keyword which just sends a value-less token */
yypush_parse(pstate, TK_KEYWORD, NULL); /* See Note 3 */
}
[[:digit:]]+ { /* Token with a semantic value */
yylval.num = atoi(yytext);
yypush_parse(pstate, TK_NUMBER, &yylval);
}
"dice-roll" { /* sends three random numbers */
for (int i = 0; i < 2; ++i) {
yylval.num = rand() % 6;
yypush_parse(pstate, TK_NUMBER, &yylval);
}
<<EOF>> { /* Obligatory EOF rule */
/* Send the parser the end token (0) */
int status = yypush_parse(pstate, 0, NULL);
/* Free the pstate */
yypstate_delete(pstate);
/* return the parser status; 0 is success */
return status;
}
In the parser, not much needs to be changed at all, other than adding the necessary declarations: [Note 4]
%define api.pure full
%define api.push-pull push
Notes
If you were building a reentrant lexer as well, you would use the extra data section of the lexer state object instead of static variables.
If you are using location objects in your parser to track source code locations, this also applies to yylloc.
The example code does not do a good job of detecting errors, since it doesn't check return codes from the calls to yypush_parse. One solution I commonly use is some variant on the macro SEND:
#define SEND(token) do { \
int status = yypush_parse(pstate, token, &yylval); \
if (status != YYPUSH_MORE) { \
yypstate_delete(pstate); \
return status; \
} \
} while (0)
It's also possible to use a goto to avoid the multiple instances of the yypstate_delete and return. YMMV.
You may have to modify the prototype of yyerror. If you are using locations and/or providing extra parameters to the push_parser, the location object and/or the extra parameters will also be present in the yyerror call. (The error string is always the last parameter.) For whatever reason, the parser state object is not provided to yyerror, which means that the yyerror function no longer has access to variables such as yych, which are now members of the yypstate structure rather than being global variables, so if you use these variables in your error reporting (which is not really recommended practice), then you will have to find an alternative solution.
Thanks to one of my friends, he provide a way to achieve
If I can ask bison to get terminals from yylex() in some cases, and from another function in other cases
In flex generated flex.cpp code, there is a macro
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
so I can "rename" flex's yylex() function to another function like pure_yylex().
So my problem is solved by:
push all terminals I want to give bison to a global vector<int>
implement a yylex() function by myself, when bison call yylex(), this function will firstly try to get terminals from a that global vector<int>
if vector<int> is empty, yylex() calls pure_yylex(), and flex starts to work

How to setup a period of time in an MQL4 source code?

I am using MQL4.
Currently, I am using [Expert Advisor]-s in MT4.StrategyTester, and set a period-of-time by the build-in pull-down calendar GUI-elements.
What I want to do is to setup a period-of-time straight in an MQL4-source code.
If it is realized, for example, I can compare the result
'from 2011/01-to 2011/12'
to
'from 2012/01-to 2012/12'
and so on.
There is an easy solution to the requirement, even with an added value for a fully automated, large-scale hyper-parameter optimisations inside the said MT4.StrategyTester tool, using the proposed pair of parameters ( aStartFromDATE and aRunTillDATE ) as an iterable tuple, that could be harnessed into a TradingStrategy robustness cross-validations of its release-candidates over some sweeping/sliding calendar window-of-time.
extern datetime aStartFromDATE = D'2010.01.01 00:00';
extern datetime aRunTillDATE = D'2345.01.01 00:00';
void OnTick(){
if ( Time < aStartFromDATE
|| Time > aRunTillDATE
){
IgnoreTicksOutsideTheGivenPeriodOfTime();
return;
}
// SURE TO BE INSIDE THE GIVEN ( MT4.STRATEGY/TESTER ITERABLE ) PERIOD OF TIME
...
..
.
}
void IgnoreTicksOutsideTheGivenPeriodOfTime(){
// Ignore, but still may do execute some utility service during a void run
}
Be careful on different scopes of syntax support:
One might be also cautious on use-cases, that include StrategyTester restrictions for some of the powerful new-syntax-constructors:
A PrintFormat() being one of such un-supported pieces inside the StrategyTester during hyper-parameter optimisations.
PrintFormat() function does not work during optimization in the Strategy Tester.

How to disable autotrading globally from MQL4/5 program (EA) without DLLs?

How do I disable autotrading globally in MetaTrader 4/5 from within MQL4/5 code without using DLLs?
Here you go, (Author is Tiago Praxedes)
#define MT_WMCMD_EXPERTS 32851
#define WM_COMMAND 0x0111
#define GA_ROOT 2
#include <WinAPI\winapi.mqh>
void SetAlgoTradingStatus(bool Enable)
{
bool Status = (bool) TerminalInfoInteger(TERMINAL_TRADE_ALLOWED);
if(Enable != Status)
{
HANDLE hChart = (HANDLE) ChartGetInteger(ChartID(), CHART_WINDOW_HANDLE);
PostMessageW(GetAncestor(hChart, GA_ROOT), WM_COMMAND, MT_WMCMD_EXPERTS, 0);
}
}
void OnTick()
{
SetAlgoTradingStatus(false);
}
Lifted it from here: Source
Yes, MQL4/5 Expert Adviser may locally forbid self to trade this way:
if ( IsTradeAllowed() )
{ Comment( __FILE__, " [EA] Trading is allowed, will disable self." );
...
}
else
{ Comment( __FILE__, " [EA] Trading is not allowed, will disable self." );
...
}
// ---------------------------------------// GRACEFULLY RELEASE ALL RESOURCES BEFORE FIN'd
// ********
// FINALLY: EXPERT-ADVISOR SIG_TERM -> self ( MT4 )
ExpertRemove(); /* MT4 The Expert Advisor
is not stopped immediately
as you call ExpertRemove();
just a flag to stop the EA operation is set.
That is:
- any next event won't be processed,
- OnDeinit() will be called
and
- the Expert Advisor will be unloaded and removed from the chart.
*/
If the idea is that you have several EA's on different pairs and you want to disable them all at the same time you could place a specific trade, that I would call an information trade and not meant to be used for trading.
Choose a price very far away from current price.
For this example, we can use 9,999.000 as price and we place the trade.
Loop through the trades and look for a price = 9999.
If you find it use that to disable trading.
If you want it to start again, you can have a button or manually delete that trade that is 9999.
Now the block is not there.
All the EA's you may have going can see this.
Also, an offsite computer will be able to see it as well.
This was used as a way to hand off trading control to a team of traders.
The new owner would send the trade that bumps everyone off.
Remove that trade but the other EA's are asleep until a human turns them back on or a "Wake Up" trade is sent.
You can send values in the Comment, TP and SL values as prices.
There are many ways to use this method.
For this to work though you would have to have your own code and make the changes. If you buy an EA and want to turn it on and off without the source code then this method won't work.

Solving tcsncpy_s.inl assertion (line 24)

I've a fairly simple program which needs user input in the form of a text string. I've a CLR form with an edit box and I need to take that input and pass it into my class which just copies it to a member variable.
In the Form.h code, handling the TextChanged event is...
int textLength = m_userDest->TextLength;
if (textLength > 2 && textLength < 5)
{
// Could be an ICAO code in here
char dest[5];
String^ text = m_userDest->Text->ToUpper();
sprintf_s(dest, 5, "%s", text);
airTraffic.SetUserDest(dest);
}
My class (airTraffic) SetUserDest function is just
void CAirTraffic::SetUserDest(char* dest)
{
strncpy_s(m_userDest, 5, dest, 5);
}
When this is run I get this debug assertion, it doesn't stay on the screen and automatically clears after a few seconds.
Debug Assertion Failed!
Program: ...sual Studio 2010\Projects\FSAirTraffic\Debug\FSAirTraffic.exe
File: f:\dd\vctools\crt_bld\self_x86\crt\tcsncpy_s.inl
Line: 24
Expression: ((_Dst)) != NULL && ((_SizeInBytes)) > 0
I don't have an f:\ drive so I'm guessing this is some internal Microsoft(?) code so I can't see the context of the assertion and exactly what it's problem is. I don't have a file called tcsncpy_s.inl on my machine.
If I don't call my class function then there's no assertion so I assumed that was the problem.
Curiously though, when stepping through the debugger the assertion occurs as I step out of the TextChanged event, with the rest of the functions operating as intended (as far as I can see).
Does anyone know what the problem is and how I can go about solving it?
I don't understand how your code works. You use m_userDest twice, first it appears to be a pointer to a structure of some sort, maybe a handle to a TextBox control:
int textLength = m_userDest->TextLength;
Later you pass it to strncpy_s, which needs a char*, not a pointer to some structure.
void CAirTraffic::SetUserDest(char* dest)
{
strncpy_s(m_userDest, 5, dest, 5);
}
While it's possible for a structure to implicitly convert to a char*, it's not possible for a structure pointer to do so. Perhaps there's a smart pointer involved? Or you are using the same member variable name for completely different purposes in different classes1?
In any case, strncpy_s is inspecting the value of its first argument and not liking it.
1 Note that the new "wisdom" saying not to use Hungarian notation has destroyed the ability to understand this code in textual form. We don't have an IDE providing mouseover information about the data type of variables. Applications Hungarian is still a good idea in the real world, despite how many "best practices" documents decry it. Amazing how many code style documents are written from a purely theoretical basis.

Add a mathematical operation to standard TCL ones

As you know TCL has some mathematical functions such as sin, cos, and hypot that are called in expr command with () braces as follows:
puts [expr sin(1.57)]
Now how can I add a function using TCL library functions so that it was called exactly the same way, and was doing something that a certain proc defines.
I would like to clarify my question. Say there is a proc (string) as follows:
proc add { a b } { return [expr $a+$b] } ;# string of a proc
Also I have a TCL interpreter in my C++ code. Now I want get the string of a proc and runtime register a function called add into the tcl::mathfunc namespace (I guess I should use Tcl_CreateObjCommand) so that I could call the following:
puts [expr add(1.57, 1.43)]
How this can be done. Could you please write a simple example. I could not find any example in TCL documentation and in books as well which describe the usage of this command.
Creating a function from C isn't too hard. To do it, you've got to write an implementation of a command that will perform the operation, and register that implementation as a command in the correct namespace. (In 8.4 and before, functions were done with a separate interface that was quite a bit nastier to use; the mechanism was wholly overhauled in 8.5.)
Command Implementation
Note that the signature is defined, and the ignored parameter is not used here. (It's really a void * — great when you're wanting to do things like binding a command to an object — but it simply isn't needed for doing an addition.)
static int AddCmd(ClientData ignored, Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]) {
double x, y, sum;
/* First, check number of arguments: command name is objv[0] always */
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "x y");
return TCL_ERROR;
}
/* Get our arguments as doubles */
if ( Tcl_GetDoubleFromObj(interp, objv[1], &x) != TCL_OK ||
Tcl_GetDoubleFromObj(interp, objv[2], &y) != TCL_OK) {
return TCL_ERROR;
}
/* Do the real operation */
sum = x + y;
/* Pass the result out */
Tcl_SetObjResult(interp, Tcl_NewDoubleObj(sum));
return TCL_OK;
}
Don't worry about the fact that it's allocating a value here; Tcl's got a very high performance custom memory manager that makes that a cheap operation.
Command Registration
This is done usually inside an initialization function that is registered as part of a Tcl package definition or which is called as part of initialization of the overall application. You can also do it directly if you are calling Tcl_CreateInterp manually. Which you do depends on how exactly how you are integrating with Tcl, and that's quite a large topic of its own. So I'll show how to create an initialization function; that's usually a good start in all scenarios.
int Add_Init(Tcl_Interp *interp) {
/* Use the fully-qualified name */
Tcl_CreateObjCommand(interp, "::tcl::mathfunc::add", AddCmd, NULL, NULL);
return TCL_OK;
}
The first NULL is the value that gets passed through as the first (ClientData) parameter to the implementation. The second is a callback to dispose of the ClientData (or NULL if it needs no action, as here).
Doing all this from C++ is also quite practical, but remember that Tcl is a C library, so they have to be functions (not methods, not without an adapter) and they need C linkage.
To get the body of a procedure from C (or C++), by far the easiest mechanism is to use Tcl_Eval to run a simple script to run info body theCmdName. Procedure implementations are very complex indeed, so the interface to them is purely at the script level (unless you actually entangle yourself far more with Tcl than is really wise).

Resources