Compare commits

...

3 Commits

11 changed files with 456 additions and 24 deletions

View File

@ -30,6 +30,7 @@ from core.views import (
notifications,
positions,
profit,
risk,
signals,
strategies,
trades,
@ -214,4 +215,24 @@ urlpatterns = [
notifications.NotificationsUpdate.as_view(),
name="notifications_update",
),
path(
"risk/<str:type>/",
risk.RiskList.as_view(),
name="risks",
),
path(
"risk/<str:type>/create/",
risk.RiskCreate.as_view(),
name="risk_create",
),
path(
"risk/<str:type>/update/<str:pk>/",
risk.RiskUpdate.as_view(),
name="risk_update",
),
path(
"risk/<str:type>/delete/<str:pk>/",
risk.RiskDelete.as_view(),
name="risk_delete",
),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

View File

@ -7,6 +7,7 @@ from .models import (
Account,
Hook,
NotificationSettings,
RiskModel,
Signal,
Strategy,
Trade,
@ -110,19 +111,14 @@ class SignalForm(RestrictedFormMixin, ModelForm):
class AccountForm(RestrictedFormMixin, ModelForm):
class Meta:
model = Account
fields = (
"name",
"exchange",
"api_key",
"api_secret",
"sandbox",
)
fields = ("name", "exchange", "api_key", "api_secret", "sandbox", "risk_model")
help_texts = {
"name": "Name of the account. Informational only.",
"exchange": "The exchange to use for this account.",
"api_key": "The API key or username for the account.",
"api_secret": "The API secret or password/token for the account.",
"sandbox": "Whether to use the sandbox/demo or not.",
"risk_model": "The risk model to use for this account.",
}
@ -298,3 +294,24 @@ class NotificationSettingsForm(RestrictedFormMixin, ModelForm):
"ntfy_topic": "The topic to send notifications to.",
"ntfy_url": "Custom NTFY server. Leave blank to use the default server.",
}
class RiskModelForm(RestrictedFormMixin, ModelForm):
class Meta:
model = RiskModel
fields = (
"name",
"description",
"max_loss_percent",
"max_risk_percent",
"max_open_trades",
"max_open_trades_per_symbol",
)
help_texts = {
"name": "Name of the risk model. Informational only.",
"description": "Description of the risk model. Informational only.",
"max_loss_percent": "The maximum percent of the account balance that can be lost before we cease trading.",
"max_risk_percent": "The maximum percent of the account balance that can be risked on all open trades.",
"max_open_trades": "The maximum number of open trades.",
"max_open_trades_per_symbol": "The maximum number of open trades per symbol.",
}

View File

@ -0,0 +1,33 @@
# Generated by Django 4.1.4 on 2022-12-21 21:43
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0047_notificationsettings'),
]
operations = [
migrations.CreateModel(
name='RiskModel',
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)),
('max_loss_percent', models.FloatField(default=0.05)),
('max_risk_percent', models.FloatField(default=0.05)),
('max_open_trades', models.IntegerField(default=10)),
('max_open_trades_per_symbol', models.IntegerField(default=2)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='account',
name='riskmodel',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.riskmodel'),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 4.1.4 on 2022-12-21 21:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0048_riskmodel_account_riskmodel'),
]
operations = [
migrations.RenameField(
model_name='account',
old_name='riskmodel',
new_name='risk_model',
),
]

View File

@ -112,6 +112,9 @@ class Account(models.Model):
supported_symbols = models.JSONField(default=list)
instruments = models.JSONField(default=list)
currency = models.CharField(max_length=255, null=True, blank=True)
risk_model = models.ForeignKey(
"core.RiskModel", on_delete=models.SET_NULL, null=True, blank=True
)
def __str__(self):
name = f"{self.name} ({self.exchange})"
@ -375,20 +378,18 @@ class NotificationSettings(models.Model):
return f"Notification settings for {self.user}"
# class Perms(models.Model):
# class Meta:
# permissions = (
# ("bypass_hashing", "Can bypass field hashing"), #
# ("bypass_blacklist", "Can bypass the blacklist"), #
# ("bypass_encryption", "Can bypass field encryption"), #
# ("bypass_obfuscation", "Can bypass field obfuscation"), #
# ("bypass_delay", "Can bypass data delay"), #
# ("bypass_randomisation", "Can bypass data randomisation"), #
# ("post_irc", "Can post to IRC"),
# ("post_discord", "Can post to Discord"),
# ("query_search", "Can search with query strings"), #
# ("use_insights", "Can use the Insights page"),
# ("index_int", "Can use the internal index"),
# ("index_meta", "Can use the meta index"),
# ("restricted_sources", "Can access restricted sources"),
# )
class RiskModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
# Maximum amount of money to have lost from the initial balance to stop trading
max_loss_percent = models.FloatField(default=0.05)
# Maximum amount of money to risk on all open trades
max_risk_percent = models.FloatField(default=0.05)
# Maximum number of trades
max_open_trades = models.IntegerField(default=10)
# Maximum number of trades per symbol
max_open_trades_per_symbol = models.IntegerField(default=2)
def __str__(self):
return self.name

View File

@ -254,6 +254,9 @@
<a class="navbar-item" href="{% url 'tradingtimes' type='page' %}">
Trading Times
</a>
<a class="navbar-item" href="{% url 'risks' type='page' %}">
Risk Management
</a>
</div>
</div>
<div class="navbar-item has-dropdown is-hoverable">

View File

@ -0,0 +1,65 @@
{% include 'partials/notify.html' %}
<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>max loss percent</th>
<th>max risk percent</th>
<th>max open trades</th>
<th>max open trades per symbol</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 }}</td>
<td>{{ item.max_loss_percent }}</td>
<td>{{ item.max_risk_percent }}</td>
<td>{{ item.max_open_trades }}</td>
<td>{{ item.max_open_trades_per_symbol }}</td>
<td>
<div class="buttons">
<button
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
hx-get="{% url 'risk_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 'risk_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>

View File

View File

@ -0,0 +1,191 @@
from django.test import TestCase
from core.models import RiskModel, User
from core.trading import risk
class RiskModelTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username="testuser", email="test@example.com", password="test"
)
self.risk_model = RiskModel.objects.create(
user=self.user,
name="Test Risk Model",
max_loss_percent=50,
max_risk_percent=10,
max_open_trades=3,
max_open_trades_per_symbol=2,
)
self.account_initial_balance = 100
self.trade = {
"symbol": "XXXYYY",
"side": "BUY",
# We already calculated the TP percent loss relative to the account size
"tp_percent": 9,
"sl_percent": 9,
"tsl_percent": 9,
}
def test_check_max_loss(self):
"""
Check that we can open a trade within the max loss limit.
"""
account_balance = 100 # We have lost no money
allowed = risk.check_max_loss(
self.risk_model, self.account_initial_balance, account_balance
)
self.assertTrue(allowed)
def test_check_max_loss_fail_exact(self):
"""
Check that we cannot open a trade outside the max loss limit where the amount
lost is exactly the max loss limit.
"""
account_balance = 50 # We have lost 50% exactly
allowed = risk.check_max_loss(
self.risk_model, self.account_initial_balance, account_balance
)
self.assertFalse(allowed)
def test_check_max_loss_fail(self):
"""
Check that we cannot open a trade outside the max loss limit.
"""
account_balance = 49 # We have lost 51%
allowed = risk.check_max_loss(
self.risk_model, self.account_initial_balance, account_balance
)
self.assertFalse(allowed)
def test_check_max_risk(self):
"""
Check that we can open a trade within the max risk limit.
"""
account_trades = [self.trade]
allowed = risk.check_max_risk(self.risk_model, account_trades)
self.assertTrue(allowed)
def test_check_max_risk_multiple_trades(self):
"""
Check that we can open a trade within the max risk limit where there are
multiple trades.
"""
trade = self.trade.copy()
trade["sl_percent"] = 1
trade["tsl_percent"] = 1
account_trades = [trade] * 9
allowed = risk.check_max_risk(self.risk_model, account_trades)
self.assertTrue(allowed)
def test_check_max_risk_fail_exact(self):
"""
Check that we cannot open a trade outside the max risk limit where the amount
risked is exactly the max risk limit.
"""
trade = self.trade.copy()
trade["sl_percent"] = 10
account_trades = [trade]
allowed = risk.check_max_risk(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_risk_fail_exact_multiple_trades(self):
"""
Check that we cannot open a trade outside the max risk limit where the amount
risked is exactly the max risk limit with multiple trades.
"""
trade = self.trade.copy()
trade["sl_percent"] = 1
trade["tsl_percent"] = 1
account_trades = [trade] * 10
allowed = risk.check_max_risk(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_open_trades(self):
"""
Check that we can open a trade within the max open trades limit.
"""
account_trades = [self.trade] * 2
allowed = risk.check_max_open_trades(self.risk_model, account_trades)
self.assertTrue(allowed)
def test_check_max_open_trades_fail_exact(self):
"""
Check that we cannot open a trade at the max open trades limit.
"""
account_trades = [self.trade] * 3
allowed = risk.check_max_open_trades(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_open_trades_fail(self):
"""
Check that we cannot open a trade outside the max open trades limit.
"""
account_trades = [self.trade] * 4
allowed = risk.check_max_open_trades(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_open_trades_per_symbol(self):
"""
Check that we can open a trade within the max open trades per symbol limit.
"""
account_trades = [self.trade]
allowed = risk.check_max_open_trades_per_symbol(self.risk_model, account_trades)
self.assertTrue(allowed)
def test_check_max_open_trades_per_symbol_fail_exact(self):
"""
Check that we cannot open a trade at the max open trades per symbol limit.
"""
account_trades = [self.trade] * 2
allowed = risk.check_max_open_trades_per_symbol(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_open_trades_per_symbol_fail(self):
"""
Check that we cannot open a trade outside the max open trades per symbol limit.
"""
account_trades = [self.trade] * 3
allowed = risk.check_max_open_trades_per_symbol(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_open_trades_per_symbol_different_symbols(self):
"""
Check that we can open a trade within the max open trades per symbol limit with
different symbols.
"""
trade1 = self.trade.copy()
trade2 = self.trade.copy()
trade1["symbol"] = "ONE"
trade2["symbol"] = "TWO"
account_trades = [trade1, trade2]
allowed = risk.check_max_open_trades_per_symbol(self.risk_model, account_trades)
self.assertTrue(allowed)
def test_check_max_open_trades_per_symbol_fail_exact_different_symbols(self):
"""
Check that we cannot open a trade at the max open trades per symbol limit with
different symbols.
"""
trade1 = self.trade.copy()
trade2 = self.trade.copy()
trade1["symbol"] = "ONE"
trade2["symbol"] = "TWO"
account_trades = [trade1, trade2, trade1, trade2]
allowed = risk.check_max_open_trades_per_symbol(self.risk_model, account_trades)
self.assertFalse(allowed)
def test_check_max_open_trades_per_symbol_fail_different_symbols(self):
"""
Check that we cannot open a trade outside the max open trades per symbol limit
with different symbols.
"""
trade1 = self.trade.copy()
trade2 = self.trade.copy()
trade1["symbol"] = "ONE"
trade2["symbol"] = "TWO"
# Each one 3 times
account_trades = [trade1, trade2, trade1, trade2, trade1, trade2]
allowed = risk.check_max_open_trades_per_symbol(self.risk_model, account_trades)
self.assertFalse(allowed)

46
core/trading/risk.py Normal file
View File

@ -0,0 +1,46 @@
def check_max_loss(risk_model, initial_balance, account_balance):
"""
Check that the account balance is within the max loss limit.
"""
max_loss_percent = risk_model.max_loss_percent
max_loss = initial_balance * (max_loss_percent / 100)
return account_balance > max_loss
def check_max_risk(risk_model, account_trades):
"""
Check that all of the trades in the account are within the max risk limit.
"""
max_risk_percent = risk_model.max_risk_percent
total_risk = 0
for trade in account_trades:
max_tmp = []
if "sl_percent" in trade:
max_tmp.append(trade["sl_percent"])
if "tsl_percent" in trade:
max_tmp.append(trade["tsl_percent"])
total_risk += max(max_tmp)
return total_risk < max_risk_percent
def check_max_open_trades(risk_model, account_trades):
"""
Check that the number of trades in the account is within the max open trades limit.
"""
return len(account_trades) < risk_model.max_open_trades
def check_max_open_trades_per_symbol(risk_model, account_trades):
"""
Check we cannot open more trades per symbol than permissible.
"""
symbol_map = {}
for trade in account_trades:
symbol = trade["symbol"]
if symbol not in symbol_map:
symbol_map[symbol] = 0
symbol_map[symbol] += 1
for symbol, count in symbol_map.items():
if count >= risk_model.max_open_trades_per_symbol:
return False
return True

37
core/views/risk.py Normal file
View File

@ -0,0 +1,37 @@
from django.contrib.auth.mixins import LoginRequiredMixin
from core.forms import RiskModelForm
from core.models import RiskModel
from core.util import logs
from core.views import ObjectCreate, ObjectDelete, ObjectList, ObjectUpdate
log = logs.get_logger(__name__)
class RiskList(LoginRequiredMixin, ObjectList):
list_template = "partials/risk-list.html"
model = RiskModel
page_title = "List of risk management strategies. Linked to accounts."
list_url_name = "risks"
list_url_args = ["type"]
submit_url_name = "risk_create"
class RiskCreate(LoginRequiredMixin, ObjectCreate):
model = RiskModel
form_class = RiskModelForm
submit_url_name = "risk_create"
class RiskUpdate(LoginRequiredMixin, ObjectUpdate):
model = RiskModel
form_class = RiskModelForm
submit_url_name = "risk_update"
class RiskDelete(LoginRequiredMixin, ObjectDelete):
model = RiskModel