From 66a18a6406f6b4ad4352f17f99f7e570ceb53474 Mon Sep 17 00:00:00 2001 From: Mark Veidemanis Date: Thu, 1 Dec 2022 20:36:58 +0000 Subject: [PATCH] Implement closing positions and refuse to post rejected trades --- core/exchanges/oanda.py | 11 ++++++++++- core/migrations/0042_trade_information.py | 18 ++++++++++++++++++ core/models.py | 7 ++++++- 3 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 core/migrations/0042_trade_information.py diff --git a/core/exchanges/oanda.py b/core/exchanges/oanda.py index 005205b..d5b9eec 100644 --- a/core/exchanges/oanda.py +++ b/core/exchanges/oanda.py @@ -117,6 +117,16 @@ class OANDAExchange(BaseExchange): items.append(item) return items + def close_position(self, side, symbol): + data = { + f"{side}Units": "ALL", + } + r = positions.PositionClose( + accountID=self.account_id, instrument=symbol, data=data + ) + response = self.call(r) + return response + def close_all_positions(self): # all_positions = self.get_all_positions() @@ -124,5 +134,4 @@ class OANDAExchange(BaseExchange): # print("POS ITER", position) r = positions.PositionClose(accountID=self.account_id) response = self.call(r) - print("CLOSE ALL POSITIONS", response) return response diff --git a/core/migrations/0042_trade_information.py b/core/migrations/0042_trade_information.py new file mode 100644 index 0000000..1034ff4 --- /dev/null +++ b/core/migrations/0042_trade_information.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.3 on 2022-12-01 19:42 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0041_alter_strategy_entry_signals_and_more'), + ] + + operations = [ + migrations.AddField( + model_name='trade', + name='information', + field=models.JSONField(blank=True, null=True), + ), + ] diff --git a/core/models.py b/core/models.py index 84de8f1..0aa0d97 100644 --- a/core/models.py +++ b/core/models.py @@ -201,6 +201,7 @@ class Trade(models.Model): trailing_stop_loss = models.FloatField(null=True, blank=True) take_profit = models.FloatField(null=True, blank=True) status = models.CharField(max_length=255, null=True, blank=True) + information = models.JSONField(null=True, blank=True) direction = models.CharField(choices=DIRECTION_CHOICES, max_length=255) # To populate from the trade @@ -213,7 +214,11 @@ class Trade(models.Model): self._original = self def post(self): - return self.account.client.post_trade(self) + if self.status in ["rejected", "close"]: + log.debug(f"Trade {self.id} rejected. Not posting.") + log.debug(f"Trade {self.id} information: {self.information}") + else: + return self.account.client.post_trade(self) def delete(self, *args, **kwargs): # close the trade