{"id":19912105,"url":"https://github.com/ichinga-samuel/aiomql","last_synced_at":"2025-04-04T17:04:09.958Z","repository":{"id":63207530,"uuid":"549218524","full_name":"Ichinga-Samuel/aiomql","owner":"Ichinga-Samuel","description":"Asynchronous Python Library For MetaTrader 5","archived":false,"fork":false,"pushed_at":"2025-01-24T13:33:01.000Z","size":764,"stargazers_count":81,"open_issues_count":2,"forks_count":25,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-03-28T16:04:05.829Z","etag":null,"topics":["asynchronous-programming","forex-bot","forex-trading","metatrader5","mql5","trading","trading-bot"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Ichinga-Samuel.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","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},"funding":{"github":"Ichinga-Samuel","buy_me_a_coffee":"ichingasamuel","patreon":"IchingaSamuel"}},"created_at":"2022-10-10T21:27:24.000Z","updated_at":"2025-03-28T15:21:46.000Z","dependencies_parsed_at":"2024-08-26T05:57:20.713Z","dependency_job_id":"66601906-7830-4224-a0cf-169079f5319e","html_url":"https://github.com/Ichinga-Samuel/aiomql","commit_stats":{"total_commits":17,"total_committers":2,"mean_commits":8.5,"dds":"0.23529411764705888","last_synced_commit":"e420475cab4e317e963d4d854bee31d99320a0d5"},"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ichinga-Samuel%2Faiomql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ichinga-Samuel%2Faiomql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ichinga-Samuel%2Faiomql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Ichinga-Samuel%2Faiomql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Ichinga-Samuel","download_url":"https://codeload.github.com/Ichinga-Samuel/aiomql/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247217174,"owners_count":20903008,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["asynchronous-programming","forex-bot","forex-trading","metatrader5","mql5","trading","trading-bot"],"created_at":"2024-11-12T21:28:16.307Z","updated_at":"2025-04-04T17:04:09.937Z","avatar_url":"https://github.com/Ichinga-Samuel.png","language":"Python","funding_links":["https://github.com/sponsors/Ichinga-Samuel","https://buymeacoffee.com/ichingasamuel","https://patreon.com/IchingaSamuel","https://www.buymeacoffee.com/ichingasamuel"],"categories":[],"sub_categories":[],"readme":"# Aiomql - Bot Building Framework and Asynchronous MetaTrader5 Library\n![GitHub](https://img.shields.io/github/license/ichinga-samuel/aiomql?style=plastic)\n![GitHub issues](https://img.shields.io/github/issues/ichinga-samuel/aiomql?style=plastic)\n![PyPI](https://img.shields.io/pypi/v/aiomql)\n\n\n### Installation\n```bash\npip install aiomql\n```\n\n### Key Features\n- Asynchronous Python Library For MetaTrader5\n- Asynchronous Bot Building Framework\n- Build bots for trading in different financial markets.\n- Use threadpool executors to run multiple strategies on multiple instruments concurrently\n- Records and keep track of trades and strategies in csv files.\n- Helper classes for Bot Building. Easy to use and extend.\n- Compatible with pandas-ta.\n- Sample Pre-Built strategies\n- Specify and Manage Trading Sessions\n- Risk Management\n- Backtesting Engine\n- Run multiple bots concurrently with different accounts from the same broker or different brokers\n- Easy to use and very accurate backtesting engine\n\n### As an asynchronous MetaTrader5 Libray\n```python\nimport asyncio\n\nfrom aiomql import MetaTrader\n\n\nasync def main():\n    mt5 = MetaTrader()\n    res = await mt5.initialize(login=31288540, password='nwa0#anaEze', server='Deriv-Demo')\n    if not res:\n        print('Unable to login and initialize')\n        return \n    # get account information\n    acc = await mt5.account_info()\n    print(acc)\n    # get symbols\n    symbols = await mt5.symbols_get()\n    print(symbols)\n    \nasyncio.run(main())\n```\n\n### As a Bot Building FrameWork using a Sample Strategy\nAiomql allows you to focus on building trading strategies and not worry about the underlying infrastructure.\nIt provides a simple and easy to use framework for building bots with rich features and functionalities.\n\n\n```python\nfrom datetime import time\nimport logging\n\nfrom aiomql import Bot, ForexSymbol, FingerTrap, Session, Sessions, RAM, SimpleTrader, TimeFrame, Chaos\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef build_bot():\n    bot = Bot()\n    # configure the parameters and the trader for a strategy\n    params = {'fast_period': 8, 'slow_period': 34, 'etf': TimeFrame.M5}\n    symbols = ['GBPUSD', 'AUDUSD', 'USDCAD', 'EURGBP', 'EURUSD']\n    symbols = [ForexSymbol(name=sym) for sym in symbols]\n    strategies = [FingerTrap(symbol=sym, params=params)for sym in symbols]\n    bot.add_strategies(strategies)\n    \n    # create a strategy that uses sessions\n    # sessions are used to specify the trading hours for a particular market\n    # the strategy will only trade during the specified sessions\n    london = Session(name='London', start=time(8, 0), end=time(16, 0))\n    new_york = Session(name='New York', start=time(13, 0), end=time(21, 0))\n    tokyo = Session(name='Tokyo', start=time(0, 0), end=time(8, 0))\n    \n    sessions = Sessions(sessions=[london, new_york, tokyo])  \n    jpy_strategy = Chaos(symbol=ForexSymbol(name='USDJPY'), sessions=sessions)\n    bot.add_strategy(strategy=jpy_strategy)\n    bot.execute()\n\n# run the bot\nbuild_bot()\n```\n\n### Backtesting\nAiomql provides a very accurate backtesting engine that allows you to test your trading strategies before deploying\nthem in the market. The backtest engine prioritizes accuracy over speed, but allows you to increase the speed\nas desired. It is very easy to use and provides a lot of flexibility. The backtester is designed to run strategies\nseamlessly without need for modification of the strategy code. When running in backtest mode all the classes that\nneeds to know if they are running in backtest mode will be able to do so and adjust their behavior accordingly.\n\n```python\nfrom aiomql import MetaBackTester, BackTestEngine, MetaTrader\nimport logging\nfrom datetime import datetime, UTC\n\nfrom aiomql.lib.backtester import BackTester\nfrom aiomql.core import Config\nfrom aiomql.contrib.strategies import FingerTrap\nfrom aiomql.contrib.symbols import ForexSymbol\nfrom aiomql.core.backtesting import BackTestEngine\n\n\ndef back_tester():\n    config = Config(mode=\"backtest\")\n    logging.basicConfig(level=logging.INFO, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n    syms = [\"Volatility 75 Index\", \"Volatility 100 Index\", \"Volatility 25 Index\", \"Volatility 10 Index\"]\n    symbols = [ForexSymbol(name=sym) for sym in syms]\n    strategies = [FingerTrap(symbol=symbol) for symbol in symbols]\n    \n    # create start time and end time for the backtest\n    start = datetime(2024, 5, 1, tzinfo=UTC)\n    stop_time = datetime(2024, 5, 2, tzinfo=UTC)\n    end = datetime(2024, 5, 7, tzinfo=UTC)\n    \n    # create a backtest engine\n    back_test_engine = BackTestEngine(start=start, end=end, speed=3600, stop_time=stop_time,\n                                      close_open_positions_on_exit=True, assign_to_config=True, preload=True,\n                                      account_info={\"balance\": 350})\n    # add it to the backtester\n    backtester = BackTester(backtest_engine=back_test_engine)\n    # add strategies to the backtester\n    backtester.add_strategies(strategies=strategies)\n    backtester.execute()\n\n\nback_tester()\n```\n\n### Writing a Custom Strategy\nAiomql provides a simple and easy to use framework for building trading strategies. You can easily extend the\nframework to build your own custom strategies. Below is an example of a simple strategy that buys when the fast\nmoving average crosses above the slow moving average and sells when the fast moving average crosses below the slow\nmoving average.\n\n```python\n# emaxover.py\nfrom aiomql import Strategy, ForexSymbol, TimeFrame, Tracker, OrderType, Sessions, Trader, ScalpTrader\n\n\nclass EMAXOver(Strategy):\n    ttf: TimeFrame  # time frame for the strategy\n    tcc: int  # how many candles to consider\n    fast_ema: int  # fast moving average period\n    slow_ema: int  # slow moving average period\n    tracker: Tracker  # tracker to keep track of strategy state\n    interval: TimeFrame  # intervals to check for entry and exit signals\n    timeout: int  # timeout after placing an order in seconds\n\n    # default parameters for the strategy\n    # they are set as attributes. You can override them in the constructor via the params argument.\n    parameters = {'ttf': TimeFrame.H1, 'tcc': 3000, 'fast_ema': 34, 'slow_ema': 55, 'interval': TimeFrame.M15,\n                  'timeout': 3 * 60 * 60}\n\n    def __init__(self, *, symbol: ForexSymbol, params: dict | None = None, trader: Trader = None,\n                 sessions: Sessions = None, name: str = \"EMAXOver\"):\n        super().__init__(symbol=symbol, params=params, sessions=sessions, name=name)\n        self.tracker = Tracker(snooze=self.interval.seconds)\n        self.trader = trader or ScalpTrader(symbol=self.symbol)\n\n    async def find_entry(self):\n        # get the candles\n        candles = await self.symbol.copy_rates_from_pos(timeframe=self.ttf, start_position=0, count=self.tcc)\n\n        # get the fast moving average\n        candles.ta.ema(length=self.fast_ema, append=True)\n        # get the slow moving average\n        candles.ta.ema(length=self.slow_ema, append=True)\n        # rename the columns\n        candles.rename(**{f\"EMA_{self.fast_ema}\": \"fast_ema\", f\"EMA_{self.slow_ema}\": \"slow_ema\"}, inplace=True)\n\n        # check for crossovers\n        # fast above slow\n        fas = candles.ta_lib.cross(candles.fast_ema, candles.slow_ema, above=True)\n        # fast below slow\n        fbs = candles.ta_lib.cross(candles.fast_ema, candles.slow_ema, above=False)\n\n        ## check for entry signals in the current candle\n        if fas.iloc[-1]:\n            self.tracker.update(order_type=OrderType.BUY, snooze=self.timeout)\n        elif fbs.iloc[-1]:\n            self.tracker.update(order_type=OrderType.SELL, snooze=self.timeout)\n        else:\n            self.tracker.update(order_type=None, snooze=self.interval.seconds)\n\n    async def trade(self):\n        await self.find_entry()\n        if self.tracker.order_type is None:\n            await self.sleep(secs=self.tracker.snooze)\n        else:\n            await self.trader.place_trade(order_type=self.tracker.order_type, parameters=self.parameters)\n            await self.delay(secs=self.tracker.snooze)\n```\n\n### Testing\n\nRun the tests with pytest\n\n```bash\npytest tests\n```\n\n### API Documentation\nsee [API Documentation](docs) for more details\n\n### Contributing\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\n\n### Changelog\n\nSee [CHANGELOG](CHANGELOG.md) for more details\n\n### Support\nFeeling generous, like the package or want to see it become a more mature package?\n\nConsider supporting the project by buying me a coffee.\n\n[![\"Buy Me A Coffee\"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/ichingasamuel)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fichinga-samuel%2Faiomql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fichinga-samuel%2Faiomql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fichinga-samuel%2Faiomql/lists"}