Add more hooks to active management
parent
dd3b3521d9
commit
1dbb3fcf79
@ -0,0 +1,30 @@
|
||||
# Generated by Django 4.1.7 on 2023-02-17 11:50
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0070_strategy_active_management_enabled_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='account',
|
||||
name='exchange',
|
||||
field=models.CharField(choices=[('alpaca', 'Alpaca'), ('oanda', 'OANDA'), ('fake', 'Fake')], max_length=255),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ActiveManagementPolicy',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
('description', models.TextField(blank=True, null=True)),
|
||||
('when_trading_time_violated', models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
@ -0,0 +1,58 @@
|
||||
# Generated by Django 4.1.7 on 2023-02-17 11:58
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0071_alter_account_exchange_activemanagementpolicy'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_asset_groups_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_crossfilter_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_max_loss_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_max_open_trades_per_symbol_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_max_open_trades_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_max_risk_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_position_size_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only'), ('adjust', 'Adjust violating trades')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_protection_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only'), ('adjust', 'Adjust violating trades')], default='none', max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='activemanagementpolicy',
|
||||
name='when_trends_violated',
|
||||
field=models.CharField(choices=[('none', 'None'), ('close', 'Close violating trades'), ('notify', 'Notify only')], default='none', max_length=255),
|
||||
),
|
||||
]
|
@ -0,0 +1,19 @@
|
||||
# Generated by Django 4.1.7 on 2023-02-17 13:16
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0072_activemanagementpolicy_when_asset_groups_violated_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='strategy',
|
||||
name='active_management_policy',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='core.activemanagementpolicy'),
|
||||
),
|
||||
]
|
@ -0,0 +1,61 @@
|
||||
{% load cache %}
|
||||
{% load cachalot cache %}
|
||||
{% get_last_invalidation 'core.AssetManagementPolicy' as last %}
|
||||
{% include 'mixins/partials/notify.html' %}
|
||||
{% cache 600 objects_active_management request.user.id object_list type last %}
|
||||
<table
|
||||
class="table is-fullwidth is-hoverable"
|
||||
hx-target="#{{ context_object_name }}-table"
|
||||
id="{{ context_object_name }}-table"
|
||||
hx-swap="outerHTML"
|
||||
hx-trigger="{{ context_object_name_singular }}Event from:body"
|
||||
hx-get="{{ list_url }}">
|
||||
<thead>
|
||||
<th>id</th>
|
||||
<th>user</th>
|
||||
<th>name</th>
|
||||
<th>description</th>
|
||||
<th>actions</th>
|
||||
</thead>
|
||||
{% for item in object_list %}
|
||||
<tr>
|
||||
<td>{{ item.id }}</td>
|
||||
<td>{{ item.user }}</td>
|
||||
<td>{{ item.name }}</td>
|
||||
<td>{{ item.description|truncatechars:80 }}</td>
|
||||
<td>
|
||||
<div class="buttons">
|
||||
<button
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
hx-get="{% url 'ams_update' type=type pk=item.id %}"
|
||||
hx-trigger="click"
|
||||
hx-target="#{{ type }}s-here"
|
||||
hx-swap="innerHTML"
|
||||
class="button">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-pencil"></i>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
hx-delete="{% url 'ams_delete' type=type pk=item.id %}"
|
||||
hx-trigger="click"
|
||||
hx-target="#modals-here"
|
||||
hx-swap="innerHTML"
|
||||
hx-confirm="Are you sure you wish to delete {{ item.name }}?"
|
||||
class="button">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
</table>
|
||||
{% endcache %}
|
@ -0,0 +1,211 @@
|
||||
from django.test import TestCase
|
||||
|
||||
from core.tests.helpers import StrategyMixin, SymbolPriceMock
|
||||
from core.trading.active_management import ActiveManagement
|
||||
from core.models import User, Account, ActiveManagementPolicy, Hook, Signal
|
||||
from unittest.mock import Mock, patch
|
||||
from core.lib.schemas.oanda_s import parse_time
|
||||
|
||||
class ActiveManagementTestCase(StrategyMixin, SymbolPriceMock, TestCase):
|
||||
def setUp(self):
|
||||
self.user = User.objects.create_user(
|
||||
username="testuser", email="test@example.com", password="test"
|
||||
)
|
||||
self.account = Account.objects.create(
|
||||
user=self.user,
|
||||
name="Test Account",
|
||||
exchange="fake",
|
||||
currency="USD",
|
||||
)
|
||||
self.account.supported_symbols = ["EUR_USD", "EUR_XXX", "USD_EUR", "XXX_EUR"]
|
||||
self.account.save()
|
||||
super().setUp()
|
||||
self.active_management_policy = ActiveManagementPolicy.objects.create(
|
||||
user=self.user,
|
||||
name="Test Policy",
|
||||
when_trading_time_violated="close",
|
||||
when_trends_violated="close",
|
||||
when_position_size_violated="close",
|
||||
when_protection_violated="close",
|
||||
when_asset_groups_violated="close",
|
||||
when_max_open_trades_violated="close",
|
||||
when_max_open_trades_per_symbol_violated="close",
|
||||
when_max_loss_violated="close",
|
||||
when_max_risk_violated="close",
|
||||
when_crossfilter_violated="close",
|
||||
)
|
||||
|
||||
self.strategy.active_management_policy = self.active_management_policy
|
||||
self.strategy.save()
|
||||
self.ams = ActiveManagement(self.strategy)
|
||||
self.trades = [
|
||||
{
|
||||
"id": "20083",
|
||||
"symbol": "EUR_USD",
|
||||
"price": "1.06331",
|
||||
"openTime": "2023-02-13T11:38:06.302917985Z", # Monday at 11:38
|
||||
"initialUnits": "10",
|
||||
"initialMarginRequired": "0.2966",
|
||||
"state": "OPEN",
|
||||
"currentUnits": "10",
|
||||
"realizedPL": "0.0000",
|
||||
"financing": "0.0000",
|
||||
"dividendAdjustment": "0.0000",
|
||||
"unrealizedPL": "-0.0008",
|
||||
"marginUsed": "0.2966",
|
||||
"takeProfitOrder": None,
|
||||
"stopLossOrder": None,
|
||||
"trailingStopLossOrder": None,
|
||||
"trailingStopValue": None,
|
||||
"side": "long",
|
||||
},
|
||||
{
|
||||
"id": "20083",
|
||||
"symbol": "EUR_USD",
|
||||
"price": "1.06331",
|
||||
"openTime": "2023-02-13T11:38:06.302917985Z", # Monday at 11:38
|
||||
"initialUnits": "10",
|
||||
"initialMarginRequired": "0.2966",
|
||||
"state": "OPEN",
|
||||
"currentUnits": "10",
|
||||
"realizedPL": "0.0000",
|
||||
"financing": "0.0000",
|
||||
"dividendAdjustment": "0.0000",
|
||||
"unrealizedPL": "-0.0008",
|
||||
"marginUsed": "0.2966",
|
||||
"takeProfitOrder": None,
|
||||
"stopLossOrder": None,
|
||||
"trailingStopLossOrder": None,
|
||||
"trailingStopValue": None,
|
||||
"side": "long",
|
||||
}
|
||||
]
|
||||
# Run parse_time on all items in trades
|
||||
for trade in self.trades:
|
||||
trade["openTime"] = parse_time(trade)
|
||||
self.ams.get_trades = self.fake_get_trades
|
||||
self.ams.get_balance = self.fake_get_balance
|
||||
# self.ams.trades = self.trades
|
||||
|
||||
def fake_get_trades(self):
|
||||
self.ams.trades = self.trades
|
||||
return self.trades
|
||||
|
||||
def fake_get_balance(self):
|
||||
return 10000
|
||||
|
||||
def fake_get_currencies(self, symbols):
|
||||
pass
|
||||
|
||||
def test_get_trades(self):
|
||||
trades = self.ams.get_trades()
|
||||
self.assertEqual(trades, self.trades)
|
||||
|
||||
def test_get_balance(self):
|
||||
balance = self.ams.get_balance()
|
||||
self.assertEqual(balance, 10000)
|
||||
|
||||
def check_violation(self, violation, calls, expected_action, expected_trades):
|
||||
"""
|
||||
Check that the violation was called with the expected action and trades.
|
||||
Matches the first argument of the call to the violation name.
|
||||
:param: violation: type of the violation to check against
|
||||
:param: calls: list of calls to the violation
|
||||
:param: expected_action: expected action to be called, close, notify, etc.
|
||||
:param: expected_trades: list of expected trades to be passed to the violation
|
||||
"""
|
||||
calls = list(calls)
|
||||
violation_calls = []
|
||||
for call in calls:
|
||||
if call[0][0] == violation:
|
||||
violation_calls.append(call)
|
||||
|
||||
self.assertEqual(len(violation_calls), len(expected_trades))
|
||||
for call in violation_calls:
|
||||
# Ensure the correct action has been called, like close
|
||||
self.assertEqual(call[0][1], expected_action)
|
||||
# Ensure the correct trade has been passed to the violation
|
||||
self.assertIn(call[0][2], expected_trades)
|
||||
|
||||
@patch("core.trading.active_management.ActiveManagement.handle_violation")
|
||||
def test_run_checks(self, handle_violation):
|
||||
self.ams.run_checks()
|
||||
self.assertEqual(handle_violation.call_count, 0)
|
||||
|
||||
@patch("core.trading.active_management.ActiveManagement.handle_violation")
|
||||
def test_trading_time_violated(self, handle_violation):
|
||||
self.trades[0]["openTime"] = "2023-02-17T11:38:06.302917Z" # Friday
|
||||
self.ams.run_checks()
|
||||
self.check_violation("trading_time", handle_violation.call_args_list, "close", [self.trades[0]])
|
||||
|
||||
def create_hook_signal(self):
|
||||
hook = Hook.objects.create(
|
||||
user=self.user,
|
||||
name="Test Hook",
|
||||
)
|
||||
signal = Signal.objects.create(
|
||||
user=self.user,
|
||||
name="Test Signal",
|
||||
hook=hook,
|
||||
type="trend",
|
||||
)
|
||||
return signal
|
||||
|
||||
@patch("core.trading.active_management.ActiveManagement.handle_violation")
|
||||
def test_trends_violated(self, handle_violation):
|
||||
signal = self.create_hook_signal()
|
||||
self.strategy.trend_signals.set([signal])
|
||||
self.strategy.trends = {"EUR_USD": "sell"}
|
||||
self.strategy.save()
|
||||
self.ams.run_checks()
|
||||
self.check_violation("trends", handle_violation.call_args_list, "close", self.trades)
|
||||
|
||||
@patch("core.trading.active_management.ActiveManagement.handle_violation")
|
||||
def test_trends_violated_none(self, handle_violation):
|
||||
signal = self.create_hook_signal()
|
||||
self.strategy.trend_signals.set([signal])
|
||||
self.strategy.trends = {"EUR_USD": "buy"}
|
||||
self.strategy.save()
|
||||
self.ams.run_checks()
|
||||
self.check_violation("trends", handle_violation.call_args_list, "close", [])
|
||||
|
||||
@patch("core.trading.active_management.ActiveManagement.handle_violation")
|
||||
def test_trends_violated_partial(self, handle_violation):
|
||||
signal = self.create_hook_signal()
|
||||
self.strategy.trend_signals.set([signal])
|
||||
self.strategy.trends = {"EUR_USD": "sell"}
|
||||
self.strategy.save()
|
||||
|
||||
# Change the side of the first trade to match the trends
|
||||
self.trades[0]["side"] = "short"
|
||||
self.ams.run_checks()
|
||||
|
||||
self.check_violation("trends", handle_violation.call_args_list, "close", [self.trades[1]])
|
||||
|
||||
@patch("core.trading.active_management.ActiveManagement.handle_violation")
|
||||
def test_position_size_violated(self, handle_violation):
|
||||
self.trades[0]["currentUnits"] = "100000"
|
||||
self.ams.run_checks()
|
||||
|
||||
self.check_violation("position_size", handle_violation.call_args_list, "close", [self.trades[0]])
|
||||
|
||||
def test_protection_violated(self):
|
||||
pass
|
||||
|
||||
def test_asset_groups_violated(self):
|
||||
pass
|
||||
|
||||
def test_max_open_trades_violated(self):
|
||||
pass
|
||||
|
||||
def test_max_open_trades_per_symbol_violated(self):
|
||||
pass
|
||||
|
||||
def test_max_loss_violated(self):
|
||||
pass
|
||||
|
||||
def test_max_risk_violated(self):
|
||||
pass
|
||||
|
||||
def test_crossfilter_violated(self):
|
||||
pass
|
@ -0,0 +1,37 @@
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from mixins.views import ObjectCreate, ObjectDelete, ObjectList, ObjectUpdate
|
||||
|
||||
from core.forms import ActiveManagementPolicyForm
|
||||
from core.models import ActiveManagementPolicy
|
||||
from core.util import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
class ActiveManagementPolicyList(LoginRequiredMixin, ObjectList):
|
||||
list_template = "partials/activemanagement-list.html"
|
||||
model = ActiveManagementPolicy
|
||||
page_title = "List of active management policies. Linked to strategies."
|
||||
|
||||
list_url_name = "ams"
|
||||
list_url_args = ["type"]
|
||||
|
||||
submit_url_name = "ams_create"
|
||||
|
||||
|
||||
class ActiveManagementPolicyCreate(LoginRequiredMixin, ObjectCreate):
|
||||
model = ActiveManagementPolicy
|
||||
form_class = ActiveManagementPolicyForm
|
||||
|
||||
submit_url_name = "ams_create"
|
||||
|
||||
|
||||
class ActiveManagementPolicyUpdate(LoginRequiredMixin, ObjectUpdate):
|
||||
model = ActiveManagementPolicy
|
||||
form_class = ActiveManagementPolicyForm
|
||||
|
||||
submit_url_name = "ams_update"
|
||||
|
||||
|
||||
class ActiveManagementPolicyDelete(LoginRequiredMixin, ObjectDelete):
|
||||
model = ActiveManagementPolicy
|
Loading…
Reference in New Issue