Anonymous
Обернуть Python в C ++ DLL для использования в MQL4
Сообщение
Anonymous » 30 май 2025, 19:54
Я пытаюсь создать dll из Python для использования в MQL4 EA . Я знаю, что могу использовать что -то вроде ZMQ, чтобы назвать Python, но это не работает, так как вы не можете использовать сокеты в бэк -тестировании. У меня есть файлы Folliwing, которые выполняют компиляцию и создают файл .exe . Когда я прикрепляю EA к диаграмме и смотрю на вкладку DLL и разбавляю, показывает, что в списке функции add_me , однако, когда я запускаю EA, не может найти 'add_me' в 'trading_functions.exe' и dlltest eurusd, h4: upressed import -функция Call>. />
trading_functions.py
Код: Выделить всё
from ctypes import *
def add(a, b):
return a + b
trading_dll.spec
Код: Выделить всё
block_cipher = None
a = Analysis(['dll_wrapper.py'],
pathex=['.'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='trading_functions',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True,
disable_windowed_traceback=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None )
# Create DLL
dll = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='trading_functions',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
dll=True) # This makes it a DLL
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='trading_functions')
setup_dll.py
Код: Выделить всё
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
ext_modules = [
Extension("trading_dll",
sources=["dll_interface.py"],
libraries=["python311"], # Adjust for your Python version
include_dirs=[numpy.get_include()],
)
]
setup(
name="trading_dll",
ext_modules=cythonize(ext_modules),
)
dll_wrapper.py
Код: Выделить всё
from ctypes import *
import trading_functions
@CFUNCTYPE(c_int, c_int)
def add_me(a, b):
try:
return a + b
except:
return 0
dll_interface.py
Код: Выделить всё
from ctypes import *
from try2 import trading_functions
# Define the exported functions
def add_me(a, b):
try:
return a + b
except Exception as e:
print(f"Error in add_me: {e}")
return 0
build_dll.py
Код: Выделить всё
import os
import sys
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext
def build_dll():
sources = ['dll_wrapper.py']
module = Extension(
'trading_functions',
sources=sources,
export_symbols=['add_me']
)
setup(
name='trading_functions',
version='1.0',
ext_modules=[module],
cmdclass={'build_ext': build_ext}
)
if __name__ == '__main__':
build_dll()
< /code>
Я строю его с командой:
pyinstaller --clean trading_dll.spec
Вывод из этого:
Код: Выделить всё
336 INFO: PyInstaller: 6.13.0, contrib hooks: 2025.4
336 INFO: Python: 3.11.9
350 INFO: Platform: Windows-10-10.0.26100-SP0
350 INFO: Python environment: C:\python\VENV\dllTest
350 INFO: Removing temporary files and cleaning cache in C:\Users\kevin\AppData\Local\pyinstaller
350 INFO: Module search paths (PYTHONPATH):
['C:\\python\\VENV\\dllTest\\Scripts\\pyinstaller.exe',
'C:\\python\\python3.11\\python311.zip',
'C:\\python\\python3.11\\DLLs',
'C:\\python\\python3.11\\Lib',
'C:\\python\\python3.11',
'C:\\python\\VENV\\dllTest',
'C:\\python\\VENV\\dllTest\\Lib\\site-packages',
'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\setuptools\\_vendor',
'C:\\Users\\kevin\\python-proj\\dllTest\\try7',
'C:\\Users\\kevin\\python-proj\\dllTest\\try7']
1189 INFO: checking Analysis
1189 INFO: Building Analysis because Analysis-00.toc is non existent
1189 INFO: Running Analysis Analysis-00.toc
1189 INFO: Target bytecode optimization level: 0
1189 INFO: Initializing module dependency graph...
1205 INFO: Initializing module graph hook caches...
1275 INFO: Analyzing modules for base_library.zip ...
2918 INFO: Processing standard module hook 'hook-heapq.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks'
3093 INFO: Processing standard module hook 'hook-encodings.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks'
5907 INFO: Processing standard module hook 'hook-pickle.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks'
10050 INFO: Caching module dependency graph...
10113 INFO: Looking for Python shared library...
10113 INFO: Using Python shared library: C:\python\python3.11\python311.dll
10113 INFO: Analyzing C:\Users\kevin\python-proj\dllTest\try7\dll_wrapper.py
10176 INFO: Processing module hooks (post-graph stage)...
10178 INFO: Performing binary vs. data reclassification (1 entries)
10178 INFO: Looking for ctypes DLLs
10205 INFO: Analyzing run-time hooks ...
10205 INFO: Including run-time hook 'pyi_rth_inspect.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks'
10224 INFO: Creating base_library.zip...
10350 INFO: Looking for dynamic libraries
10540 INFO: Extra DLL search directories (AddDllDirectory): []
10540 INFO: Extra DLL search directories (PATH): []
10779 INFO: Warnings written to C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\warn-trading_dll.txt
10811 INFO: Graph cross-reference written to C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\xref-trading_dll.html
10889 INFO: checking PYZ
10889 INFO: Building PYZ because PYZ-00.toc is non existent
10889 INFO: Building PYZ (ZlibArchive) C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\PYZ-00.pyz
11303 INFO: Building PYZ (ZlibArchive) C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\PYZ-00.pyz completed successfully.
11319 INFO: checking PKG
11321 INFO: Building PKG because PKG-00.toc is non existent
11321 INFO: Building PKG (CArchive) trading_functions.pkg
13011 INFO: Building PKG (CArchive) trading_functions.pkg completed successfully.
13011 INFO: Bootloader C:\python\VENV\dllTest\Lib\site-packages\PyInstaller\bootloader\Windows-32bit-intel\run.exe
13014 INFO: checking EXE
13014 INFO: Building EXE because EXE-00.toc is non existent
13014 INFO: Building EXE from EXE-00.toc
13014 INFO: Copying bootloader EXE to C:\Users\kevin\python-proj\dllTest\try7\dist\trading_functions.exe
13027 INFO: Copying icon to EXE
13043 INFO: Copying 0 resources to EXE
13043 INFO: Embedding manifest in EXE
13052 INFO: Appending PKG archive to EXE
13058 INFO: Fixing EXE headers
13122 INFO: Building EXE from EXE-00.toc completed successfully.
13146 INFO: checking PKG
13146 INFO: Building PKG because PKG-01.toc is non existent
13146 INFO: Building PKG (CArchive) trading_functions.pkg
13154 INFO: Building PKG (CArchive) trading_functions.pkg completed successfully.
13154 INFO: Bootloader C:\python\VENV\dllTest\Lib\site-packages\PyInstaller\bootloader\Windows-32bit-intel\runw.exe
13154 INFO: checking EXE
13154 INFO: Building EXE because EXE-01.toc is non existent
13154 INFO: Building EXE from EXE-01.toc
13154 INFO: Copying bootloader EXE to C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\trading_functions.exe
13218 INFO: Copying icon to EXE
13233 INFO: Copying 0 resources to EXE
13233 INFO: Embedding manifest in EXE
13233 INFO: Appending PKG archive to EXE
13233 INFO: Fixing EXE headers
13281 INFO: Building EXE from EXE-01.toc completed successfully.
13281 INFO: checking COLLECT
13281 INFO: Building COLLECT because COLLECT-00.toc is non existent
13281 INFO: Building COLLECT COLLECT-00.toc
13361 INFO: Building COLLECT COLLECT-00.toc completed successfully.
13361 INFO: Build complete! The results are available in: C:\Users\kevin\python-proj\dllTest\try7\dist
< /code>
my ea ea
[b] dlltest.mq4[/b]
#property copyright "Your Name"
#property link "https://www.yourwebsite.com"
#property version "1.00"
#property strict
// Import DLL functions
#import "trading_functions.exe"
double add_me(int a, int b);
#import
// EA inputs
input int MA_Period = 20;
input int RSI_Period = 14;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
Print(add_me(2, 3));
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
}
Любая помощь о том, почему это не работает, будет оценена.
Подробнее здесь:
https://stackoverflow.com/questions/796 ... se-in-mql4
1748624054
Anonymous
Я пытаюсь создать dll из Python для использования в MQL4 EA . Я знаю, что могу использовать что -то вроде ZMQ, чтобы назвать Python, но это не работает, так как вы не можете использовать сокеты в бэк -тестировании. У меня есть файлы Folliwing, которые выполняют компиляцию и создают файл .exe . Когда я прикрепляю EA к диаграмме и смотрю на вкладку DLL и разбавляю, показывает, что в списке функции add_me , однако, когда я запускаю EA, не может найти 'add_me' в 'trading_functions.exe' и dlltest eurusd, h4: upressed import -функция Call>. />[b] trading_functions.py[/b] [code]from ctypes import * def add(a, b): return a + b [/code] [b] trading_dll.spec[/b] [code]block_cipher = None a = Analysis(['dll_wrapper.py'], pathex=['.'], binaries=[], datas=[], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='trading_functions', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True, disable_windowed_traceback=False, target_arch=None, codesign_identity=None, entitlements_file=None ) # Create DLL dll = EXE(pyz, a.scripts, [], exclude_binaries=True, name='trading_functions', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=False, dll=True) # This makes it a DLL coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='trading_functions') [/code] [b] setup_dll.py[/b] [code]from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy ext_modules = [ Extension("trading_dll", sources=["dll_interface.py"], libraries=["python311"], # Adjust for your Python version include_dirs=[numpy.get_include()], ) ] setup( name="trading_dll", ext_modules=cythonize(ext_modules), ) [/code] [b]dll_wrapper.py[/b] [code]from ctypes import * import trading_functions @CFUNCTYPE(c_int, c_int) def add_me(a, b): try: return a + b except: return 0 [/code] [b]dll_interface.py[/b] [code]from ctypes import * from try2 import trading_functions # Define the exported functions def add_me(a, b): try: return a + b except Exception as e: print(f"Error in add_me: {e}") return 0 [/code] [b]build_dll.py[/b] [code]import os import sys from distutils.core import setup, Extension from distutils.command.build_ext import build_ext def build_dll(): sources = ['dll_wrapper.py'] module = Extension( 'trading_functions', sources=sources, export_symbols=['add_me'] ) setup( name='trading_functions', version='1.0', ext_modules=[module], cmdclass={'build_ext': build_ext} ) if __name__ == '__main__': build_dll() < /code> Я строю его с командой: pyinstaller --clean trading_dll.spec[/code] Вывод из этого: [code]336 INFO: PyInstaller: 6.13.0, contrib hooks: 2025.4 336 INFO: Python: 3.11.9 350 INFO: Platform: Windows-10-10.0.26100-SP0 350 INFO: Python environment: C:\python\VENV\dllTest 350 INFO: Removing temporary files and cleaning cache in C:\Users\kevin\AppData\Local\pyinstaller 350 INFO: Module search paths (PYTHONPATH): ['C:\\python\\VENV\\dllTest\\Scripts\\pyinstaller.exe', 'C:\\python\\python3.11\\python311.zip', 'C:\\python\\python3.11\\DLLs', 'C:\\python\\python3.11\\Lib', 'C:\\python\\python3.11', 'C:\\python\\VENV\\dllTest', 'C:\\python\\VENV\\dllTest\\Lib\\site-packages', 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\setuptools\\_vendor', 'C:\\Users\\kevin\\python-proj\\dllTest\\try7', 'C:\\Users\\kevin\\python-proj\\dllTest\\try7'] 1189 INFO: checking Analysis 1189 INFO: Building Analysis because Analysis-00.toc is non existent 1189 INFO: Running Analysis Analysis-00.toc 1189 INFO: Target bytecode optimization level: 0 1189 INFO: Initializing module dependency graph... 1205 INFO: Initializing module graph hook caches... 1275 INFO: Analyzing modules for base_library.zip ... 2918 INFO: Processing standard module hook 'hook-heapq.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks' 3093 INFO: Processing standard module hook 'hook-encodings.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks' 5907 INFO: Processing standard module hook 'hook-pickle.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks' 10050 INFO: Caching module dependency graph... 10113 INFO: Looking for Python shared library... 10113 INFO: Using Python shared library: C:\python\python3.11\python311.dll 10113 INFO: Analyzing C:\Users\kevin\python-proj\dllTest\try7\dll_wrapper.py 10176 INFO: Processing module hooks (post-graph stage)... 10178 INFO: Performing binary vs. data reclassification (1 entries) 10178 INFO: Looking for ctypes DLLs 10205 INFO: Analyzing run-time hooks ... 10205 INFO: Including run-time hook 'pyi_rth_inspect.py' from 'C:\\python\\VENV\\dllTest\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks' 10224 INFO: Creating base_library.zip... 10350 INFO: Looking for dynamic libraries 10540 INFO: Extra DLL search directories (AddDllDirectory): [] 10540 INFO: Extra DLL search directories (PATH): [] 10779 INFO: Warnings written to C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\warn-trading_dll.txt 10811 INFO: Graph cross-reference written to C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\xref-trading_dll.html 10889 INFO: checking PYZ 10889 INFO: Building PYZ because PYZ-00.toc is non existent 10889 INFO: Building PYZ (ZlibArchive) C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\PYZ-00.pyz 11303 INFO: Building PYZ (ZlibArchive) C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\PYZ-00.pyz completed successfully. 11319 INFO: checking PKG 11321 INFO: Building PKG because PKG-00.toc is non existent 11321 INFO: Building PKG (CArchive) trading_functions.pkg 13011 INFO: Building PKG (CArchive) trading_functions.pkg completed successfully. 13011 INFO: Bootloader C:\python\VENV\dllTest\Lib\site-packages\PyInstaller\bootloader\Windows-32bit-intel\run.exe 13014 INFO: checking EXE 13014 INFO: Building EXE because EXE-00.toc is non existent 13014 INFO: Building EXE from EXE-00.toc 13014 INFO: Copying bootloader EXE to C:\Users\kevin\python-proj\dllTest\try7\dist\trading_functions.exe 13027 INFO: Copying icon to EXE 13043 INFO: Copying 0 resources to EXE 13043 INFO: Embedding manifest in EXE 13052 INFO: Appending PKG archive to EXE 13058 INFO: Fixing EXE headers 13122 INFO: Building EXE from EXE-00.toc completed successfully. 13146 INFO: checking PKG 13146 INFO: Building PKG because PKG-01.toc is non existent 13146 INFO: Building PKG (CArchive) trading_functions.pkg 13154 INFO: Building PKG (CArchive) trading_functions.pkg completed successfully. 13154 INFO: Bootloader C:\python\VENV\dllTest\Lib\site-packages\PyInstaller\bootloader\Windows-32bit-intel\runw.exe 13154 INFO: checking EXE 13154 INFO: Building EXE because EXE-01.toc is non existent 13154 INFO: Building EXE from EXE-01.toc 13154 INFO: Copying bootloader EXE to C:\Users\kevin\python-proj\dllTest\try7\build\trading_dll\trading_functions.exe 13218 INFO: Copying icon to EXE 13233 INFO: Copying 0 resources to EXE 13233 INFO: Embedding manifest in EXE 13233 INFO: Appending PKG archive to EXE 13233 INFO: Fixing EXE headers 13281 INFO: Building EXE from EXE-01.toc completed successfully. 13281 INFO: checking COLLECT 13281 INFO: Building COLLECT because COLLECT-00.toc is non existent 13281 INFO: Building COLLECT COLLECT-00.toc 13361 INFO: Building COLLECT COLLECT-00.toc completed successfully. 13361 INFO: Build complete! The results are available in: C:\Users\kevin\python-proj\dllTest\try7\dist < /code> my ea ea [b] dlltest.mq4[/b] #property copyright "Your Name" #property link "https://www.yourwebsite.com" #property version "1.00" #property strict // Import DLL functions #import "trading_functions.exe" double add_me(int a, int b); #import // EA inputs input int MA_Period = 20; input int RSI_Period = 14; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Print(add_me(2, 3)); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { } [/code] Любая помощь о том, почему это не работает, будет оценена. Подробнее здесь: [url]https://stackoverflow.com/questions/79645832/wrap-python-in-c-dll-for-use-in-mql4[/url]