admin管理员组文章数量:1024615
I’m trying to create a new user account on the MT5 server using the following Python code, but it’s not working as expected. The connection to the server seems to succeed, but the user creation process either fails or does not return the expected result.
Here is the full code I’m using:
import logging
from MT5Manager import ManagerAPI
import time
# Logging setup
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
MT5_SERVER_ADDRESS = "***"
MT5_LOGIN_ID = 1011
MT5_PASSWORD = "***"
def connect_to_mt5():
"""Connect to the MT5 server with detailed debugging."""
manager = ManagerAPI()
try:
logger.info("Attempting to connect to the MT5 server...")
response = manager.Connect(MT5_SERVER_ADDRESS, MT5_LOGIN_ID, MT5_PASSWORD, 2, 1000000)
if response:
logger.info("Successfully connected to the MT5 server.")
return manager
else:
logger.error("Failed to connect to the MT5 server. Raw response: %s", response)
return None
except Exception as e:
logger.exception("Exception occurred during connection to the MT5 server.")
return None
def add_user(manager, pass_main, pass_investor, group, **kwargs):
"""Create a user account on the MT5 server with minimal data."""
try:
logger.info("Preparing user creation request...")
user_request = {
"pass_main": pass_main, # Main password
"pass_investor": pass_investor, # Investor password
"group": group, # Group name
"name": kwargs.get("name", "Propiy"), # Optional name
"city": kwargs.get("city", "website"), # Optional city
"state": kwargs.get("state", "website"), # Optional state
"country": kwargs.get("country", "website"), # Optional country
"zipcode": kwargs.get("zipcode", "1470"), # Optional zipcode
}
logger.debug("User request data: %s", user_request)
logger.info("Sending user creation request to the MT5 server...")
result = manager.UserAdd(user_request)
logger.debug(f"Raw UserAdd response: {result}")
if result == 0:
logger.info("User creation request succeeded.")
# Retrieve and inspect all users
logins = manager.UserLogins()
if logins:
logger.info("Retrieved logins: %s", logins)
for login in logins:
user_details = manager.UserGet({"Login": login})
logger.debug(f"Retrieved user details: {user_details}")
# Match user details
if user_details and user_details.get("Name") == user_request["name"]:
logger.info(f"Successfully located created user with Login ID: {user_details['Login']}")
return user_details["Login"]
logger.error("Failed to locate the created user in the retrieved list.")
else:
logger.error(f"User creation failed. Server returned: {result}")
return None
except Exception as e:
logger.exception("Exception occurred during user creation.")
return None
if __name__ == "__main__":
try:
logger.info("Starting the MT5 user creation script...")
manager = connect_to_mt5()
if manager:
# Add a delay to ensure the server has stabilized between connections
time.sleep(2)
# Minimal user info for testing
pass_main = "Test123!"
pass_investor = "forex-hedge"
group = "1" # Replace with the target group
# Attempt to create the user
login_id = add_user(manager, pass_main, pass_investor, group)
if login_id:
logger.info(f"User created successfully with Login ID: {login_id}")
else:
logger.error("Failed to create the user.")
# Disconnect from the server
logger.info("Disconnecting from the MT5 server...")
manager.Disconnect()
logger.info("Disconnected successfully.")
else:
logger.error("Could not establish a connection to the MT5 server.")
except Exception as main_exception:
logger.exception("An unexpected error occurred during execution.")
and I get this result
2024-11-18 15:44:10,428 - INFO - Starting the MT5 user creation script...
2024-11-18 15:44:10,451 - INFO - Attempting to connect to the MT5 server...
2024-11-18 15:44:10,583 - INFO - Successfully connected to the MT5 server.
2024-11-18 15:44:12,584 - INFO - Preparing user creation request...
2024-11-18 15:44:12,584 - DEBUG - User request data: {'pass_main': 'Test123!', 'pass_investor': 'forex-hedge', 'group': '1', 'name': 'Propiy', 'city': 'website', 'state': 'website', 'country': 'website', 'zipcode': '1470'}
2024-11-18 15:44:12,584 - INFO - Sending user creation request to the MT5 server...
2024-11-18 15:44:12,584 - DEBUG - Raw UserAdd response: False
2024-11-18 15:44:12,584 - INFO - User creation request succeeded.
2024-11-18 15:44:12,584 - ERROR - Failed to locate the created user in the retrieved list.
2024-11-18 15:44:12,585 - ERROR - Failed to create the user.
2024-11-18 15:44:12,585 - INFO - Disconnecting from the MT5 server...
2024-11-18 15:44:12,594 - INFO - Disconnected successfully.
The code seems to connect to the MT5 server successfully, but either the UserAdd function fails or the created user cannot be found using UserLogins. what's is wrong with code?
I’m trying to create a new user account on the MT5 server using the following Python code, but it’s not working as expected. The connection to the server seems to succeed, but the user creation process either fails or does not return the expected result.
Here is the full code I’m using:
import logging
from MT5Manager import ManagerAPI
import time
# Logging setup
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
MT5_SERVER_ADDRESS = "***"
MT5_LOGIN_ID = 1011
MT5_PASSWORD = "***"
def connect_to_mt5():
"""Connect to the MT5 server with detailed debugging."""
manager = ManagerAPI()
try:
logger.info("Attempting to connect to the MT5 server...")
response = manager.Connect(MT5_SERVER_ADDRESS, MT5_LOGIN_ID, MT5_PASSWORD, 2, 1000000)
if response:
logger.info("Successfully connected to the MT5 server.")
return manager
else:
logger.error("Failed to connect to the MT5 server. Raw response: %s", response)
return None
except Exception as e:
logger.exception("Exception occurred during connection to the MT5 server.")
return None
def add_user(manager, pass_main, pass_investor, group, **kwargs):
"""Create a user account on the MT5 server with minimal data."""
try:
logger.info("Preparing user creation request...")
user_request = {
"pass_main": pass_main, # Main password
"pass_investor": pass_investor, # Investor password
"group": group, # Group name
"name": kwargs.get("name", "Propiy"), # Optional name
"city": kwargs.get("city", "website"), # Optional city
"state": kwargs.get("state", "website"), # Optional state
"country": kwargs.get("country", "website"), # Optional country
"zipcode": kwargs.get("zipcode", "1470"), # Optional zipcode
}
logger.debug("User request data: %s", user_request)
logger.info("Sending user creation request to the MT5 server...")
result = manager.UserAdd(user_request)
logger.debug(f"Raw UserAdd response: {result}")
if result == 0:
logger.info("User creation request succeeded.")
# Retrieve and inspect all users
logins = manager.UserLogins()
if logins:
logger.info("Retrieved logins: %s", logins)
for login in logins:
user_details = manager.UserGet({"Login": login})
logger.debug(f"Retrieved user details: {user_details}")
# Match user details
if user_details and user_details.get("Name") == user_request["name"]:
logger.info(f"Successfully located created user with Login ID: {user_details['Login']}")
return user_details["Login"]
logger.error("Failed to locate the created user in the retrieved list.")
else:
logger.error(f"User creation failed. Server returned: {result}")
return None
except Exception as e:
logger.exception("Exception occurred during user creation.")
return None
if __name__ == "__main__":
try:
logger.info("Starting the MT5 user creation script...")
manager = connect_to_mt5()
if manager:
# Add a delay to ensure the server has stabilized between connections
time.sleep(2)
# Minimal user info for testing
pass_main = "Test123!"
pass_investor = "forex-hedge"
group = "1" # Replace with the target group
# Attempt to create the user
login_id = add_user(manager, pass_main, pass_investor, group)
if login_id:
logger.info(f"User created successfully with Login ID: {login_id}")
else:
logger.error("Failed to create the user.")
# Disconnect from the server
logger.info("Disconnecting from the MT5 server...")
manager.Disconnect()
logger.info("Disconnected successfully.")
else:
logger.error("Could not establish a connection to the MT5 server.")
except Exception as main_exception:
logger.exception("An unexpected error occurred during execution.")
and I get this result
2024-11-18 15:44:10,428 - INFO - Starting the MT5 user creation script...
2024-11-18 15:44:10,451 - INFO - Attempting to connect to the MT5 server...
2024-11-18 15:44:10,583 - INFO - Successfully connected to the MT5 server.
2024-11-18 15:44:12,584 - INFO - Preparing user creation request...
2024-11-18 15:44:12,584 - DEBUG - User request data: {'pass_main': 'Test123!', 'pass_investor': 'forex-hedge', 'group': '1', 'name': 'Propiy', 'city': 'website', 'state': 'website', 'country': 'website', 'zipcode': '1470'}
2024-11-18 15:44:12,584 - INFO - Sending user creation request to the MT5 server...
2024-11-18 15:44:12,584 - DEBUG - Raw UserAdd response: False
2024-11-18 15:44:12,584 - INFO - User creation request succeeded.
2024-11-18 15:44:12,584 - ERROR - Failed to locate the created user in the retrieved list.
2024-11-18 15:44:12,585 - ERROR - Failed to create the user.
2024-11-18 15:44:12,585 - INFO - Disconnecting from the MT5 server...
2024-11-18 15:44:12,594 - INFO - Disconnected successfully.
The code seems to connect to the MT5 server successfully, but either the UserAdd function fails or the created user cannot be found using UserLogins. what's is wrong with code?
Share Improve this question asked Nov 18, 2024 at 15:57 Omid GoudaziOmid Goudazi 1902 silver badges9 bronze badges1 Answer
Reset to default 0use this code
# include the library
import MT5Manager
# create manager interface
manager = MT5Manager.ManagerAPI()
# connect the server
if manager.Connect("192.168.1.100:443", 1002, "1Ar#pqkj", 0):
# create a user
user = MT5Manager.MTUser(manager)
# fill in the required fields: group, leverage, first and last name
user.Group = "demo\\example"
user.Leverage = 100
user.FirstName = "John"
user.LastName = "Smith"
# add a user to the server
if not manager.UserAdd(user,"1Ar#pqkj","1Ar#pqkj"):
# adding failed with an error
error = MT5Manager.LastError()
# no more logins
if error[1] == MT5Manager.EnMTAPIRetcode.MT_RET_USR_LOGIN_EXHAUSTED:
print("No free logins on server")
# add a user to another server
elif error[1] == MT5Manager.EnMTAPIRetcode.MT_RET_USR_LOGIN_PROHIBITED:
print("Can't add user for non current server")
# such a user already exists
elif error[1] == MT5Manager.EnMTAPIRetcode.MT_RET_USR_LOGIN_EXIST:
print("User with same login already exists")
# another error
else:
print(f"User was not added: {MT5Manager.LastError()}")
else:
# user added successfully
print(f"User {user.Login} was added")
# disconnect from the server
manager.Disconnect()
else:
# failed to connect to the server
print(f"Failed to connect to server: {MT5Manager.LastError()}")
I’m trying to create a new user account on the MT5 server using the following Python code, but it’s not working as expected. The connection to the server seems to succeed, but the user creation process either fails or does not return the expected result.
Here is the full code I’m using:
import logging
from MT5Manager import ManagerAPI
import time
# Logging setup
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
MT5_SERVER_ADDRESS = "***"
MT5_LOGIN_ID = 1011
MT5_PASSWORD = "***"
def connect_to_mt5():
"""Connect to the MT5 server with detailed debugging."""
manager = ManagerAPI()
try:
logger.info("Attempting to connect to the MT5 server...")
response = manager.Connect(MT5_SERVER_ADDRESS, MT5_LOGIN_ID, MT5_PASSWORD, 2, 1000000)
if response:
logger.info("Successfully connected to the MT5 server.")
return manager
else:
logger.error("Failed to connect to the MT5 server. Raw response: %s", response)
return None
except Exception as e:
logger.exception("Exception occurred during connection to the MT5 server.")
return None
def add_user(manager, pass_main, pass_investor, group, **kwargs):
"""Create a user account on the MT5 server with minimal data."""
try:
logger.info("Preparing user creation request...")
user_request = {
"pass_main": pass_main, # Main password
"pass_investor": pass_investor, # Investor password
"group": group, # Group name
"name": kwargs.get("name", "Propiy"), # Optional name
"city": kwargs.get("city", "website"), # Optional city
"state": kwargs.get("state", "website"), # Optional state
"country": kwargs.get("country", "website"), # Optional country
"zipcode": kwargs.get("zipcode", "1470"), # Optional zipcode
}
logger.debug("User request data: %s", user_request)
logger.info("Sending user creation request to the MT5 server...")
result = manager.UserAdd(user_request)
logger.debug(f"Raw UserAdd response: {result}")
if result == 0:
logger.info("User creation request succeeded.")
# Retrieve and inspect all users
logins = manager.UserLogins()
if logins:
logger.info("Retrieved logins: %s", logins)
for login in logins:
user_details = manager.UserGet({"Login": login})
logger.debug(f"Retrieved user details: {user_details}")
# Match user details
if user_details and user_details.get("Name") == user_request["name"]:
logger.info(f"Successfully located created user with Login ID: {user_details['Login']}")
return user_details["Login"]
logger.error("Failed to locate the created user in the retrieved list.")
else:
logger.error(f"User creation failed. Server returned: {result}")
return None
except Exception as e:
logger.exception("Exception occurred during user creation.")
return None
if __name__ == "__main__":
try:
logger.info("Starting the MT5 user creation script...")
manager = connect_to_mt5()
if manager:
# Add a delay to ensure the server has stabilized between connections
time.sleep(2)
# Minimal user info for testing
pass_main = "Test123!"
pass_investor = "forex-hedge"
group = "1" # Replace with the target group
# Attempt to create the user
login_id = add_user(manager, pass_main, pass_investor, group)
if login_id:
logger.info(f"User created successfully with Login ID: {login_id}")
else:
logger.error("Failed to create the user.")
# Disconnect from the server
logger.info("Disconnecting from the MT5 server...")
manager.Disconnect()
logger.info("Disconnected successfully.")
else:
logger.error("Could not establish a connection to the MT5 server.")
except Exception as main_exception:
logger.exception("An unexpected error occurred during execution.")
and I get this result
2024-11-18 15:44:10,428 - INFO - Starting the MT5 user creation script...
2024-11-18 15:44:10,451 - INFO - Attempting to connect to the MT5 server...
2024-11-18 15:44:10,583 - INFO - Successfully connected to the MT5 server.
2024-11-18 15:44:12,584 - INFO - Preparing user creation request...
2024-11-18 15:44:12,584 - DEBUG - User request data: {'pass_main': 'Test123!', 'pass_investor': 'forex-hedge', 'group': '1', 'name': 'Propiy', 'city': 'website', 'state': 'website', 'country': 'website', 'zipcode': '1470'}
2024-11-18 15:44:12,584 - INFO - Sending user creation request to the MT5 server...
2024-11-18 15:44:12,584 - DEBUG - Raw UserAdd response: False
2024-11-18 15:44:12,584 - INFO - User creation request succeeded.
2024-11-18 15:44:12,584 - ERROR - Failed to locate the created user in the retrieved list.
2024-11-18 15:44:12,585 - ERROR - Failed to create the user.
2024-11-18 15:44:12,585 - INFO - Disconnecting from the MT5 server...
2024-11-18 15:44:12,594 - INFO - Disconnected successfully.
The code seems to connect to the MT5 server successfully, but either the UserAdd function fails or the created user cannot be found using UserLogins. what's is wrong with code?
I’m trying to create a new user account on the MT5 server using the following Python code, but it’s not working as expected. The connection to the server seems to succeed, but the user creation process either fails or does not return the expected result.
Here is the full code I’m using:
import logging
from MT5Manager import ManagerAPI
import time
# Logging setup
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
MT5_SERVER_ADDRESS = "***"
MT5_LOGIN_ID = 1011
MT5_PASSWORD = "***"
def connect_to_mt5():
"""Connect to the MT5 server with detailed debugging."""
manager = ManagerAPI()
try:
logger.info("Attempting to connect to the MT5 server...")
response = manager.Connect(MT5_SERVER_ADDRESS, MT5_LOGIN_ID, MT5_PASSWORD, 2, 1000000)
if response:
logger.info("Successfully connected to the MT5 server.")
return manager
else:
logger.error("Failed to connect to the MT5 server. Raw response: %s", response)
return None
except Exception as e:
logger.exception("Exception occurred during connection to the MT5 server.")
return None
def add_user(manager, pass_main, pass_investor, group, **kwargs):
"""Create a user account on the MT5 server with minimal data."""
try:
logger.info("Preparing user creation request...")
user_request = {
"pass_main": pass_main, # Main password
"pass_investor": pass_investor, # Investor password
"group": group, # Group name
"name": kwargs.get("name", "Propiy"), # Optional name
"city": kwargs.get("city", "website"), # Optional city
"state": kwargs.get("state", "website"), # Optional state
"country": kwargs.get("country", "website"), # Optional country
"zipcode": kwargs.get("zipcode", "1470"), # Optional zipcode
}
logger.debug("User request data: %s", user_request)
logger.info("Sending user creation request to the MT5 server...")
result = manager.UserAdd(user_request)
logger.debug(f"Raw UserAdd response: {result}")
if result == 0:
logger.info("User creation request succeeded.")
# Retrieve and inspect all users
logins = manager.UserLogins()
if logins:
logger.info("Retrieved logins: %s", logins)
for login in logins:
user_details = manager.UserGet({"Login": login})
logger.debug(f"Retrieved user details: {user_details}")
# Match user details
if user_details and user_details.get("Name") == user_request["name"]:
logger.info(f"Successfully located created user with Login ID: {user_details['Login']}")
return user_details["Login"]
logger.error("Failed to locate the created user in the retrieved list.")
else:
logger.error(f"User creation failed. Server returned: {result}")
return None
except Exception as e:
logger.exception("Exception occurred during user creation.")
return None
if __name__ == "__main__":
try:
logger.info("Starting the MT5 user creation script...")
manager = connect_to_mt5()
if manager:
# Add a delay to ensure the server has stabilized between connections
time.sleep(2)
# Minimal user info for testing
pass_main = "Test123!"
pass_investor = "forex-hedge"
group = "1" # Replace with the target group
# Attempt to create the user
login_id = add_user(manager, pass_main, pass_investor, group)
if login_id:
logger.info(f"User created successfully with Login ID: {login_id}")
else:
logger.error("Failed to create the user.")
# Disconnect from the server
logger.info("Disconnecting from the MT5 server...")
manager.Disconnect()
logger.info("Disconnected successfully.")
else:
logger.error("Could not establish a connection to the MT5 server.")
except Exception as main_exception:
logger.exception("An unexpected error occurred during execution.")
and I get this result
2024-11-18 15:44:10,428 - INFO - Starting the MT5 user creation script...
2024-11-18 15:44:10,451 - INFO - Attempting to connect to the MT5 server...
2024-11-18 15:44:10,583 - INFO - Successfully connected to the MT5 server.
2024-11-18 15:44:12,584 - INFO - Preparing user creation request...
2024-11-18 15:44:12,584 - DEBUG - User request data: {'pass_main': 'Test123!', 'pass_investor': 'forex-hedge', 'group': '1', 'name': 'Propiy', 'city': 'website', 'state': 'website', 'country': 'website', 'zipcode': '1470'}
2024-11-18 15:44:12,584 - INFO - Sending user creation request to the MT5 server...
2024-11-18 15:44:12,584 - DEBUG - Raw UserAdd response: False
2024-11-18 15:44:12,584 - INFO - User creation request succeeded.
2024-11-18 15:44:12,584 - ERROR - Failed to locate the created user in the retrieved list.
2024-11-18 15:44:12,585 - ERROR - Failed to create the user.
2024-11-18 15:44:12,585 - INFO - Disconnecting from the MT5 server...
2024-11-18 15:44:12,594 - INFO - Disconnected successfully.
The code seems to connect to the MT5 server successfully, but either the UserAdd function fails or the created user cannot be found using UserLogins. what's is wrong with code?
Share Improve this question asked Nov 18, 2024 at 15:57 Omid GoudaziOmid Goudazi 1902 silver badges9 bronze badges1 Answer
Reset to default 0use this code
# include the library
import MT5Manager
# create manager interface
manager = MT5Manager.ManagerAPI()
# connect the server
if manager.Connect("192.168.1.100:443", 1002, "1Ar#pqkj", 0):
# create a user
user = MT5Manager.MTUser(manager)
# fill in the required fields: group, leverage, first and last name
user.Group = "demo\\example"
user.Leverage = 100
user.FirstName = "John"
user.LastName = "Smith"
# add a user to the server
if not manager.UserAdd(user,"1Ar#pqkj","1Ar#pqkj"):
# adding failed with an error
error = MT5Manager.LastError()
# no more logins
if error[1] == MT5Manager.EnMTAPIRetcode.MT_RET_USR_LOGIN_EXHAUSTED:
print("No free logins on server")
# add a user to another server
elif error[1] == MT5Manager.EnMTAPIRetcode.MT_RET_USR_LOGIN_PROHIBITED:
print("Can't add user for non current server")
# such a user already exists
elif error[1] == MT5Manager.EnMTAPIRetcode.MT_RET_USR_LOGIN_EXIST:
print("User with same login already exists")
# another error
else:
print(f"User was not added: {MT5Manager.LastError()}")
else:
# user added successfully
print(f"User {user.Login} was added")
# disconnect from the server
manager.Disconnect()
else:
# failed to connect to the server
print(f"Failed to connect to server: {MT5Manager.LastError()}")
本文标签: forexUnable to Create User Account with MT5Manager in PythonStack Overflow
版权声明:本文标题:forex - Unable to Create User Account with MT5Manager in Python - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745609648a2158928.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论