Files

67 lines
2.0 KiB
Python
Raw Permalink Normal View History

2024-10-28 06:36:10 +01:00
import asyncio
import json
import shutil
from logging import getLogger
from pathlib import Path
import pytest
from aiomql.core import Config
from aiomql.core.meta_trader import MetaTrader
logger = getLogger(__name__)
async def cleanup():
try:
2024-11-04 00:32:51 +01:00
shutil.rmtree(Path("tests/live/configs"), ignore_errors=True)
Path.unlink(Path("tests/live/test.json"), missing_ok=True)
shutil.rmtree(Path("tests/live/trade_records"), ignore_errors=True)
2024-10-28 06:36:10 +01:00
await close_all_positions()
await MetaTrader().shutdown()
except Exception as err:
logger.error(f"Failed to complete cleanup: {err}")
async def close_all_positions():
try:
mt = MetaTrader()
positions = await mt.positions_get()
tasks = []
for position in positions:
2024-11-11 05:56:08 +01:00
order_type = mt.ORDER_TYPE_BUY if position.type == mt.ORDER_TYPE_SELL else mt.ORDER_TYPE_SELL
2024-11-04 00:32:51 +01:00
req = {
"action": mt.TRADE_ACTION_DEAL,
"symbol": position.symbol,
"volume": position.volume,
"type": order_type,
"position": position.ticket,
"price": position.price_current,
}
2024-10-28 06:36:10 +01:00
tasks.append(mt.order_send(req))
await asyncio.gather(*tasks)
except Exception as err:
logger.error(f"Failed to close all positions: {err}")
2024-11-04 00:32:51 +01:00
@pytest.fixture(scope="package", autouse=True)
2024-10-28 06:36:10 +01:00
async def config(request):
2024-11-04 00:32:51 +01:00
Path("tests/live/configs").mkdir(exist_ok=True)
2024-11-16 09:26:10 +01:00
with open("aiomql.json", "r") as fh, open("tests/live/configs/test2.json", "w") as fh1, open(
"tests/live/test.json", "w"
) as fh2:
2024-10-28 06:36:10 +01:00
data = json.load(fh)
json.dump(data, fh1, indent=2)
json.dump(data, fh2, indent=2)
2024-11-23 10:23:01 +01:00
config = Config(root="tests/live", config_file="tests/live/test.json")
2024-10-28 06:36:10 +01:00
yield config
await cleanup()
2024-11-04 00:32:51 +01:00
@pytest.fixture(scope="package", autouse=True)
2024-10-28 06:36:10 +01:00
async def mt():
mt = MetaTrader()
await mt.initialize()
await mt.login()
yield mt
await mt.shutdown()