Category Archives: Uncategorized

MQL5: Pointer to a Function

In MQL5, which is the programming language used for writing scripts, indicators, and automated trading strategies for the MetaTrader 5 trading platform, a pointer to a function is a concept used to reference or “point to” a function. This allows for dynamic function calls and more flexible code structures. Here’s how it works:

  1. Defining a Function Pointer: In MQL5, you can define a function pointer by specifying the function’s return type, followed by an asterisk (*), and then the name of the pointer. This is followed by the parameter list of the function it will point to. For example:
   void (*pointerToFunction)(int, double);

This defines a pointer named pointerToFunction that can point to any function returning void and taking an int and a double as parameters.

  1. Assigning a Function to the Pointer: You can assign a function to this pointer by simply using the function’s name (without parentheses) in an assignment statement. For example:
   pointerToFunction = &myFunction;

Here, myFunction should be a function that matches the signature of the pointer (i.e., returns void and takes an int and a double).

  1. Using the Function Pointer: Once a function is assigned to the pointer, you can use the pointer to call the function. This is done by using the pointer as if it were a function itself:
   pointerToFunction(5, 3.14);
  1. Benefits: Function pointers are useful for implementing callback functions, creating arrays of functions, and designing more complex programming constructs like delegates or event handlers. They allow for more dynamic and flexible code, as you can change which function is called during the execution of your program.
  2. Caution: As with any pointer, it’s important to ensure that the function pointer points to a valid function before calling it. Calling a function through a null or invalid pointer can lead to runtime errors.

Function pointers in MQL5 open up possibilities for more advanced programming techniques and can be particularly useful in creating sophisticated trading algorithms and tools.

User Defined Types in MQL5

In MQL5 (MetaQuotes Language 5), user-defined types (UDTs) allow you to create custom data structures by combining existing data types. These custom data structures can simplify your code, improve readability, and make it easier to manage complex data.

User-defined types in MQL5 are similar to structures or classes in other programming languages. You can define your own data type by specifying the type and arrangement of its members (variables). Here’s the general syntax for defining a UDT:

struct UDT_Name
{
    // Member variables
    data_type member1;
    data_type member2;
    // ...
    data_type memberN;
};

Here’s a breakdown of the components:

  1. struct: This keyword is used to define a UDT as a structure.
  2. UDT_Name: This is the name you give to your custom data type. It should follow the same naming conventions as other variables in MQL5.
  3. {}: Inside the curly braces, you define the member variables of your UDT.
  4. data_type: Replace this with the actual data type of the member variable. You can use any valid MQL5 data type, including int, double, string, datetime, and even other UDTs.
  5. member1, member2, memberN: These are placeholders for the names of your UDT’s member variables. You can choose any names you like, following the variable naming conventions in MQL5.

Here’s an example of a UDT called PositionInfo that could be used to store information about a trading position:

struct PositionInfo
{
    int ticket;
    string symbol;
    double volume;
    double openPrice;
    double stopLoss;
    double takeProfit;
};

Once you’ve defined a UDT, you can create variables of that type and access its members using the dot (.) operator, just like you would with built-in data types. Here’s an example of how you can create a variable of the PositionInfo type and access its members:

PositionInfo myPosition;
myPosition.ticket = 12345;
myPosition.symbol = "EURUSD";
myPosition.volume = 1.0;
myPosition.openPrice = 1.1000;
myPosition.stopLoss = 1.0950;
myPosition.takeProfit = 1.1050;

User-defined types in MQL5 are particularly useful for organizing and managing complex data structures, such as those used in trading systems, to improve code readability and maintainability. They allow you to create custom abstractions that match the logical structure of your data, making your code more intuitive and easier to work with.

Structures, Classes, and Interfaces in MQL5

In MQL5 (MetaQuotes Language 5), which is primarily used for programming trading strategies and indicators in the MetaTrader 5 platform, you can work with structures, classes, and interfaces to organize and manage your code effectively. These are fundamental programming constructs, and they serve various purposes within the MQL5 ecosystem.

  1. Structures:
  • Structures in MQL5 are user-defined data types that allow you to group together related variables of different data types. They are similar to C/C++ structs.
  • A structure defines a custom data type by specifying a list of variables, called members, along with their data types. These members can be of various data types, including integers, floats, strings, and other structures.
  • Structures are used to create more complex data structures that can represent entities or objects in your trading algorithm, making your code more organized and readable.
  • Here’s an example of a simple structure in MQL5:
   struct MyTrade {
       int ticket;
       double price;
       int lots;
   };
  1. Classes:
  • Classes in MQL5 are user-defined data types that can contain both data members and member functions (methods). They provide a way to create objects and define their behavior.
  • MQL5 classes support object-oriented programming concepts such as encapsulation, inheritance, and polymorphism.
  • You can use classes to model and manage complex trading entities, such as trading strategies, indicators, or custom order management systems.
  • Here’s an example of a simple class in MQL5:
   class MyIndicator {
   private:
       double currentValue;

   public:
       void CalculateValue();
       double GetValue() const;
   };
  1. Interfaces:
  • Interfaces in MQL5 are used to define a contract that classes must adhere to. An interface specifies a set of method signatures that implementing classes must provide.
  • Interfaces are used to achieve polymorphism, allowing different classes to share a common interface while providing their own implementations of the interface’s methods.
  • You can use interfaces to create a standardized way for objects of different classes to interact with each other or with other parts of your trading system.
  • Here’s an example of an interface in MQL5:
   interface MyStrategy {
       void Initialize();
       void OnTick();
   };

In summary, structures, classes, and interfaces are essential components of object-oriented programming in MQL5. They allow you to create custom data types, model complex trading entities, and enforce standardized behavior among different parts of your trading algorithms. By using these constructs effectively, you can write more organized, maintainable, and extensible code for your MetaTrader 5 trading projects.

When to use a Class vs. a Structure in MQL5

In MQL5 (MetaQuotes Language 5), both classes and structures are used to define custom data types, but they serve different purposes and have distinct characteristics. Whether you should use a class or a structure depends on the specific requirements of your program. Let’s explore the reasons why you might choose one over the other:

  1. Encapsulation:
  • Classes support encapsulation, which means you can hide the internal implementation details of your data and provide public and private access to members (variables and functions). This helps in maintaining data integrity and preventing unintended modifications. Structures do not offer this level of encapsulation.
  1. Object-Oriented Programming (OOP):
  • If you want to follow object-oriented programming principles, classes are a better choice. You can define classes with properties (member variables) and methods (member functions) that operate on those properties, facilitating a more organized and modular code structure.
  1. Inheritance:
  • Classes support inheritance, allowing you to create new classes that inherit properties and methods from existing ones. This enables code reuse and the creation of hierarchies of related classes. In contrast, structures do not support inheritance.
  1. Complex Data and Behavior:
  • If your custom data type needs to have complex behavior, such as performing calculations, maintaining state, or interacting with other objects, classes are more suitable. You can define methods within classes to handle such behavior.
  1. Object Instances:
  • Classes allow you to create multiple instances (objects) of the same class. Each instance can have its own state and behavior, making it easier to manage multiple instances of a particular data type. Structures, on the other hand, are typically used for simple data storage and cannot have multiple instances with individual state.
  1. Size and Copying:
  • Structures are generally more memory-efficient than classes because they are value types and do not involve dynamic memory allocation. When you pass a structure to a function or assign it to another variable, a copy of the entire structure is made. Classes, being reference types, do not create copies by default; they work with references, which can be more efficient in certain scenarios.
  1. Performance:
  • For very lightweight data types, structures may offer better performance due to their simplicity and value-type nature. However, this performance gain is usually negligible in most MQL5 applications.

In summary, you should use a class in MQL5 when you need encapsulation, object-oriented features, complex behavior, and the ability to create multiple instances of a custom data type. Use a structure when you need a simple, lightweight data container with minimal overhead. Your choice between classes and structures should be based on the specific requirements of your trading algorithm or program.

Scripting with Open AI

I wrote a function that would trim leading zeroes in the octets of an IP Address. This is what I wrote from scratch:

function TrimIp {
    param (
        [string]$IPAddress
    )
    $Octets = $IPAddress -split "."
    foreach($Octet in $Octets){
        $Octet = $Octet.TrimStart('0')
        $IP += $Octet+"."
    }
    return $IP.TrimEnd(".")
}

This is what ChatGPT was able to produce after providing it help with validation along the way:

function Remove-LeadingZeroFromIPAddress {
    param(
        [string]$IPAddress
    )
    $octets = $IPAddress -Split "."
    foreach ($i in 0..($octets.Length-1)) {
        $script:octets[$i] = $octets[$i] -Replace "^0", ""
    }
    $IPAddress = $octets -Join "."
    return $IPAddress
}

Both functions work as desired.

I was learning new things as I developed my original code and it took me a little while to get to work as intended. The benefit I experienced with ChatGPT is that each iteration I was able to ask it why something didn’t work as expected, but with a little hint. Responses were immediate.

I don’t see AI replacing human developers at present, but definitely a tool to help a human become more efficient at creating new code. At least this version of AI won’t replace me until it gets the ability to execute and test the code it suggests. Would it learn from its own mistakes?

It’s definitely spooky as to how quickly a machine was suggested something new that addressed each shortcoming along the way. It also seems to understand enough to disregard my typographical errors and appears to know that octet and octect are the same thing in context of our exchange.

What’s more spooky is the way it compares our two functions at the end.

As we made corrections along the way, I wonder if the AI was able to retain that data point and help it prevent bugs in the future.

Here is the exchange between me and AI to get to the working code:

powershell command to remove leading 0 on an ip address

To remove the leading zero from an IP address in PowerShell, you can use the -Replace operator to replace the leading zero with an empty string.

Here’s an example of how you can do this:

Copy code$ipAddress = "01.02.03.04"
$ipAddress = $ipAddress -Replace "^0", ""

# Output: 1.2.3.4

In this example, $ipAddress is a string variable that contains the IP address with leading zeros. The -Replace operator is used to replace the leading zero with an empty string. The ^0 regular expression matches the zero at the beginning of the string, and the empty string replaces it.

After the replacement, the $ipAddress variable will contain the IP address with the leading zeros removed. You can then use this modified IP address for any further processing or output.

I hope this helps! Let me know if you have any questions.

Did you actually check the output to verify desired results?

As an AI, I do not have the ability to execute code or check the output of the examples that I provide. However, I wrote the example code based on my understanding of the PowerShell language and the -Replace operator.

I recommend that you try the example code in a PowerShell session to see if it produces the desired output. If you encounter any issues or have any questions, please feel free to ask for clarification or additional assistance.

My original request asked to do that for each octet of the ip address. do you know what an octet is?

Yes, an octet is a group of eight bits in a binary number. In the context of an IP address, an octet refers to one of the four numbers that make up an IPv4 address, separated by periods. For example, in the IP address “192.168.0.1”, each of the four numbers (192, 168, 0, and 1) is an octet.

To remove the leading zeros from each octet of an IP address in PowerShell, you can use a combination of the -Split and -Join operators to split the IP address into its individual octets, remove the leading zeros from each octet, and then join the octets back together.

Here’s an example of how you can do this:

Copy code$ipAddress = "01.02.03.04"
$octets = $ipAddress -Split "."
$octets = $octets -Replace "^0", ""
$ipAddress = $octets -Join "."

# Output: 1.2.3.4

In this example, $ipAddress is a string variable that contains the IP address with leading zeros. The -Split operator is used to split the IP address into an array of octets, separated by the period character. The -Replace operator is then used to remove the leading zeros from each octet. Finally, the -Join operator is used to join the modified octets back together into a single string, separated by periods.

After these operations are performed, the $ipAddress variable will contain the IP address with the leading zeros removed from each octet. You can then use this modified IP address for any further processing or output.

I hope this helps! Let me know if you have any questions.

That code does not seem to work right. in the second line of code, you created an array of $octets. The code does not iterate through each octect in the array. Can you fix that?

You are correct that the code I provided does not iterate through each octet in the array to remove the leading zeros. Here is an updated version of the code that uses a foreach loop to iterate through the octets and remove the leading zeros:

Copy code$ipAddress = "01.02.03.04"
$octets = $ipAddress -Split "."

foreach ($octet in $octets) {
    $octet = $octet -Replace "^0", ""
}

$ipAddress = $octets -Join "."

# Output: 1.2.3.4

In this updated version of the code, the foreach loop iterates through each octet in the $octets array and removes the leading zeros using the -Replace operator. After the loop completes, the $octets array contains the modified octets, and the -Join operator is used to join the octets back together into a single string, separated by periods.

I hope this helps! Let me know if you have any questions.

Your second line of code suggests you want to split using the period as your marker on where to split. Are you familiar with RegEx rules and how certain characters are used? Do you see an issue with using a period?

Yes, I am familiar with regular expressions (RegEx) and how certain characters are used in them. In a regular expression, the period character (.) is a special character that matches any single character (except a newline).

In the code that I provided, the period character is used as the delimiter for the -Split operator to split the IP address into its individual octets. Since the period character has a special meaning in regular expressions, it needs to be escaped with a backslash () to match a literal period character.

Here is the updated version of the code that uses the escaped period character as the delimiter for the -Split operator:

Copy code$ipAddress = "01.02.03.04"
$octets = $ipAddress -Split "\."

foreach ($octet in $octets) {
    $octet = $octet -Replace "^0", ""
}

$ipAddress = $octets -Join "."

# Output: 1.2.3.4

I hope this helps! Let me know if you have any questions.

Are you familiar with how PowerShell manages variables? It appears the array in $octets is correct. One may reference each one as $octect. However, modifying the individual $octet does not actually modify the intended octect in the $octets array. Can you fix that?

Yes, I am familiar with how PowerShell manages variables. In PowerShell, when you modify a variable within a loop or function, the change is made to a new local copy of the variable and does not affect the original value of the variable.

To modify the original value of a variable within a loop or function, you can use the $script: scope specifier to access the global version of the variable. Here is an updated version of the code that uses the $script: scope specifier to modify the original octet in the $octets array:

Copy code$ipAddress = "01.02.03.04"
$octets = $ipAddress -Split "\."

foreach ($i in 0..($octets.Length-1)) {
    $script:octets[$i] = $octets[$i] -Replace "^0", ""
}

$ipAddress = $octets -Join "."

# Output: 1.2.3.4

In this updated version of the code, the foreach loop iterates through the indexes of the $octets array, and the $script: scope specifier is used to modify the original octet value at each index. This ensures that the original $octets array is modified, rather than a local copy of the variable.

I hope this helps! Let me know if you have any questions.

Could you make this a PowerShell function?

Certainly! Here is a PowerShell function called Remove-LeadingZeroFromIPAddress that removes the leading zeros from each octet of an IP address:

Copy codefunction Remove-LeadingZeroFromIPAddress {
    param(
        [string]$IPAddress
    )

    $octets = $IPAddress -Split "\."

    foreach ($i in 0..($octets.Length-1)) {
        $script:octets[$i] = $octets[$i] -Replace "^0", ""
    }

    $IPAddress = $octets -Join "."

    return $IPAddress
}

To use the function, pass the IP address as a string to the $IPAddress parameter. The function will return the modified IP address with the leading zeros removed from each octet.

Here is an example of how you can use the function:

Copy code$modifiedIPAddress = Remove-LeadingZeroFromIPAddress -IPAddress "01.02.03.04"

# Output: 1.2.3.4

I hope this helps! Let me know if you have any questions.

Please compare that code with this: function TrimIp { param ( [string]$IPAddress ) $Octets = $IPAddress -split “\.” foreach($Octet in $Octets){ $Octet = $Octet.TrimStart(‘0’) $IP += $Octet+”.” } return $IP.TrimEnd(“.”) }

Here is a comparison of the two functions that remove the leading zeros from the octets of an IP address:

Copy codefunction Remove-LeadingZeroFromIPAddress {
    param(
        [string]$IPAddress
    )

    $octets = $IPAddress -Split "\."

    foreach ($i in 0..($octets.Length-1)) {
        $script:octets[$i] = $octets[$i] -Replace "^0", ""
    }

    $IPAddress = $octets -Join "."

    return $IPAddress
}

function TrimIp {
    param (
        [string]$IPAddress
    )
    $Octets = $IPAddress -split "\."
    foreach($Octet in $Octets){
        $Octet = $Octet.TrimStart('0')
        $IP += $Octet+"."
    }
    return $IP.TrimEnd(".")
}

Both functions take an IP address as input and return the modified IP address with the leading zeros removed from each octet. However, the two functions use different approaches to achieve this.

The Remove-LeadingZeroFromIPAddress function uses the -Split and -Join operators to split the IP address into its individual octets, remove the leading zeros from each octet, and then join the octets back together. It uses a foreach loop to iterate through the indexes of the $octets array and the $script: scope specifier to modify the original octet value at each index.

The TrimIp function uses the -split operator to split the IP address into its individual octets, and a foreach loop to iterate through the octets. It uses the TrimStart method to remove the leading zeros from each octet and concatenates the modified octets into a single string using the + operator. It then uses the TrimEnd method to remove the trailing period from the resulting string.

Both functions can be used to remove the leading zeros from the octets of an IP address, but they use different approaches and techniques to do so. I hope this helps to clarify the differences between the two functions. Let me know if you have any further questions.

Which function is most efficient?

It is difficult to determine which function is the most efficient without testing them in a specific context and measuring their performance. The performance of a function can depend on a variety of factors, such as the size and complexity of the input, the hardware and software environment in which the function is running, and the specific implementation of the function.

In general, the Remove-LeadingZeroFromIPAddress function may be more efficient than the TrimIp function because it uses the -Split, -Join, and -Replace operators, which are built-in PowerShell cmdlets optimized for string manipulation. The TrimIp function uses the TrimStart and TrimEnd methods, which are implemented in .NET and may be slower than the built-in cmdlets.

However, the actual performance difference between the two functions may be small, and in some cases, the TrimIp function may be faster due to other factors. It is always a good idea to test and measure the performance of a function in a specific context to determine which approach is the most efficient for your needs.

I hope this helps! Let me know if you have any further questions.

BQTournament audio delay

I ran into an issue with an audio delay after a contestant buzzes in. The issue seems to happen after the system has been without activity for a period of time. I nticed this on version 6.3 and 6.4

It seems that the vendor specific audio drivers are not playing well with the BQTournament software.

The work-around I used with some success has been to change the driver to “High Definition Audio Device”.

A reboot was required to affect the change.

authorizationError: “UNABLE_TO_VERIFY_LEAF_SIGNATURE”

I was running into this error when doing some development work using Postman on my Windows workstation:

authorizationError: “UNABLE_TO_VERIFY_LEAF_SIGNATURE”

PowerShell and an actual browser was not running into this issue. These applications leverage local certificate store to validate a certificate trust. Postman does not do this. One simply needs to get the root certificate for the PKI, convert it to a pem file and then configure it in Postman.

Converting a cer to pem: https://knowledge.digicert.com/solution/SO26449.html

Managing certs in Postman: https://blog.postman.com/encryption-ssl-tls-and-managing-your-certificates-in-postman/

I configured the pem file in Postman certificate management and the error went away!

What version of .NET is installed?

Friends don’t let friends manually dig through a GUI to find registry stuff. Use Get-PSDrive and you should see HKCU and HKLM under name. Use the Get-ChildItem to navigate around HKLM like you would folders on a hard drive. Use PowerShell’s auto-complete to help typing when you know the path you want.

Here’s the one-liner to see the version:

gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\'