From 9dda0e8b4a01703b6478b1f165a3514e33acf830 Mon Sep 17 00:00:00 2001 From: Mark Veidemanis Date: Mon, 2 Jan 2023 18:42:55 +0000 Subject: [PATCH] Write live open/close and list trades tests --- core/tests/trading/test_live.py | 70 ++++++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/core/tests/trading/test_live.py b/core/tests/trading/test_live.py index 1e40a8a..74d15e3 100644 --- a/core/tests/trading/test_live.py +++ b/core/tests/trading/test_live.py @@ -1,12 +1,80 @@ from django.test import TestCase +from core.models import Trade from core.tests.helpers import ElasticMock, LiveBase class LiveTradingTestCase(ElasticMock, LiveBase, TestCase): + def setUp(self): + super(LiveTradingTestCase, self).setUp() + self.trade = Trade.objects.create( + user=self.user, + account=self.account, + symbol="EUR_USD", + time_in_force="FOK", + type="market", + amount=10, + direction="buy", + ) + def test_account_functional(self): """ Test that the account is functional. """ balance = self.account.client.get_balance() - self.assertTrue(balance > 0) + # We need some money to place trades + self.assertTrue(balance > 1000) + + def open_trade(self): + posted = self.trade.post() + # Check the opened trade + self.assertEqual(posted["type"], "MARKET_ORDER") + self.assertEqual(posted["symbol"], "EUR_USD") + self.assertEqual(posted["units"], "10") + self.assertEqual(posted["timeInForce"], "FOK") + + return posted + + def close_trade(self): + # refresh the trade to get the trade id + self.trade.refresh_from_db() + closed = self.account.client.close_trade(self.trade.order_id) + + # Check the feedback from closing the trade + self.assertEqual(closed["type"], "MARKET_ORDER") + self.assertEqual(closed["symbol"], "EUR_USD") + self.assertEqual(closed["units"], "-10") + self.assertEqual(closed["timeInForce"], "FOK") + self.assertEqual(closed["reason"], "TRADE_CLOSE") + + return closed + + def test_place_close_trade(self): + """ + Test placing a trade. + """ + self.open_trade() + self.close_trade() + + def test_get_all_open_trades(self): + """ + Test getting all open trades. + """ + + self.open_trade() + + trades = self.account.client.get_all_open_trades() + self.trade.refresh_from_db() + found = False + for trade in trades["itemlist"]: + if trade["id"] == self.trade.order_id: + self.assertEqual(trade["symbol"], "EUR_USD") + self.assertEqual(trade["currentUnits"], "10") + self.assertEqual(trade["initialUnits"], "10") + self.assertEqual(trade["state"], "OPEN") + found = True + break + self.close_trade() + + if not found: + self.fail("Could not find the trade in the list of open trades")