i would like to discuss topic about how to get trully random numbers for best possible simulations of your forex trading EA or setup.
First of all, common random number generators in classic libraries are not truly random. I don't know, how many peoplet actually that know.
And i think that truly random numbers are elementary basic to be able to test your trading strategy properly.
So here are is my code in Python, how i try to create and store random numbers in operating memory:
Code: Select all
import os
import secrets
import numpy as np
def generate_secure_bytes(size_in_bytes):
"""
Fills a mutable bytearray in operating memory with highly secure,
OS-generated random bytes.
"""
# os.urandom pulls from the OS hardware entropy pool
# bytearray ensures it stays in a mutable, efficient memory array
return bytearray(os.urandom(size_in_bytes))
def generate_secure_integers(count, max_value):
"""
Generates an array of secure random integers using the secrets module.
Slower than os.urandom, but easier to use for specific integer ranges.
"""
return [secrets.randbelow(max_value) for _ in range(count)]
# --- Example Usage ---
# 1. Generate 1 Megabyte of purely random data into memory
megabyte_array = generate_secure_bytes(1024 * 1024)
print(f"Generated {len(megabyte_array)} bytes of secure entropy.")
# 2. If you need a mathematical array (like NumPy) of random floats (0.0 to 1.0)
# We can securely convert random bytes into NumPy floats
def generate_secure_numpy_floats(count):
# Get random bytes (8 bytes per 64-bit float)
random_bytes = os.urandom(count * 8)
# Convert bytes to 64-bit unsigned integers
random_ints = np.frombuffer(random_bytes, dtype=np.uint64)
# Divide by the maximum 64-bit integer value to get a float between 0 and 1
return random_ints / (2**64 - 1)
secure_floats = generate_secure_numpy_floats(100)
print(f"First 3 secure floats: {secure_floats[:3]}")To achieve the "best randomness possible" in Python, you must avoid the standard random module, which uses a predictable Pseudo-Random Number Generator (PRNG) called the Mersenne Twister.
For true randomness, you have two primary options depending on your strict definition of "true":
OS-Level Hardware Entropy (Cryptographically Secure): Uses your computer's environmental noise (disk reads, keystrokes, CPU thermal noise) gathered by the operating system. This is the standard for high-security cryptographic applications.
Quantum/Atmospheric True Randomness (API): Fetches numbers generated by physical quantum phenomena or atmospheric noise from external scientific servers.
Here is the Python code for both approaches.
Method 1: OS-Level Entropy (Best for Local Memory & Speed)
This approach uses os.urandom() or the secrets module. It pulls directly from your operating system's entropy pool (e.g., /dev/urandom on Linux/Mac, or CryptGenRandom on Windows), which is seeded by actual hardware events.