Implement TP/SL price to percent conversion

This commit is contained in:
2023-01-05 19:27:59 +00:00
parent a6f9e74ee1
commit d3e2bc8648
6 changed files with 389 additions and 23 deletions

View File

@@ -1,7 +1,9 @@
from django.test import TestCase
from core.exchanges.common import convert_open_trades
from core.models import Trade
from core.tests.helpers import ElasticMock, LiveBase
from core.trading.market import get_precision, get_price, get_sl, get_tp
class LiveTradingTestCase(ElasticMock, LiveBase, TestCase):
@@ -25,8 +27,11 @@ class LiveTradingTestCase(ElasticMock, LiveBase, TestCase):
# We need some money to place trades
self.assertTrue(balance > 1000)
def open_trade(self):
posted = self.trade.post()
def open_trade(self, trade=None):
if trade:
posted = trade.post()
else:
posted = self.trade.post()
# Check the opened trade
self.assertEqual(posted["type"], "MARKET_ORDER")
self.assertEqual(posted["symbol"], "EUR_USD")
@@ -35,10 +40,14 @@ class LiveTradingTestCase(ElasticMock, LiveBase, TestCase):
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)
def close_trade(self, trade=None):
if trade:
trade.refresh_from_db()
closed = self.account.client.close_trade(trade.order_id)
else:
# 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")
@@ -83,3 +92,42 @@ class LiveTradingTestCase(ElasticMock, LiveBase, TestCase):
"""
Test converting open trades response to Trade-like format.
"""
eur_usd_price = get_price(self.account, "buy", "EUR_USD")
trade_tp = get_tp("buy", 1, eur_usd_price)
trade_sl = get_sl("buy", 2, eur_usd_price)
# trade_tsl = get_sl("buy", 1, eur_usd_price, return_var=True)
# # TP 1% profit
# trade_tp = eur_usd_price * D(1.01)
# # SL 2% loss
# trade_sl = eur_usd_price * D(0.98)
# # TSL 1% loss
# trade_tsl = eur_usd_price * D(0.99)
trade_precision, display_precision = get_precision(self.account, "EUR_USD")
# Round everything to the display precision
trade_tp = round(trade_tp, display_precision)
trade_sl = round(trade_sl, display_precision)
# trade_tsl = round(trade_tsl, display_precision)
complex_trade = Trade.objects.create(
user=self.user,
account=self.account,
symbol="EUR_USD",
time_in_force="FOK",
type="market",
amount=10,
direction="buy",
take_profit=trade_tp,
stop_loss=trade_sl,
# trailing_stop_loss=trade_tsl,
)
posted = self.open_trade(complex_trade)
print("OPENED", posted)
trades = self.account.client.get_all_open_trades()
print("TRADES", trades)
trades_converted = convert_open_trades(trades["itemlist"])
print("TRADES CONVERTED", trades_converted)
closed = self.close_trade(complex_trade)
print("CLOSED", closed)