### Install MetaApi Cloud SDK Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/README.rst Install the MetaApi Cloud SDK using pip. This command installs the necessary package for interacting with the MetaApi services. ```bash pip install metaapi-cloud-sdk ``` -------------------------------- ### Get Provisioning Profiles (Classic Pagination) Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves provisioning profiles with classic pagination, providing total count and items. ```APIDOC ## Get Provisioning Profiles (Classic Pagination) ### Description Retrieves provisioning profiles using classic pagination, which includes the total count of matching profiles and a list of items. ### Method GET (implied by `get_provisioning_profiles_with_classic_pagination`) ### Endpoint `/provisioning-profiles` (implied) ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of profiles to return per page. - **offset** (integer) - Optional - The number of profiles to skip. - **query** (string) - Optional - A search query to filter profiles by name. - **version** (integer) - Optional - The MetaTrader version to filter by. ### Request Example ```python provisioningProfiles = await api.provisioning_profile_api.get_provisioning_profiles_with_classic_pagination({ 'limit': 10, 'offset': 0, 'query': 'ICMarketsSC-MT5', 'version': 5 }) print(provisioningProfiles['count']) ``` ### Response #### Success Response (200) - **items** (array) - A list of provisioning profile objects. - **count** (integer) - The total number of provisioning profiles matching the filter. ``` -------------------------------- ### Create Market Buy Order with Error Handling Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Example of creating a market buy order and handling potential exceptions. The result object contains 'stringCode' and 'numericCode' for extra information. ```python result = await connection.create_market_buy_order(symbol='GBPUSD', volume=0.07, stop_loss=0.9, take_profit=2.0, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) print('Trade successful, result code is ' + result['stringCode']) ``` ```python # catch and output exception try: await connection.create_market_buy_order(symbol='GBPUSD', volume=0.07, stop_loss=0.9, take_profit=2.0, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'}) except Exception as err: print(api.format_error(err)) ``` -------------------------------- ### Threshold Trailing Stop Loss Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst This example demonstrates setting up a threshold-based trailing stop loss for a market buy order. It uses absolute price thresholds and specifies a stop price base. ```python print(await connection.create_market_buy_order('GBPUSD', 0.07, 0.9, 2.0, { 'trailingStopLoss': { 'threshold': { 'thresholds': [ { 'threshold': 1.3, 'stopLoss': 1.1 } ], 'units': 'ABSOLUTE_PRICE', 'stopPriceBase': 'CURRENT_PRICE' } } })) ``` -------------------------------- ### Get Provisioning Profiles (Infinite Scroll) Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves provisioning profiles with infinite scroll pagination, allowing filtering. ```APIDOC ## Get Provisioning Profiles (Infinite Scroll) ### Description Retrieves provisioning profiles using infinite scroll pagination. Supports filtering by name and version. ### Method GET (implied by `get_provisioning_profiles_with_infinite_scroll_pagination`) ### Endpoint `/provisioning-profiles` (implied) ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of profiles to return per page. - **offset** (integer) - Optional - The number of profiles to skip. - **query** (string) - Optional - A search query to filter profiles by name. - **version** (integer) - Optional - The MetaTrader version to filter by. ### Request Example ```python provisioningProfiles = await api.provisioning_profile_api.get_provisioning_profiles_with_infinite_scroll_pagination({ 'limit': 10, 'offset': 0, 'query': 'ICMarketsSC-MT5', 'version': 5 }) ``` ### Response #### Success Response (200) - **provisioningProfiles** (array) - A list of provisioning profile objects. ``` -------------------------------- ### Get Provisioning Profile by ID Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a specific provisioning profile by its unique ID. ```APIDOC ## Get Provisioning Profile by ID ### Description Retrieves a single provisioning profile using its unique identifier. ### Method GET (implied by `get_provisioning_profile`) ### Endpoint `/provisioning-profiles/{profileId}` (implied) ### Parameters #### Path Parameters - **profileId** (string) - Required - The ID of the provisioning profile to retrieve. ### Response #### Success Response (200) - **provisioningProfile** (object) - The provisioning profile object. ``` -------------------------------- ### Distance Trailing Stop Loss Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst This example demonstrates how to set up a distance-based trailing stop loss for a market buy order. The distance is specified in relative points. ```python print(await connection.create_market_buy_order('GBPUSD', 0.07, 0.9, 2.0, { 'trailingStopLoss': { 'distance': { 'distance': 200, 'units': 'RELATIVE_POINTS' } } })) ``` -------------------------------- ### Get Access Rules Manifest Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/tokenManagementApi.rst Retrieves the full list of available access rule elements for detailed token management. This is useful for understanding the scope of permissions that can be applied to tokens. ```APIDOC ## Get Access Rules Manifest ### Description Retrieves the full list of available access rule elements for detailed token management. ### Method GET (Implied by SDK method call) ### Endpoint Not explicitly defined, SDK method abstracts this. ### Parameters None ### Request Example ```python manifest = await api.token_management_api.get_access_rules() ``` ### Response #### Success Response (200) - **manifest** (object) - An object containing the access rules manifest. ``` -------------------------------- ### Get Access Rules Manifest with MetaAPI Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/tokenManagementApi.rst Use the `get_access_rules` method to retrieve the full list of available access rule elements for detailed token management. This is useful for understanding the scope of permissions. ```python manifest = await api.token_management_api.get_access_rules() ``` -------------------------------- ### Get Accounts with Classic Scroll Pagination Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a list of MetaTrader accounts with classic scroll pagination. Allows filtering by query, state, limit, and offset. ```APIDOC ## GET /v1/accounts ### Description Retrieves a list of MetaTrader accounts using classic scroll pagination. Supports filtering and pagination. ### Method GET ### Endpoint /v1/accounts ### Parameters #### Query Parameters - **accounts_filter** (object) - Optional - Filter criteria for accounts. - **limit** (integer) - Optional - The maximum number of accounts to return per page. Defaults to 1000. - **offset** (integer) - Optional - The number of accounts to skip. Defaults to 0. - **query** (string) - Optional - A query string to search for accounts (e.g., by server name). - **state** (array of strings) - Optional - An array of account states to filter by (e.g., ['DEPLOYED']). ### Response #### Success Response (200) - **items** (array) - A list of account objects matching the filter. - Each item contains account details like id, name, type, login, server, state, etc. - **count** (integer) - The total number of accounts matching the filter (without pagination). ### Response Example ```json { "items": [ { "id": "accountId1", "name": "Trading account #1", "type": "cloud", "login": "1234567", "server": "ICMarketsSC-Demo", "state": "DEPLOYED" } ], "count": 100 } ``` ``` -------------------------------- ### Get Accounts with Infinite Scroll Pagination Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a list of MetaTrader accounts with infinite scroll pagination. Allows filtering by query, state, limit, and offset. ```APIDOC ## GET /v1/accounts ### Description Retrieves a list of MetaTrader accounts using infinite scroll pagination. Supports filtering and pagination. ### Method GET ### Endpoint /v1/accounts ### Parameters #### Query Parameters - **accounts_filter** (object) - Optional - Filter criteria for accounts. - **limit** (integer) - Optional - The maximum number of accounts to return per page. Defaults to 1000. - **offset** (integer) - Optional - The number of accounts to skip. Defaults to 0. - **query** (string) - Optional - A query string to search for accounts (e.g., by server name). - **state** (array of strings) - Optional - An array of account states to filter by (e.g., ['DEPLOYED']). ### Response #### Success Response (200) - **items** (array) - A list of account objects matching the filter. - Each item contains account details like id, name, type, login, server, state, etc. - **count** (integer) - The total number of accounts matching the filter (without pagination). ### Response Example ```json { "items": [ { "id": "accountId1", "name": "Trading account #1", "type": "cloud", "login": "1234567", "server": "ICMarketsSC-Demo", "state": "DEPLOYED" } ], "count": 100 } ``` ``` -------------------------------- ### Create Provisioning Profile Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Creates a new provisioning profile for a broker. This is required before creating an account if automatic broker settings detection fails. For MT5, a 'servers.dat' file is required; for MT4, an '.srv' file is needed. ```python # if you do not have created a provisioning profile for your broker, # you should do it before creating an account provisioningProfile = await api.provisioning_profile_api.create_provisioning_profile(profile={ 'name': 'My profile', 'version': 5, 'brokerTimezone': 'EET', 'brokerDSTSwitchTimezone': 'EET' }) # servers.dat file is required for MT5 profile and can be found inside # config directory of your MetaTrader terminal data folder. It contains # information about available broker servers await provisioningProfile.upload_file(file_name='servers.dat', file='/path/to/servers.dat') # for MT4, you should upload an .srv file instead await provisioningProfile.upload_file(file_name='broker.srv', file='/path/to/broker.srv') ``` -------------------------------- ### Get Expert Advisor by ID Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a specific expert advisor by its unique ID. ```APIDOC ## Get Expert Advisor by ID ### Description Retrieves a specific expert advisor using its unique identifier. ### Method GET (implied by `get_expert_advisor`) ### Endpoint `/accounts/{accountId}/experts/{expertId}` (implied) ### Parameters #### Path Parameters - **accountId** (string) - Required - The ID of the account. - **expertId** (string) - Required - The ID of the expert advisor to retrieve. ### Response #### Success Response (200) - **expert** (object) - The expert advisor object. ``` -------------------------------- ### Create MetaTrader Account with Provisioning Profile Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Use this method to create a MetaTrader account when automatic broker settings detection fails. It requires a provisioning profile ID. ```python account = await api.metatrader_account_api.create_account(account={ 'name': 'Trading account #1', 'type': 'cloud', 'login': '1234567', # password can be investor password for read-only access 'password': 'qwerty', 'server': 'ICMarketsSC-Demo', 'provisioningProfileId': provisioningProfile.id, 'magic': 123456, 'quoteStreamingIntervalInSeconds': 2.5, # set to 0 to receive quote per tick 'reliability': 'high' # set this field to 'high' value if you want to increase uptime of your account (recommended for production environments) }) ``` -------------------------------- ### Get Expert Advisors Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a list of all existing expert advisors associated with the account. ```APIDOC ## Get Expert Advisors ### Description Retrieves a list of all expert advisors configured for the account. ### Method GET (implied by `get_expert_advisors`) ### Endpoint `/accounts/{accountId}/experts` (implied) ### Parameters #### Path Parameters - **accountId** (string) - Required - The ID of the account to retrieve expert advisors from. ### Response #### Success Response (200) - **experts** (array) - A list of expert advisor objects. ``` -------------------------------- ### Create MetaTrader Account for End-User Configuration Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Create an account in a DRAFT state, allowing an end-user to configure it later via a generated link. This is useful when login and password are not initially provided. ```python account = await api.metatrader_account_api.create_account(account={ 'name': 'Trading account #1', 'type': 'cloud', 'server': 'ICMarketsSC-Demo', 'provisioningProfileId': provisioningProfile.id, 'application': 'MetaApi', 'magic': 123456, 'quoteStreamingIntervalInSeconds': 2.5, # set to 0 to receive quote per tick 'reliability': 'high' # set this field to 'high' value if you want to increase uptime of your account (recommended for production environments) }) configuration_link = await account.create_configuration_link(ttl_in_days=7) ``` -------------------------------- ### Create Market Buy Order with Result Check Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst This snippet demonstrates creating a market buy order and then checking the 'stringCode' from the result for success. ```python result = await connection.create_market_buy_order(symbol='GBPUSD', volume=0.07, stop_loss=0.9, take_profit=2.0, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) print('Trade successful, result code is ' + result['stringCode']) ``` -------------------------------- ### Get Account by ID Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a specific MetaTrader account by its unique account ID. ```APIDOC ## GET /v1/accounts/{accountId} ### Description Retrieves a specific MetaTrader account by its unique account ID. ### Method GET ### Endpoint /v1/accounts/{accountId} ### Parameters #### Path Parameters - **accountId** (string) - Required - The ID of the account to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the account. - **name** (string) - The name of the trading account. - **type** (string) - The type of account. - **login** (string) - The trading account login. - **server** (string) - The MetaTrader server address. - **state** (string) - The current state of the account. ``` -------------------------------- ### Connect to MetaApi Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/README.rst Instantiate the MetaApi class with your API token to establish a connection. Ensure you have obtained a valid token from the MetaApi web UI. ```python from metaapi_cloud_sdk import MetaApi token = '...' api = MetaApi(token=token) ``` -------------------------------- ### Retrieve Provisioning Profiles with Classic Pagination Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves provisioning profiles using classic pagination, which allows for calculating the total page count. Supports filtering and returns a dictionary containing 'items' and 'count'. ```python # filter and paginate profiles, see doc for full list of filter options available provisioningProfiles = await api.provisioning_profile_api.get_provisioning_profiles_with_classic_pagination({ 'limit': 10, 'offset': 0, 'query': 'ICMarketsSC-MT5', # searches over name 'version': 5 }) provisioningProfile = None for profile in provisioningProfiles['items']: if profile.id == 'profileId': provisioningProfile = profile break # number of all profiles matching filter without pagination options print(provisioningProfiles['count']) # get profiles without filter (returns 1000 profiles max) provisioningProfiles = await api.provisioning_profile_api.get_provisioning_profiles_with_classic_pagination() ``` -------------------------------- ### Create Account with Provisioning Profile Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Creates a MetaTrader account using a provisioning profile. This is useful when automatic detection fails and you have a pre-configured profile. ```APIDOC ## POST /v1/accounts ### Description Creates a MetaTrader account using a provisioning profile. ### Method POST ### Endpoint /v1/accounts ### Parameters #### Request Body - **account** (object) - Required - Account configuration details. - **name** (string) - Required - The name of the trading account. - **type** (string) - Required - The type of account ('cloud' or 'local'). - **login** (string) - Required - The trading account login. - **password** (string) - Required - The trading account password (can be investor password for read-only access). - **server** (string) - Required - The MetaTrader server address. - **provisioningProfileId** (string) - Required - The ID of the provisioning profile to use. - **magic** (integer) - Optional - The magic number for the account. - **quoteStreamingIntervalInSeconds** (float) - Optional - The interval in seconds for receiving quote updates. Set to 0 for tick-by-tick quotes. - **reliability** (string) - Optional - The reliability setting for the account ('high' recommended for production). ### Request Example ```json { "account": { "name": "Trading account #1", "type": "cloud", "login": "1234567", "password": "qwerty", "server": "ICMarketsSC-Demo", "provisioningProfileId": "provisioningProfileId", "magic": 123456, "quoteStreamingIntervalInSeconds": 2.5, "reliability": "high" } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created account. - **name** (string) - The name of the trading account. - **type** (string) - The type of account. - **login** (string) - The trading account login. - **server** (string) - The MetaTrader server address. - **provisioningProfileId** (string) - The ID of the provisioning profile used. - **magic** (integer) - The magic number for the account. - **quoteStreamingIntervalInSeconds** (float) - The interval for quote updates. - **reliability** (string) - The reliability setting. - **state** (string) - The current state of the account (e.g., 'DEPLOYED', 'DRAFT'). ``` -------------------------------- ### Create MT5 Demo Account Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Create a MetaTrader 5 demo account with specified details. An optional provisioning profile ID can be provided if the server file is not found by server name. ```python demo_account = await api.metatrader_demo_account_api.create_mt5_demo_account( account={ 'accountType': 'type', 'balance': 100000, 'email': 'example@example.com', 'leverage': 100, 'serverName': 'ICMarketsSC-Demo', 'keywords': ["Raw Trading Ltd"] }) # optionally specify a provisioning profile id if servers file is not found by server name demo_account = await api.metatrader_account_generator_api.create_mt5_demo_account( account={ 'accountType': 'type', 'balance': 100000, 'email': 'example@example.com', 'leverage': 100, 'serverName': 'Example-Server', 'name': 'Test User', 'phone': '+12345678901' }, profile_id=provisioningProfile.id) ``` -------------------------------- ### Create MetaTrader Account with Auto Broker Settings Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Use this snippet to create a MetaTrader account by automatically detecting broker settings. Ensure you handle potential exceptions related to server discovery, authentication, or settings detection. ```python try: account = await api.metatrader_account_api.create_account(account={ 'name': 'Trading account #1', 'type': 'cloud', 'login': '1234567', 'platform': 'mt4', # password can be investor password for read-only access 'password': 'qwerty', 'server': 'ICMarketsSC-Demo', 'magic': 123456, 'keywords': ["Raw Trading Ltd"], 'quoteStreamingIntervalInSeconds': 2.5, # set to 0 to receive quote per tick 'reliability': 'high' # set this field to 'high' value if you want to increase uptime of your account (recommended for production environments) }) except Exception as err: # process errors if hasattr(err, 'details'): # returned if the server file for the specified server name has not been found # recommended to check the server name or create the account using a provisioning profile if err.details == 'E_SRV_NOT_FOUND': print(err) # returned if the server has failed to connect to the broker using your credentials # recommended to check your login and password elif err.details == 'E_AUTH': print(err) # returned if the server has failed to detect the broker settings # recommended to try again later or create the account using a provisioning profile elif err.details == 'E_SERVER_TIMEZONE': print(err) ``` -------------------------------- ### Configure Equity Tracking with MetaApi Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/riskManagement.rst Set up equity tracking by enabling the riskManagementApiEnabled field for MetaApi MetaTrader accounts and creating trackers with specified parameters. This snippet demonstrates creating, retrieving, updating, and deleting trackers. ```python from metaapi_cloud_sdk import MetaApi, RiskManagement token = '...' metaapi = MetaApi(token=token) risk_management = RiskManagement(token=token) # retrieve MetaApi MetaTrader accounts with riskManagementApiEnabled field set to true account = await api.metatrader_account_api.get_account(account_id='accountId') if not account.risk_management_api_enabled: raise Exception('Please set riskManagementApiEnabled field to true in your MetaApi account in ' 'order to use it in RiskManagement API') risk_management_api = risk_management.risk_management_api # create a tracker tracker_id = await risk_management_api.create_tracker('accountId', { 'name': 'Test tracker', 'period': 'day', 'absoluteDrawdownThreshold': 100 }) # retrieve list of trackers print(await risk_management_api.get_trackers('accountId')) # retrieve a tracker by id print(await risk_management_api.get_tracker('accountId', 'trackerId')) # update a tracker print(await risk_management_api.update_tracker('accountId', tracker_id['id'], {'name': 'Updated name'})) # remove a tracker print(await risk_management_api.delete_tracker('accountId', tracker_id['id'])) ``` -------------------------------- ### Retrieve Provisioning Profiles with Infinite Scroll Pagination Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves provisioning profiles using infinite scroll pagination. Supports filtering by name, version, and other options. If no filter is applied, it returns up to 1000 profiles. ```python # filter and paginate profiles, see doc for full list of filter options available provisioningProfiles = await api.provisioning_profile_api.get_provisioning_profiles_with_infinite_scroll_pagination({ 'limit': 10, 'offset': 0, 'query': 'ICMarketsSC-MT5', # searches over name 'version': 5 }) # get profiles without filter (returns 1000 profiles max) provisioningProfiles = await api.provisioning_profile_api.get_provisioning_profiles_with_infinite_scroll_pagination() provisioningProfile = None for profile in provisioningProfiles: if profile.id == 'profileId': provisioningProfile = profile break ``` -------------------------------- ### Query Historical Market Data via RPC API Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Retrieve historical candle or tick data for a given symbol and timeframe. This API is currently supported on G1 accounts only. Specify start time and limit for data retrieval. ```python from datetime import datetime # retrieve 1000 candles before the specified time candles = await account.get_historical_candles(symbol='EURUSD', timeframe='1m', start_time=datetime.fromisoformat('2021-05-01'), limit=1000) # retrieve 1000 ticks after the specified time ticks = await account.get_historical_ticks(symbol='EURUSD', start_time=datetime.fromisoformat('2021-05-01'), offset=5, limit=1000) # retrieve 1000 latest ticks ticks = await account.get_historical_ticks(symbol='EURUSD', start_time=None, offset=0, limit=1000) ``` -------------------------------- ### Create Limit Buy Order with Expiration Settings Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Demonstrates creating limit buy orders with different expiration settings. ORDER_TIME_GTC is applied by default. Use ORDER_TIME_SPECIFIED for a precise expiration time or ORDER_TIME_SPECIFIED_DAY for expiration at the end of a specific day. ```python print(await connection.create_limit_buy_order('GBPUSD', 0.07, 1.0, 0.9, 2.0)) ``` ```python print(await connection.create_limit_buy_order( 'GBPUSD', 0.07, 1.0, 0.9, 2.0, { 'expiration': { 'type': 'ORDER_TIME_SPECIFIED', 'time': datetime.now() + timedelta(days=1) } } )) ``` ```python print(await connection.create_limit_buy_order( 'GBPUSD', 0.07, 1.0, 0.9, 2.0, { 'expiration': { 'type': 'ORDER_TIME_SPECIFIED_DAY', 'time': datetime.now() + timedelta(days=1) } } )) ``` ```python print(await connection.create_limit_buy_order( 'GBPUSD', 0.07, 1.0, 0.9, 2.0, { 'expiration': { 'type': 'ORDER_TIME_SPECIFIED_DAY', 'time': datetime.now() + timedelta(days=1) } } )) ``` -------------------------------- ### Handle Order Creation Exception Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst This snippet shows how to use a try-except block to catch and print any exceptions that occur during order creation. ```python try: await connection.create_market_buy_order(symbol='GBPUSD', volume=0.07, stop_loss=0.9, take_profit=2.0, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'}) except Exception as err: print(api.format_error(err)) ``` -------------------------------- ### Create Provisioning Profile Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Creates a new provisioning profile for a broker, which can be used for account creation. ```APIDOC ## Create Provisioning Profile ### Description Creates a new provisioning profile for a broker. This is useful when automatic broker settings detection fails. ### Method POST (implied by `create_provisioning_profile` and `upload_file` calls) ### Endpoint `/provisioning-profiles` (implied) ### Parameters #### Request Body - **profile** (object) - Required - The details of the provisioning profile. - **name** (string) - Required - The name of the profile. - **version** (integer) - Required - The MetaTrader version (e.g., 5 for MT5). - **brokerTimezone** (string) - Required - The timezone of the broker. - **brokerDSTSwitchTimezone** (string) - Required - The timezone for Daylight Saving Time switches. ### Request Example ```python provisioningProfile = await api.provisioning_profile_api.create_provisioning_profile(profile={ 'name': 'My profile', 'version': 5, 'brokerTimezone': 'EET', 'brokerDSTSwitchTimezone': 'EET' }) ``` ### File Upload - **file_name** (string) - Required - The name of the file to upload (e.g., 'servers.dat' for MT5, 'broker.srv' for MT4). - **file** (string) - Required - The path to the file on the local system. ``` -------------------------------- ### Create Limit Buy Order Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Use this to create a limit buy order. Specify open price, stop loss, and take profit levels. ```python print(await connection.create_limit_buy_order(symbol='GBPUSD', volume=0.07, open_price=1.0, stop_loss=0.9, take_profit=2.0, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) ``` -------------------------------- ### Create MT4 Demo Account Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Create a MetaTrader 4 demo account with specified details. An optional provisioning profile ID can be provided if the server file is not found by server name. ```python demo_account = await api.metatrader_account_generator_api.create_mt4_demo_account( account={ 'balance': 100000, 'accountType': 'type', 'email': 'example@example.com', 'leverage': 100, 'serverName': 'Example-Server', 'name': 'Test User', 'phone': '+12345678901', 'keywords': ["Example Broker Ltd"] }) # optionally specify a provisioning profile id if servers file is not found by server name demo_account = await api.metatrader_account_generator_api.create_mt4_demo_account( account={ 'balance': 100000, 'accountType': 'type', 'email': 'example@example.com', 'leverage': 100, 'serverName': 'Example-Server', 'name': 'Test User', 'phone': '+12345678901' }, profile_id=provisioningProfile.id) ``` -------------------------------- ### Error Response: Server File Not Found Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst This JSON object represents an error where the server file for the specified broker could not be found. It suggests checking the server name or using a provisioning profile. ```json { "id": 3, "error": "ValidationError", "message": "We were unable to retrieve the server file for this broker. Please check the server name or configure the provisioning profile manually.", "details": "E_SRV_NOT_FOUND" } ``` -------------------------------- ### Close Positions and Orders with MetaAPI Python SDK Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Demonstrates various methods for closing positions and orders using the MetaAPI Python SDK. Ensure you have a valid connection object. ```python print(await connection.close_position_partially(position_id='46870472', volume=0.9)) ``` ```python print(await connection.close_position(position_id='46870472')) ``` ```python print(await connection.close_by(position_id='46870472', opposite_position_id='46870482')) ``` ```python print(await connection.close_positions_by_symbol(symbol='EURUSD')) ``` ```python print(await connection.modify_order(order_id='46870472', open_price=1.0, stop_loss=2.0, take_profit=0.9)) ``` ```python print(await connection.cancel_order(order_id='46870472')) ``` -------------------------------- ### Create Limit Buy Order with Specified Expiration Time Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Creates a limit buy order that will be canceled at a specified time, one day from the current time. Requires importing datetime and timedelta. ```python # specified expiration time print(await connection.create_limit_buy_order( 'GBPUSD', 0.07, 1.0, 0.9, 2.0, { 'expiration': { 'type': 'ORDER_TIME_SPECIFIED', 'time': datetime.now() + timedelta(days=1) } } )) ``` -------------------------------- ### Create Account for User Configuration Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Creates a MetaTrader account in a DRAFT state, allowing a user to later configure it by providing login and password via a generated link. ```APIDOC ## POST /v1/accounts ### Description Creates a MetaTrader account in a DRAFT state, intended for end-user configuration. ### Method POST ### Endpoint /v1/accounts ### Parameters #### Request Body - **account** (object) - Required - Account configuration details. - **name** (string) - Required - The name of the trading account. - **type** (string) - Required - The type of account ('cloud' or 'local'). - **server** (string) - Required - The MetaTrader server address. - **provisioningProfileId** (string) - Optional - The ID of the provisioning profile to use. - **application** (string) - Required - The application name associated with the account. - **magic** (integer) - Optional - The magic number for the account. - **quoteStreamingIntervalInSeconds** (float) - Optional - The interval in seconds for receiving quote updates. Set to 0 for tick-by-tick quotes. - **reliability** (string) - Optional - The reliability setting for the account ('high' recommended for production). ### Request Example ```json { "account": { "name": "Trading account #1", "type": "cloud", "server": "ICMarketsSC-Demo", "provisioningProfileId": "provisioningProfileId", "application": "MetaApi", "magic": 123456, "quoteStreamingIntervalInSeconds": 2.5, "reliability": "high" } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created account. - **name** (string) - The name of the trading account. - **type** (string) - The type of account. - **server** (string) - The MetaTrader server address. - **provisioningProfileId** (string) - The ID of the provisioning profile used. - **application** (string) - The application name. - **magic** (integer) - The magic number for the account. - **quoteStreamingIntervalInSeconds** (float) - The interval for quote updates. - **reliability** (string) - The reliability setting. - **state** (string) - The current state of the account (should be 'DRAFT'). ### Related Operations - **create_configuration_link**: Generates a link for user configuration. ``` -------------------------------- ### Enable SDK Logging Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/logging.rst Call this static method before creating MetaApi instances to direct SDK logs to the Python logging library. The application is still responsible for configuring logging appenders and categories. ```python from metaapi_cloud_sdk import MetaApi MetaApi.enable_logging() meta_api = MetaApi(token) ``` -------------------------------- ### Create Market Sell Order Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Use this to create a market sell order. Ensure the connection object is properly initialized. ```python print(await connection.create_market_sell_order(symbol='GBPUSD', volume=0.07, stop_loss=2.0, take_profit=0.9, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) ``` -------------------------------- ### Create Expert Advisor Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Use this snippet to create a new expert advisor with specified parameters and upload its custom EA file. ```python expert = await account.create_expert_advisor(expert_id='expertId', expert={ 'period': '1h', 'symbol': 'EURUSD', 'preset': 'a2V5MT12YWx1ZTEKa2V5Mj12YWx1ZTIKa2V5Mz12YWx1ZTMKc3VwZXI9dHJ1ZQ' }) await expert.upload_file('/path/to/custom-ea') ``` -------------------------------- ### Create Stop Limit Buy Order Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Use this to create a stop limit buy order. Requires specifying open price, stop limit price, stop loss, and take profit. ```python print(await connection.create_stop_limit_buy_order(symbol='GBPUSD', volume=0.07, open_price=1.5, stop_limit_price=1.4, stop_loss=0.9, take_profit=2.0, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) ``` -------------------------------- ### Deploy Account Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Deploys a MetaTrader account, making it ready for trading operations. ```APIDOC ## POST /v1/accounts/{accountId}/deploy ### Description Deploys a MetaTrader account. ### Method POST ### Endpoint /v1/accounts/{accountId}/deploy ### Parameters #### Path Parameters - **accountId** (string) - Required - The ID of the account to deploy. ### Response #### Success Response (200) - Indicates successful deployment of the account. ``` -------------------------------- ### Create Stop Buy Order Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Use this to create a stop buy order. The open price should be set appropriately for a stop order. ```python print(await connection.create_stop_buy_order(symbol='GBPUSD', volume=0.07, open_price=1.5, stop_loss=2.0, take_profit=0.9, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) ``` -------------------------------- ### Create Limit Buy Order with Specified Expiration Day Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Creates a limit buy order that will be canceled at the end of a specified trade day, one day from the current time. Requires importing datetime and timedelta. ```python # specified expiration date print(await connection.create_limit_buy_order( 'GBPUSD', 0.07, 1.0, 0.9, 2.0, { 'expiration': { 'type': 'ORDER_TIME_SPECIFIED_DAY', 'time': datetime.now() + timedelta(days=1) } } )) ``` -------------------------------- ### Create Limit Sell Order Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Use this to create a limit sell order. Ensure all required parameters like open price, stop loss, and take profit are provided. ```python print(await connection.create_limit_sell_order(symbol='GBPUSD', volume=0.07, open_price=1.5, stop_loss=2.0, take_profit=0.9, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) ``` -------------------------------- ### Create Configuration Link Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Generates a unique link that a user can use to enter their trading account login and password or change the account password. ```APIDOC ## POST /{accountId}/create-configuration-link ### Description Generates a configuration link for a MetaTrader account that is in a DRAFT state. ### Method POST ### Endpoint /{accountId}/create-configuration-link ### Parameters #### Path Parameters - **accountId** (string) - Required - The ID of the account for which to create a configuration link. #### Query Parameters - **ttl_in_days** (integer) - Optional - The time-to-live for the link in days. Defaults to 7 days. ### Response #### Success Response (200) - **configurationLink** (string) - The generated URL for account configuration. ``` -------------------------------- ### Query Account Information, Positions, Orders, and History via RPC API Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Use this to retrieve account balance, equity, open positions, pending orders, and historical data. Ensure the RPC connection is established and synchronized before making calls. ```python connection = account.get_rpc_connection() await connection.connect() await connection.wait_synchronized() # retrieve balance and equity print(await connection.get_account_information()) # retrieve open positions print(await connection.get_positions()) # retrieve a position by id print(await connection.get_position(position_id='1234567')) # retrieve pending orders print(await connection.get_orders()) # retrieve a pending order by id print(await connection.get_order(order_id='1234567')) # retrieve history orders by ticket print(await connection.get_history_orders_by_ticket(ticket='1234567')) # retrieve history orders by position id print(await connection.get_history_orders_by_position(position_id='1234567')) # retrieve history orders by time range print(await connection.get_history_orders_by_time_range(start_time=start_time, end_time=end_time)) # retrieve history deals by ticket print(await connection.get_deals_by_ticket(ticket='1234567')) # retrieve history deals by position id print(await connection.get_deals_by_position(position_id='1234567')) # retrieve history deals by time range print(await connection.get_deals_by_time_range(start_time=start_time, end_time=end_time)) ``` -------------------------------- ### Retrieve Provisioning Profile by ID Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Retrieves a specific provisioning profile using its unique profile ID. ```python provisioningProfile = await api.provisioning_profile_api.get_provisioning_profile('profileId') ``` -------------------------------- ### Create Limit Buy Order Expiring End of Day Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Creates a limit buy order that will be canceled at the end of the current trade day, one day from the current time. Requires importing datetime and timedelta. ```python # expires at the end of the current day print(await connection.create_limit_buy_order( 'GBPUSD', 0.07, 1.0, 0.9, 2.0, { 'expiration': { 'type': 'ORDER_TIME_SPECIFIED_DAY', 'time': datetime.now() + timedelta(days=1) } } )) ``` -------------------------------- ### Update Provisioning Profile Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/managingAccounts.rst Updates an existing provisioning profile with new details and optionally uploads a new broker-specific file ('servers.dat' for MT5, '.srv' for MT4). ```python await provisioningProfile.update(profile={'name': 'New name'}) # for MT5, you should upload a servers.dat file await provisioningProfile.upload_file(file_name='servers.dat', file='/path/to/servers.dat') # for MT4, you should upload an .srv file instead await provisioningProfile.upload_file(file_name='broker.srv', file='/path/to/broker.srv') ``` -------------------------------- ### Query Account Information, Positions, Orders, and History Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst This section details how to retrieve various account-related data such as balance, equity, open positions, pending orders, and historical trades using the RPC connection. ```APIDOC ## Query Account Information, Positions, Orders, and History ### Description Access account information, open positions, pending orders, and historical trade data via the RPC API. ### Method RPC API calls through a `connection` object obtained from `account.get_rpc_connection()`. ### Endpoints - `connection.connect()` - `connection.wait_synchronized()` - `connection.get_account_information()` - `connection.get_positions()` - `connection.get_position(position_id: str)` - `connection.get_orders()` - `connection.get_order(order_id: str)` - `connection.get_history_orders_by_ticket(ticket: str)` - `connection.get_history_orders_by_position(position_id: str)` - `connection.get_history_orders_by_time_range(start_time: datetime, end_time: datetime)` - `connection.get_deals_by_ticket(ticket: str)` - `connection.get_deals_by_position(position_id: str)` - `connection.get_deals_by_time_range(start_time: datetime, end_time: datetime)` ### Request Example ```python connection = account.get_rpc_connection() await connection.connect() await connection.wait_synchronized() # retrieve balance and equity print(await connection.get_account_information()) # retrieve open positions print(await connection.get_positions()) # retrieve a position by id print(await connection.get_position(position_id='1234567')) # retrieve pending orders print(await connection.get_orders()) # retrieve a pending order by id print(await connection.get_order(order_id='1234567')) # retrieve history orders by ticket print(await connection.get_history_orders_by_ticket(ticket='1234567')) # retrieve history orders by position id print(await connection.get_history_orders_by_position(position_id='1234567')) # retrieve history orders by time range print(await connection.get_history_orders_by_time_range(start_time=start_time, end_time=end_time)) # retrieve history deals by ticket print(await connection.get_deals_by_ticket(ticket='1234567')) # retrieve history deals by position id print(await connection.get_deals_by_position(position_id='1234567')) # retrieve history deals by time range print(await connection.get_deals_by_time_range(start_time=start_time, end_time=end_time)) ``` ### Response Responses vary based on the method called. Typically returns dictionaries or lists of dictionaries containing account, position, order, or deal information. ``` -------------------------------- ### Create Stop Limit Sell Order Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/streamingApi.rst Use this to create a stop limit sell order. Requires open price, stop limit price, stop loss, and take profit. ```python print(await connection.create_stop_limit_sell_order(symbol='GBPUSD', volume=0.07, open_price=1.0, stop_limit_price=1.1, stop_loss=2.0, take_profit=0.9, options={'comment': 'comment', 'clientId': 'TE_GBPUSD_7hyINWqAl'})) ``` -------------------------------- ### Query Contract Specifications and Quotes Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/metaApi/rpcApi.rst Learn how to fetch available trading symbols, their contract specifications, and real-time price quotes using the RPC API. ```APIDOC ## Query Contract Specifications and Quotes ### Description Retrieve information about available trading symbols, their specifications, and current market prices. ### Method RPC API calls through a `connection` object obtained from `account.get_rpc_connection()`. ### Endpoints - `connection.connect()` - `connection.wait_synchronized()` - `connection.get_symbols()` - `connection.get_symbol_specification(symbol: str)` - `connection.get_symbol_price(symbol: str)` ### Request Example ```python connection = account.get_rpc_connection() await connection.connect() await connection.wait_synchronized() # read symbols available print(await connection.get_symbols()) # read contract specification print(await connection.get_symbol_specification(symbol='GBPUSD')) # read current price print(await connection.get_symbol_price(symbol='GBPUSD')) ``` ### Response Responses include lists of symbols, detailed contract specifications for a symbol, or current price information for a symbol. ``` -------------------------------- ### Retrieve Equity Chart Source: https://github.com/metaapi/metaapi-python-sdk/blob/main/docs/riskManagement.rst Fetches the equity chart data for a specified account. This method supports loading data within a specified broker time. ```python # retrieve equity chart, please note that this method supports loading within specified broker time print(await risk_management_api.get_equity_chart('accountId')) ```