How to store AccountBalance() into a variable? - mql4

if(Total_sell_pos() == 0 && Total_buy_pos() == 0) {
double previous_balance = AccountBalance(); //usd1000
}
if (AccountEquity() > previous_balance + (previous_balance *0.05)){ //usd1000 + 50 = usd1050
CloseSellOrders();
CloseBuyOrders();
Delete_Pendings();
}
if Equity more than usd1050 then delete pending and orders.
But why when run the code, it keep delete pending and orders immediately even when Equity is less than previous balance?
The following code is the problem, and I replace it :
AccountEquity() > previous_balance + (previous_balance *0.05)
with
AccountEquity() > 1050
then only it works. I did try to check the value :
double check_value = previous_balance + (previous_balance *0.05);
printf (check_value); //1050
May I know why I cannot use the following code?
AccountEquity() > previous_balance + (previous_balance *0.05)

Q: How to store AccountBalance() into a variable?
Let's start with the variable - declare it:
double aPreviousBALANCE;
The scope-of-declaration is driven by the enclosing code-block boundaries. MQL4/5 can declare a variable on the "global"-scope, that may become visible from inside other code-blocks, but if any such has a variable name identical to the "global"-scope defined one, the locally declared ( explicitly in the code, or introduced from the function-parameters' declaration in the call-signature specification ) will "shade-off" the access to the variable declared on the "global"-scope. This you have to check in the original code and MQL4/5-IDE may warn you about such collision(s) during the compilation ( ref. Compiler Warning Messages ).
Let's store in it the actual state, we'll have more steps here:
RefreshRates(); // Force a state-update
aPreviousBALANCE = AccountInfoDouble( ACCOUNT_BALANCE ); // Store an updated value
Q: May I know why I cannot use the following code?
Well, any language, MQL4/5 not being an exception, has some order of execution of mathematical operators. MQL4 need not and does not have the warranty about using the same one as any other language we may have had some prior experience. So, always be rather explicit in this a specify all ordering via explicit parentheses, this will save you any further "surprises" when the language parser / compiler will suddenly change the priority of operators and sudden nightmares will appear. Not worth a single such shock to ever happen:
if ( ( ( a * b ) + c ) < fun() ) // is EXPLICIT and a way safer, than
if ( a * b + c < fun() ) // is DEPENDENT on not having {now|in future}
// a binary boolean (<)-operator
// a higher priority than (+)-op
so, rather be always explicit and you remain on the safer side.
Finally, test:
RefreshRates(); // Force a state-update
if ( ( aPreviousBALANCE * 1.05 ) < AccountInfoDouble( ACCOUNT_EQUITY ) )
{
...
}
Also check, how are your settings pre-set from the Broker-side - they run a Support-Line for you to ask about their settings:
Equity calculation depends on trading server settings.
Print( "Profit calculation mode for SYMBOL[ ",
Symbol(),
" ] is ",
MarketInfo( Symbol(), MODE_PROFITCALCMODE ),
" { 0: mode-FOREX, 1: mode-CFD, 2: mode-FUTURES }."
);
And where is my AccountBalance() function?
Recent Terminal Builds use a set of new types of calls to:
AccountInfo{Integer|
Double|
String}( <anEnumDrivenItemIDENTIFIER>
)
SymbolInfo{Integer|
Double|
String}( <aSymbolNAME>,
<anEnumDrivenItemIDENTIFIER>
)
to name just a few, so re-read the documentation to adopt the most recent changes. Always. ALAP when your Terminal has got a new Build updated ( might be seen when loading a new version of Help files for the MQL4-IDE and/or Terminal ).
Well, this happens. MQL4 evolves and some features we were used to for ages cease to exist, start to suddenly yield inaccurate or indefinite result or change its behaviour ( ol' MQL4-ers still remember the day, when string data type simply ceased to be a string in silence and suddenly started to become a struct. Ok, it was mentioned somewhere deep inside an almost unrelated page of an updated Help-file, yet the code-crashes were painful and long to debug, analyze and re-factor )

Related

Differentiating Mode 2 Form 1 from Mode 2 Form 2 on XA CD-ROMs?

I'm developing a library for reading CD-ROMs and the ISO9660 file system.
Long story short, pretty much everything is working except for one thing I'm having a hard time figuring out how it's done:
Where does XA standard defines differentiation among Mode 2 Form 1 from Mode 2 Form 2?
Currently, I am using the following pseudo-code to differentiate between both forms; albeit it's a naive heuristic, it does work but well, it's far from ideal:
var buffer = ... // this is a raw sector of 2352 bytes
var m2F1 = ISector.Cast<SectorMode2Form1>(buffer);
var edc1 = EdcHelper.ComputeBlock(0, buffer, 16, 2056);
var edc2 = BitConverter.ToUInt32(m2F1.Edc, 0);
var isM2F1 = edc1 == edc2;
if (isM2F1) return CdRomSectorMode.Mode2Form1;
// NOTE we cannot reliably check EDC of M2F2 since it's optional
var isForm2 =
m2F1.SubHeaderCopy1.SubMode.HasFlag(SectorMode2Form1SubHeaderSubMode.Form2) &&
m2F1.SubHeaderCopy2.SubMode.HasFlag(SectorMode2Form1SubHeaderSubMode.Form2);
if (isForm2) return CdRomSectorMode.Mode2Form2;
return CdRomSectorMode.Mode2Formless;
If you look at some software like IsoBuster, it appears to be a track-level property, however, I'm failing to understand where the value would be read from within the track.
I'm actually doing something similar in typescript for my ps1 mod tools. It seems like you actually probably have it correct here, since I'm going to assume your HasFlag check is checking position bit position 6 of the subheader. If that flag is set, you are in form 2.
So what you probably want something like:
const sectorBytes = new Uint8Arrray(buffer);
if (sectorBytes[0x012] & 0x20) === 0x20) {
return CdRomSectorMode.Mode2Form2;
} else {
return CdRomSectorMode.Mode2Form1;
}
You could of course use the flag code you already have, but that would require you to use one of the types first to get that. This just keeps it generic bytes and checks the flag, then returns the relevant mode.

Change request.comment-value?

I use different kinds of stop losses and would like to be notified (SendNotification()) about which kind of stop loss was hit upon trade exit.
Let's say I entered a trade by...
request.action = TRADE_ACTION_DEAL;
request.symbol = pSymbol;
request.type = pType;
request.sl = pStop;
request.tp = pProfit;
request.comment = pComment;
request.volume = pVolume;
request.price = SymbolInfoDouble(pSymbol,SYMBOL_ASK);
request.price = SymbolInfoDouble(pSymbol,SYMBOL_BID)
OrderSend(request,result);
I would now like to have the request.comment changed by the last stop loss like so:
request.action = TRADE_ACTION_SLTP;
request.symbol = pSymbol;
request.sl = pStop;
request.tp = pProfit;
request.comment = "Fixed SL";
PositionSelect(_Symbol);
request.order = PositionGetInteger(POSITION_IDENTIFIER);
OrderSend(request,result);
Unfortunately the second block of code does not change the first request.comment = pComment; though (instead the new comment is [sl 1.19724]).
Is it possible to change the comment via TRADE_ACTION_SLTP? What am I doing wrong?
Thank you!
I would now like to have the request.comment changed
There was never a way to do this in MQL4/5 trading platforms
Sad, but true.
The core-functionality was always focused on engineering a fast, reliable soft-real-time ( providing still just a best-effort scheduling alongside the stream of externally injected FxMarket-Event-Flow ), so bear with the product as-is.
Plus, there was always one more degree-of-uncertainty, the Broker-side automation was almost free for modifying the .comment-part of the Trade-position, so even if your OrderSend() was explicit on what ought be stored there, the result was unsure and the Broker-side could ( whenever, be it immediately or at any later stage ) change this field outside of any control ( which was not left on your side ), so the only semi-UUID# keys could have been placed into the .magic ( and your local-side application code always had to do all the job via some key:value storage extension to the otherwise uncertain Broker-side content.
Even the Trade number ( ID, ticket ) identifier is not always a persistent key and may change under some Trade management operations, so be indeed very carefull, before deciding your way.
like to be notified ( SendNotification() ) about which kind of stop loss was hit upon trade exit.
Doable, yet one will need to build all the middleware-logic on one's own :
The wish is clear and doable. Given a proper layer of middleware-logic will get built, one can enjoy whatever such automation.
Having built things like an augmented-visual-trading, remote AI/ML-quant-predictors or real-time fully-adaptive non-blocking GUI-quant-tools augmentations ( your trader gets online graphical visual aids inside GUI, automatically overlaid over other EA + Indicator tools on the GUI-surface, fully click-and-modify interactive / adaptive for fast visually augmented discretionary modifications of the traded asset management ), so only one's imagination and resources available are one's limit here.
Yet, one has to respect the published platform limits - the same as OrderModify() does not provide any means for the wish above, the add-on traded assets customer-specific reporting on position terminations is to be assembled by one's own initiative, as the platform does not provide ( for obvious reasons noted above ) any tools, relevant for such non-core activity.

readByteSync - is this behavior correct?

stdin.readByteSync has recently been added to Dart.
Using stdin.readByteSync for data entry, I am attempting to allow a default value and if an entry is made by the operator, to clear the default value. If no entry is made and just enter is pressed, then the default is used.
What appears to be happening however is that no terminal output is sent to the terminal until a newline character is entered. Therefore when I do a print() or a stdout.write(), it is delayed until newline is entered.
Therefore, when operator enters first character to override default, the default is not cleared. IE. The default is "abc", data entered is "xx", however "xxc" is showing on screen after entry of "xx". The "problem" appears to be that no "writes" to the terminal are sent until newline is entered.
While I can find an alternative way of doing this, I would like to know if this is the way readByteSync should or must work. If so, I’ll find an alternative way of doing what I want.
// Example program //
import 'dart:io';
void main () {
int iInput;
List<int> lCharCodes = [];
print(""); print("");
String sDefault = "abc";
stdout.write ("Enter data : $sDefault\b\b\b");
while (iInput != 10) { // wait for newline
iInput = stdin.readByteSync();
if (iInput == 8 && lCharCodes.length > 0) { // bs
lCharCodes.removeLast();
} else if (iInput > 31) { // ascii printable char
lCharCodes.add(iInput);
if (lCharCodes.length == 1)
stdout.write (" \b\b\b\b chars cleared"); // clear line
print ("\nlCharCodes length = ${lCharCodes.length}");
}
}
print ("\nData entered = ${new String.fromCharCodes(lCharCodes).trim()}");
}
Results on Command screen are :
c:\Users\Brian\dart-dev1\test\bin>dart testsync001.dart
Enter data : xxc
chars cleared
lCharCodes length = 1
lCharCodes length = 2
Data entered = xx
c:\Users\Brian\dart-dev1\test\bin>
I recently added stdin.readByteSync and readLineSync, to easier create small scrips reading the stdin. However, two things are still missing, for this to be feature-complete.
1) Line mode vs Raw mode. This is basically what you are asking for, a way to get a char as soon as it's printed.
2) Echo on/off. This mode is useful for e.g. typing in passwords, so you can disable the default echo of the characters.
I hope to be able to implement and land these features rather soon.
You can star this bug to track the development of it!
This is common behavior for consoles. Try to flush the output with stdout.flush().
Edit: my mistake. I looked at a very old revision (dartlang-test). The current API does not provide any means to flush stdout. Feel free to file a bug.

Need Lua Help. attempt to index field 'Config' (a nil value) Gmod13

Having this error when I run my gamemode.
[ERROR]
gamemodes/rp/gamemode/cl_init.lua:910: attempt to index field 'Config' (a nil value)
1. unknown - gamemodes/rp/gamemode/cl_init.lua:910
config is a table, with index's such as config["Run Speed"] and the entire table is set globally equal to GM.Config in the sh_config.lua file. Why is config not being registered as a value? Must I include the config file into the cl_init file? and if so, how? Using the include()?
function GM:Think()
if ( self.Config["Local Voice"] ) then **--Referred line(910)**
for k, v in pairs( player.GetAll() ) do
if ( hook.Call("PlayerCanVoice",GAMEMODE, v) ) then
if ( v:IsMuted() ) then v:SetMuted(); end
else
if ( !v:IsMuted() ) then v:SetMuted(); end
end
end
end
-- Call the base class function.
return self.BaseClass:Think();
end
Edit -- config table in sh_config.lua.
local config = {};
-- Command
config["Command Prefix"] = "/"; -- The prefix that is used for chat commands.
config["Maximum Notes"] = 2; -- Maximum notes per player
config["Advert Cost"] = 60; -- The money that it costs to advertise.
config["Advert Timeout"] = 150 -- How many seconds between adverts
config["OOC Timeout"] = 60 -- How many seconds between OOC messages
config["Item Timer"] = 7 -- How many seconds between item uses
config["Item Timer (S)"] = 20 -- How many seconds between specific item uses
config["Note Fade Speed"] = 12 -- How many minutes before nots disappear
-- Voice
config["Local Voice"] = true; -- Players can only hear a player's voice if they are near them. This is the index being called which is creating an error.
config["Talk Radius"] = 256; -- The radius of each player that
--other players have to be in to hear them talk (units).
-- Player Stuff
config["Walk Speed"] = 150; -- The speed that players walk at.
config["Run Speed"] = 275; -- The speed that players run at.
GM.Config = config;
I have includecs("sh_config.lua"); in sh_init.lua. include("sh_config.lua") and AddCSLuaFile("sh_config.lua") in init.lua. and include("sh_config.lua"); in cl_init.lua.
Im still getting this stupid error though. Can someone explain what the difference between including and Addcs'ing a file does. How do I make sh_config's variables global in other files? Or in other words how do I make the desired file(cl_init) read through the code in sh_config.lua and I can use code from it in the client side init?
You need to include sh_config.lua at the top of cl_init.lua.
include("path/to/file.lua")
Be sure to do AddCSLuaFile("path/to/lua.lua") in the init.lua file as well. You will also need to do include("path/to/file.lua") in init.lua as well. (That's only required for shared files, though)
Also I am pretty sure the scope of your config table would be limited to sh_config.lua so you should remove local from your variable declaration.
*sh_config* is a shared file - Meaning it'll have to be included both clientside, and serverside.
In init.lua - In top of the other includes. Put include("sh_config.lua")
Also in init.lua, put AddCSLuaFile("sh_config.lua") - This will make sure the file is downloaded by the client, and executed clientside.
In cl_init.lua - put include("sh_config.lua"). Also around the other includes. This should work as expected.
Seeing how this is a Config file, I assume it should be included first, or almost first. It may contain vital settings, for the rest of the script load.
Also - Often a shared.lua is included, to be equal to a shared_init file. This may be your case. If it is, you should add one include("sh_config.lua") with the includes, in shared.lua, and AddCSLuaFile("sh_config.lua") in a if CLIENT then-block

LuaRings - How to access values set in slave states (by stable.set) in master state?

Minimal example is really the 2nd example from Rings main page
require"rings"
local init_cmd = [[
require"stable"]]
local count_cmd = [[
count = stable.get"shared_counter" or 0
stable.set ("shared_counter", count + 1)
return count
]]
S = rings.new () -- new state
assert(S:dostring (init_cmd))
print (S:dostring (count_cmd)) -- true, 0
print (S:dostring (count_cmd)) -- true, 1
S:close ()
S = rings.new () -- another new state
assert (S:dostring (init_cmd))
print (S:dostring (count_cmd)) -- true, 2
S:close ()
However, I'm not able to get value of shared_counter. print(shared_counter) outputs nil.
I've tried to use stable.get(), but it says stable can only be used in slave states.
I finally tried
remotedostring("shared_counter = "..count)
Which worked, but I'm not quite sure if it's a proper way to do it. I guess direct access to stable value table would be sufficent?
EDIT: Oh, and I forgot to add, that the main part of the problem is communicating in the other way - from master to slave.
The stable library stores the values in a global table in the master state called _state_persistent_table_. Though obviously this is meant to be hidden and private.
If you're uncomfortable with this, stable just uses remotedostring() internally, and it would not be hard to do something like that yourself.
For master->slave, slave:dostring() should suffice, using similar techniques.

Resources