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() # 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")