{"id":21447153,"url":"https://github.com/metaapi/metaapi-copyfactory-python-sdk","last_synced_at":"2026-03-09T13:43:41.825Z","repository":{"id":206157693,"uuid":"715990758","full_name":"metaapi/metaapi-copyfactory-python-sdk","owner":"metaapi","description":"Python SDK for CopyFactory trade copying API. Can copy trades both between MetaTrader 5 (MT5) and MetaTrader 4 (MT4)","archived":false,"fork":false,"pushed_at":"2025-09-01T02:41:25.000Z","size":43,"stargazers_count":4,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-01T03:25:23.119Z","etag":null,"topics":["api","cloud","copyfactory","copytrade","forex","metaapi","metaapi-cloud","metatrader","metatrader4","metatrader5","mt4","mt4-api","mt5","mt5-api","python","rest","risk-filters","trade-copying","trading"],"latest_commit_sha":null,"homepage":"https://metaapi.cloud","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/metaapi.png","metadata":{"files":{"readme":"README.rst","changelog":"changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-11-08T08:51:06.000Z","updated_at":"2025-09-01T02:40:20.000Z","dependencies_parsed_at":null,"dependency_job_id":"d4b20112-216e-41ae-a5f2-b7b7f85da360","html_url":"https://github.com/metaapi/metaapi-copyfactory-python-sdk","commit_stats":{"total_commits":4,"total_committers":1,"mean_commits":4.0,"dds":0.0,"last_synced_commit":"ceea3cb75b0a9be5176ff3bf768cc27c2a3f64b1"},"previous_names":["metaapi/metaapi-copyfactory-python-sdk"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/metaapi/metaapi-copyfactory-python-sdk","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metaapi%2Fmetaapi-copyfactory-python-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metaapi%2Fmetaapi-copyfactory-python-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metaapi%2Fmetaapi-copyfactory-python-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metaapi%2Fmetaapi-copyfactory-python-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/metaapi","download_url":"https://codeload.github.com/metaapi/metaapi-copyfactory-python-sdk/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/metaapi%2Fmetaapi-copyfactory-python-sdk/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30297293,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-09T11:12:22.024Z","status":"ssl_error","status_checked_at":"2026-03-09T11:10:54.577Z","response_time":61,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","cloud","copyfactory","copytrade","forex","metaapi","metaapi-cloud","metatrader","metatrader4","metatrader5","mt4","mt4-api","mt5","mt5-api","python","rest","risk-filters","trade-copying","trading"],"created_at":"2024-11-23T03:09:02.941Z","updated_at":"2026-03-09T13:43:41.807Z","avatar_url":"https://github.com/metaapi.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"CopyFactory trade copying API for Python (a member of `metaapi.cloud \u003chttps://metaapi.cloud\u003e`_ project)\n#######################################################################################################\n\nCopyFactory is a powerful trade copying API which makes developing forex\ntrade copying applications as easy as writing few lines of code.\n\nCopyFactory API is a member of MetaApi project (`https://metaapi.cloud \u003chttps://metaapi.cloud\u003e`_),\na powerful cloud forex trading API which supports both MetaTrader 4 and MetaTrader 5 platforms.\n\nMetaApi is a paid service, however we may offer a free tier access in some cases.\n\nThe `MetaApi pricing \u003chttps://metaapi.cloud/#pricing\u003e`_ was developed with the intent to make your charges less or equal to what you would have to pay\nfor hosting your own infrastructure. This is possible because over time we managed to heavily optimize\nour MetaTrader infrastructure. And with MetaApi you can save significantly on application development and\nmaintenance costs and time thanks to high-quality API, open-source SDKs and convenience of a cloud service.\n\nThis SDK requires a 3.8+ version of Python to run.\n\nWhy do we offer CopyFactory API trade copying API\n=================================================\n\nWe found that developing reliable and flexible trade copier is a task\nwhich requires lots of effort, because developers have to solve a series\nof complex technical tasks to create a product.\n\nWe decided to share our product as it allows developers to start with a\npowerful solution in almost no time, saving on development and\ninfrastructure maintenance costs.\n\nFrequently asked questions (FAQ)\n================================\n\nFAQ is located here: `https://metaapi.cloud/docs/copyfactory/faq/ \u003chttp://metaapi.cloud/docs/copyfactory/faq/\u003e`_\n\nCopyFactory copytrading API features\n====================================\n\nFeatures supported:\n\n- low latency trade copying API\n- reliable trade copying API\n- suitable for large-scale deployments\n- suitable for large number of subscribers\n- connect arbitrary number of strategy providers and subscribers\n- subscribe accounts to multiple strategies at once\n- select arbitrary copy ratio for each subscription\n- configure symbol mapping between strategy providers and subscribers\n- apply advanced risk filters on strategy provider side\n- override risk filters on subscriber side\n- provide multiple strategies from a single account based on magic or symbol filters\n- supports manual trading on subscriber accounts while copying trades\n- synchronize subscriber account with strategy providers\n- monitor trading history\n- calculate trade copying commissions for account managers\n- support portfolio strategies as trading signal source, i.e. the strategies which include signals of several other strategies (also known as combos on some platforms)\n\nPlease note that trade copying to MT5 netting accounts is not supported in the current API version\n\nPlease check Features section of the `https://metaapi.cloud/docs/copyfactory/ \u003chttps://metaapi.cloud/docs/copyfactory/\u003e`_\ndocumentation for detailed description of all settings you can make.\n\nREST API documentation\n======================\n\nCopyFactory SDK is built on top of CopyFactory REST API.\n\nCopyFactory REST API docs are available at `https://metaapi.cloud/docs/copyfactory/ \u003chttps://metaapi.cloud/docs/copyfactory/\u003e`_\n\nCode examples\n=============\n\nWe published some code examples in our github repository, namely:\n\n- Python: `https://github.com/metaapi/metaapi-copyfactory-python-sdk/tree/master/examples \u003chttps://github.com/metaapi/metaapi-copyfactory-python-sdk/tree/master/examples\u003e`_\n\nInstallation\n============\n\n.. code-block:: bash\n\n    pip install metaapi-cloud-sdk\n\nRetrieving API token\n====================\n\nPlease visit `https://app.metaapi.cloud/token \u003chttps://app.metaapi.cloud/token\u003e`_ web UI to obtain your API token.\n\nConfiguring trade copying\n=========================\n\nIn order to configure trade copying you need to:\n\n- add MetaApi MetaTrader accounts with CopyFactory as application field value (see above)\n- create CopyFactory provider and subscriber accounts and connect them to MetaApi accounts via connectionId field\n- create a strategy being copied\n- subscribe subscriber CopyFactory accounts to the strategy\n\n.. code-block:: python\n\n    from metaapi_cloud_sdk import MetaApi, CopyFactory\n\n    token = '...'\n    metaapi = MetaApi(token=token)\n    copy_factory = CopyFactory(token=token)\n\n    # retrieve MetaApi MetaTrader accounts with CopyFactory as application field value\n    # provider account must have PROVIDER value in copyFactoryRoles\n    provider_metaapi_account = await metaapi.metatrader_account_api.get_account(account_id='providerMetaapiAccountId')\n    if (provider_metaapi_account is None) or provider_metaapi_account.copy_factory_roles is None or 'PROVIDER' not \\\n            in provider_metaapi_account.copy_factory_roles:\n        raise Exception('Please specify PROVIDER copyFactoryRoles value in your MetaApi '\n                        'account in order to use it in CopyFactory API')\n    # subscriber account must have SUBSCRIBER value in copyFactoryRoles\n    subscriber_metaapi_account = await metaapi.metatrader_account_api.get_account(account_id='subscriberMetaapiAccountId')\n    if (subscriber_metaapi_account is None) or subscriber_metaapi_account.copy_factory_roles is None or 'SUBSCRIBER' not \\\n            in subscriber_metaapi_account.copy_factory_roles:\n        raise Exception('Please specify SUBSCRIBER copyFactoryRoles value in your MetaApi '\n                        'account in order to use it in CopyFactory API')\n\n    configuration_api = copy_factory.configuration_api\n\n    # create a strategy being copied\n    strategy_id = await configuration_api.generate_strategy_id()\n    await configuration_api.update_strategy(id=strategy_id['id'], strategy={\n        'name': 'Test strategy',\n        'description': 'Some useful description about your strategy',\n        'accountId': provider_metaapi_account.id,\n        'maxTradeRisk': 0.1,\n        'stopOutRisk': {\n            'value': 0.4,\n            'startTime': '2020-08-24T00:00:00.000Z'\n        },\n        'timeSettings': {\n            'lifetimeInHours': 192,\n            'openingIntervalInMinutes': 5\n        }\n    })\n\n    # subscribe subscriber CopyFactory accounts to the strategy\n    await configuration_api.update_subscriber(subscriber_metaapi_account.id, {\n        'name': 'Demo account',\n        'subscriptions': [\n            {\n                'strategyId': strategy_id['id'],\n                'multiplier': 1\n            }\n        ]\n    })\n\n\nSee in-code documentation for full definition of possible configuration options.\n\nRetrieving paginated lists\n==========================\n\nThere are two groups of methods to retrieve paginated lists:\n\n- with pagination in infinite scroll style\n- with pagination in a classic style which allows you to calculate page count\n\nThey are applied to following entities:\n\n- strategies: ``get_strategies_with_infinite_scroll_pagination`` and ``get_strategies_with_classic_pagination``\n- provider portfolios: ``get_portfolio_strategies_with_infinite_scroll_pagination`` and ``get_portfolio_strategies_with_classic_pagination``\n- subscribers: ``get_subscribers_with_infinite_scroll_pagination`` and ``get_subscribers_with_classic_pagination``\n\nExample of retrieving strategies with pagination in infinite scroll style:\n\n.. code-block:: python\n\n    # paginate strategies, see in-code documentation for full list of filter options available.\n    strategies = await api.metatrader_account_api.get_strategies_with_infinite_scroll_pagination(\n        {'limit': 10, 'offset': 0}\n    )\n\n    # get strategies without filter (returns 1000 strategies max)\n    strategies = await api.metatrader_account_api.get_strategies_with_infinite_scroll_pagination()\n    strategy = None\n\n    for s in strategies:\n        if s['_id'] == 'strategyId':\n            strategy = s\n            break\n\nExample of retrieving strategies with pagination in classic style:\n\n.. code-block:: python\n\n    # paginate strategies, see in-code documentation for full list of filter options available.\n    strategies = await api.metatrader_account_api.get_strategies_with_classic_pagination({'limit': 10, 'offset': 0})\n    strategy = None\n\n    for s in strategies:\n        if s['_id'] == 'strategyId':\n            strategy = s\n            break\n    # number of all strategies matching filter without pagination options\n    print(strategies['count'])\n\n    # get strategies without filter (returns 1000 strategies max)\n    strategies = await api.metatrader_account_api.get_strategies_with_classic_pagination()\n\nRetrieving trade copying history\n================================\n\nCopyFactory allows you to monitor transactions conducted on trading accounts in real time.\n\nRetrieving trading history on provider side\n-------------------------------------------\n\n.. code-block:: python\n\n    history_api = copy_factory.history_api\n\n    # retrieve trading history, please note that this method support pagination and limits number of records\n    print(await history_api.get_provided_transactions(time_from=datetime.fromisoformat('2020-08-01'),\n        time_till=datetime.fromisoformat('2020-09-01')))\n\n\nRetrieving trading history on subscriber side\n---------------------------------------------\n\n.. code-block:: python\n\n    history_api = copy_factory.history_api\n\n    # retrieve trading history, please note that this method support pagination and limits number of records\n    print(await history_api.get_subscription_transactions(time_from=datetime.fromisoformat('2020-08-01'),\n        time_till=datetime.fromisoformat('2020-09-01')))\n\nResynchronizing subscriber accounts to providers\n================================================\nThere is a configurable time limit during which the trades can be opened. Sometimes trades can not open in time due to broker errors or trading session time discrepancy.\nYou can resynchronize a subscriber account to place such late trades. Please note that positions which were\nclosed manually on a subscriber account will also be reopened during resynchronization.\n\n.. code-block:: python\n\n    account_id = '...' # CopyFactory account id\n\n    # resynchronize all strategies\n    await copy_factory.trading_api.resynchronize(account_id=account_id)\n\n    # resynchronize specific strategy\n    await copy_factory.trading_api.resynchronize(account_id=account_id, strategy_ids=['ABCD'])\n\nSending external trading signals to a strategy\n==============================================\nYou can submit external trading signals to your trading strategy.\n\n.. code-block:: python\n\n    trading_api = copy_factory.trading_api\n    signal_id = trading_api.generate_signal_id()\n\n    # get strategy signal client\n    strategy_signal_client = await trading_api.get_strategy_signal_client(strategy_id)\n\n    # add trading signal\n    await strategy_signal_client.update_external_signal(signal_id=signal_id, signal={\n        'symbol': 'EURUSD',\n        'type': 'POSITION_TYPE_BUY',\n        'time': datetime.now(),\n        'volume': 0.01\n    })\n\n    # get external signals\n    print(await strategy_signal_client.get_external_signals())\n\n    # remove signal\n    await strategy_signal_client.remove_external_signal(signal_id=signal_id, signal={\n        'time': datetime.now()\n    })\n\nRetrieving trading signals\n==========================\n\n.. code-block:: python\n\n    subscriber_id = '...' # CopyFactory subscriber id\n    subscriber_signal_client = await trading_api.get_subscriber_signal_client(subscriber_id)\n\n    # retrieve trading signals\n    print(await subscriber_signal_client.get_trading_signals())\n\nManaging stopouts\n=================\nA subscription to a strategy can be stopped if the strategy have exceeded allowed risk limit.\n\n.. code-block:: python\n\n    trading_api = copy_factory.trading_api\n    account_id = '...' # CopyFactory account id\n    strategy_id = '...' # CopyFactory strategy id\n\n    # retrieve list of strategy stopouts\n    print(await trading_api.get_stopouts(account_id=account_id))\n\n    # reset a stopout so that subscription can continue\n    await trading_api.reset_subscription_stopouts(account_id=account_id, strategy_id=strategy_id, reason='daily-equity')\n\nManaging stopout listeners\n==========================\nYou can subscribe to a stream of stopout events using the stopout listener.\n\n.. code-block:: python\n\n    from metaapi_cloud_sdk import StopoutListener\n\n    trading_api = copy_factory.trading_api\n\n    # create a custom class based on the StopoutListener\n    class Listener(StopoutListener):\n\n        # specify the function called on event arrival\n        async def on_stopout(self, strategy_stopout_event):\n            print('Strategy stopout event', strategy_stopout_event)\n\n        # specify the function called on error event\n        async def on_error(self, error):\n            print('Error event', error)\n\n    # add listener\n    listener = Listener()\n    listener_id = trading_api.add_stopout_listener(listener)\n\n    # remove listener\n    trading_api.remove_stopout_listener(listener_id)\n\nRetrieving subscriber trading logs\n==================================\n\n.. code-block:: python\n\n    trading_api = copy_factory.trading_api\n    account_id = '...' # CopyFactory account id\n\n    # retrieve subscriber trading log\n    print(await trading_api.get_user_log(account_id))\n\n    # retrieve paginated subscriber trading log by time range\n    print(await trading_api.get_user_log(account_id, datetime.fromtimestamp(datetime.now().timestamp() - 24 * 60 * 60), None, 20, 10))\n\nLog streaming\n=============\nYou can subscribe to a stream of strategy or subscriber log events using the user log listener.\n\nStrategy logs\n-------------\n\n.. code-block:: python\n\n    from metaapi_cloud_sdk import UserLogListener\n\n    trading_api = copy_factory.trading_api\n\n    # create a custom class based on the UserLogListener\n    class Listener(UserLogListener):\n\n        # specify the function called on event arrival\n        async def on_user_log(self, log_event):\n            print('Strategy user log event', log_event)\n\n        # specify the function called on error event\n        async def on_error(self, error):\n            print('Error event', error)\n\n    # add listener\n    listener = Listener()\n    listener_id = trading_api.add_strategy_log_listener(listener, 'ABCD')\n\n    # remove listener\n    trading_api.remove_strategy_log_listener(listener_id)\n\nSubscriber logs\n---------------\n\n.. code-block:: python\n\n    from metaapi_cloud_sdk import UserLogListener\n\n    trading_api = copy_factory.trading_api\n\n    # create a custom class based on the UserLogListener\n    class Listener(UserLogListener):\n\n        # specify the function called on event arrival\n        async def on_user_log(self, log_event):\n            print('Subscriber user log event', log_event)\n\n        # specify the function called on error event\n        async def on_error(self, error):\n            print('Error event', error)\n\n    # add listener\n    listener = Listener()\n    listener_id = trading_api.add_subscriber_log_listener(listener, 'accountId')\n\n    # remove listener\n    trading_api.remove_subscriber_log_listener(listener_id)\n\nTransaction streaming\n=====================\nYou can subscribe to a stream of strategy or subscriber transaction events using the transaction listener.\n\nStrategy transactions\n---------------------\n\n.. code-block:: python\n\n    from metaapi_cloud_sdk import TransactionListener\n\n    history_api = copy_factory.history_api\n\n    # create a custom class based on the TransactionListener\n    class Listener(TransactionListener):\n\n        # specify the function called on event arrival\n        async def on_transaction(self, transaction_event):\n            print('Strategy transaction event', transaction_event)\n\n        # specify the function called on error event\n        async def on_error(self, error):\n            print('Error event', error)\n\n    # add listener\n    listener = Listener()\n    listener_id = history_api.add_strategy_transaction_listener(listener, 'ABCD')\n\n    # remove listener\n    history_api.remove_strategy_transaction_listener(listener_id)\n\nSubscriber transactions\n-----------------------\n\n.. code-block:: python\n\n    from metaapi_cloud_sdk import TransactionListener\n\n    history_api = copy_factory.history_api\n\n    # create a custom class based on the TransactionListener\n    class Listener(TransactionListener):\n\n        # specify the function called on event arrival\n        async def on_transaction(transaction_event):\n            print('Subscriber transaction event', transaction_event)\n\n        # specify the function called on error event\n        async def on_error(self, error):\n            print('Error event', error)\n\n    # add listener\n    listener = Listener()\n    listener_id = history_api.add_strategy_transaction_listener(listener, 'ABCD')\n\n    # remove listener\n    history_api.remove_subscriber_transaction_listener(listener_id)\n\nWebhooks\n========\n\nWebhooks can be created on specific strategies and their URLs can be provided to external systems to create external trading signals. The URL contains a secret webhook ID, so no extra authorization is required on a REST API invocation to a webhook.\n\n.. code-block:: python\n\n    strategy_id = '...'\n\n    webhook = await copyfactory.configuration_api.create_webhook(strategy_id)\n    url = webhook['url']\n\nFor example, if ``webhook.url`` is ``https://copyfactory-api-v1.london.agiliumtrade.ai/webhooks/yMLd8aviewgFfS4NBxZETkoVPbWAJ92t`` then a request can be sent to it to create an external signal:\n\n.. code-block:: bash\n\n    curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\n      \"symbol\": \"EURUSD\",\n      \"type\": \"POSITION_TYPE_BUY\",\n      \"time\": \"2024-12-19T06:52:19.679Z\",\n      \"volume\": 0.1\n    }' 'https://copyfactory-api-v1.london.agiliumtrade.ai/webhooks/yMLd8aviewgFfS4NBxZETkoVPbWAJ92t'\n\n\nRelated projects:\n=================\n\nSee our website for the full list of APIs and features supported `https://metaapi.cloud/#features \u003chttps://metaapi.cloud/#features\u003e`_\n\nSome of the APIs you might decide to use together with this module:\n\n1. MetaApi cloud forex trading API `https://metaapi.cloud/docs/client/ \u003chttps://metaapi.cloud/docs/client/\u003e`_\n2. MetaTrader account management API `https://metaapi.cloud/docs/provisioning/ \u003chttps://metaapi.cloud/docs/provisioning/\u003e`_\n3. MetaStats cloud forex trading statistics API `https://metaapi.cloud/docs/metastats/ \u003chttps://metaapi.cloud/docs/metastats/\u003e`_\n4. MetaApi MT manager API `https://metaapi.cloud/docs/manager/ \u003chttps://metaapi.cloud/docs/manager/\u003e`_\n5. MetaApi risk management API `https://metaapi.cloud/docs/risk-management/ \u003chttps://metaapi.cloud/docs/risk-management/\u003e`_\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmetaapi%2Fmetaapi-copyfactory-python-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmetaapi%2Fmetaapi-copyfactory-python-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmetaapi%2Fmetaapi-copyfactory-python-sdk/lists"}