329 lines
13 KiB
Python
329 lines
13 KiB
Python
from django import forms
|
|
from django.contrib.auth.forms import UserCreationForm
|
|
from django.core.exceptions import FieldDoesNotExist
|
|
from django.forms import ModelForm
|
|
|
|
from .models import (
|
|
Account,
|
|
Hook,
|
|
NotificationSettings,
|
|
RiskModel,
|
|
Signal,
|
|
Strategy,
|
|
Trade,
|
|
TradingTime,
|
|
User,
|
|
)
|
|
|
|
# flake8: noqa: E501
|
|
|
|
|
|
class RestrictedFormMixin:
|
|
"""
|
|
This mixin is used to restrict the queryset of a form to the current user.
|
|
The request object is passed from the view.
|
|
Fieldargs is used to pass additional arguments to the queryset filter.
|
|
"""
|
|
|
|
fieldargs = {}
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
# self.fieldargs = {}
|
|
self.request = kwargs.pop("request")
|
|
super().__init__(*args, **kwargs)
|
|
for field in self.fields:
|
|
# Check it's not something like a CharField which has no queryset
|
|
if not hasattr(self.fields[field], "queryset"):
|
|
continue
|
|
|
|
model = self.fields[field].queryset.model
|
|
# Check if the model has a user field
|
|
try:
|
|
model._meta.get_field("user")
|
|
# Add the user to the queryset filters
|
|
self.fields[field].queryset = model.objects.filter(
|
|
user=self.request.user, **self.fieldargs.get(field, {})
|
|
)
|
|
except FieldDoesNotExist:
|
|
pass
|
|
|
|
|
|
class NewUserForm(UserCreationForm):
|
|
email = forms.EmailField(required=True)
|
|
|
|
class Meta:
|
|
model = User
|
|
fields = (
|
|
"username",
|
|
"email",
|
|
"first_name",
|
|
"last_name",
|
|
"password1",
|
|
"password2",
|
|
)
|
|
|
|
def save(self, commit=True):
|
|
user = super(NewUserForm, self).save(commit=False)
|
|
user.email = self.cleaned_data["email"]
|
|
if commit:
|
|
user.save()
|
|
return user
|
|
|
|
|
|
class CustomUserCreationForm(UserCreationForm):
|
|
class Meta:
|
|
model = User
|
|
fields = "__all__"
|
|
|
|
|
|
class HookForm(RestrictedFormMixin, ModelForm):
|
|
class Meta:
|
|
model = Hook
|
|
fields = (
|
|
"name",
|
|
"hook",
|
|
)
|
|
help_texts = {
|
|
"name": "Name of the hook. Informational only.",
|
|
"hook": "The URL slug to use for the hook. Make it unique.",
|
|
}
|
|
|
|
|
|
class SignalForm(RestrictedFormMixin, ModelForm):
|
|
class Meta:
|
|
model = Signal
|
|
fields = (
|
|
"name",
|
|
"signal",
|
|
"hook",
|
|
"type",
|
|
"direction",
|
|
)
|
|
help_texts = {
|
|
"name": "Name of the signal. Informational only.",
|
|
"signal": "The name of the signal in Drakdoo. Copy it from there.",
|
|
"hook": "The hook this signal belongs to.",
|
|
"type": "Whether the signal is used for entering or exiting trades, or determining the trend.",
|
|
"direction": "The direction of the signal. This is used to determine if the signal is a buy or sell.",
|
|
}
|
|
|
|
|
|
class AccountForm(RestrictedFormMixin, ModelForm):
|
|
class Meta:
|
|
model = Account
|
|
fields = (
|
|
"name",
|
|
"exchange",
|
|
"api_key",
|
|
"api_secret",
|
|
"sandbox",
|
|
"enabled",
|
|
"risk_model",
|
|
"initial_balance",
|
|
)
|
|
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.",
|
|
"enabled": "Whether the account is enabled.",
|
|
"risk_model": "The risk model to use for this account.",
|
|
"initial_balance": "The initial balance of the account.",
|
|
}
|
|
|
|
|
|
class StrategyForm(RestrictedFormMixin, ModelForm):
|
|
fieldargs = {
|
|
"entry_signals": {"type": "entry"},
|
|
"exit_signals": {"type": "exit"},
|
|
"trend_signals": {"type": "trend"},
|
|
}
|
|
|
|
class Meta:
|
|
model = Strategy
|
|
fields = (
|
|
"name",
|
|
"description",
|
|
"account",
|
|
"trading_times",
|
|
"order_type",
|
|
"time_in_force",
|
|
"entry_signals",
|
|
"exit_signals",
|
|
"trend_signals",
|
|
"enabled",
|
|
"take_profit_percent",
|
|
"stop_loss_percent",
|
|
"trailing_stop_loss_percent",
|
|
"price_slippage_percent",
|
|
"callback_price_deviation_percent",
|
|
"trade_size_percent",
|
|
)
|
|
|
|
help_texts = {
|
|
"name": "Name of the strategy. Informational only.",
|
|
"description": "Description of the strategy. Informational only.",
|
|
"account": "The account to use for this strategy.",
|
|
"trading_times": "When the strategy will place new trades.",
|
|
"order_type": "Market: Buy/Sell at the current market price. Limit: Buy/Sell at a specified price. Limits protect you more against market slippage.",
|
|
"time_in_force": "The time in force controls how the order is executed.",
|
|
"entry_signals": "Callbacks received to these signals will trigger a trade.",
|
|
"exit_signals": "Callbacks received to these signals will close all trades for the symbol on the account.",
|
|
"trend_signals": "Callbacks received to these signals will limit the trading direction of the given symbol to the callback direction until further notice.",
|
|
"enabled": "Whether the strategy is enabled.",
|
|
"take_profit_percent": "The take profit will be set at this percentage above/below the entry price.",
|
|
"stop_loss_percent": "The stop loss will be set at this percentage above/below the entry price.",
|
|
"trailing_stop_loss_percent": "The trailing stop loss will be set at this percentage above/below the entry price. A trailing stop loss will follow the price as it moves in your favor.",
|
|
"price_slippage_percent": "The price slippage is the maximum percent the price can move against you before the trade is cancelled. Limit orders will be set at this percentage against your favour. Market orders will have a price bound set if this is supported.",
|
|
"callback_price_deviation_percent": "The callback price deviation is the maximum percent the price can change between receiving the callback and acting on it. This protects against rogue or delayed callbacks. Keep it low.",
|
|
"trade_size_percent": "Percentage of the account balance to use for each trade.",
|
|
}
|
|
|
|
entry_signals = forms.ModelMultipleChoiceField(
|
|
queryset=Signal.objects.all(),
|
|
widget=forms.CheckboxSelectMultiple,
|
|
help_text=Meta.help_texts["entry_signals"],
|
|
required=False,
|
|
)
|
|
exit_signals = forms.ModelMultipleChoiceField(
|
|
queryset=Signal.objects.all(),
|
|
widget=forms.CheckboxSelectMultiple,
|
|
help_text=Meta.help_texts["exit_signals"],
|
|
required=False,
|
|
)
|
|
trend_signals = forms.ModelMultipleChoiceField(
|
|
queryset=Signal.objects.all(),
|
|
widget=forms.CheckboxSelectMultiple,
|
|
help_text=Meta.help_texts["trend_signals"],
|
|
required=False,
|
|
)
|
|
trading_times = forms.ModelMultipleChoiceField(
|
|
queryset=TradingTime.objects.all(), widget=forms.CheckboxSelectMultiple
|
|
)
|
|
|
|
def clean(self):
|
|
super(StrategyForm, self).clean()
|
|
entry_signals = self.cleaned_data.get("entry_signals")
|
|
exit_signals = self.cleaned_data.get("exit_signals")
|
|
for entry in entry_signals.all():
|
|
if entry in exit_signals.all():
|
|
self._errors["entry_signals"] = self.error_class(
|
|
[
|
|
"You cannot bet against yourself. Do not use the same signal for entry and exit."
|
|
]
|
|
)
|
|
for exit in exit_signals.all():
|
|
if exit in entry_signals.all():
|
|
self._errors["exit_signals"] = self.error_class(
|
|
[
|
|
"You cannot bet against yourself. Do not use the same signal for entry and exit."
|
|
]
|
|
)
|
|
# Get all the directions for entry and exit signals
|
|
entries_set = set([x.direction for x in entry_signals.all()])
|
|
exits_set = set([x.direction for x in exit_signals.all()])
|
|
|
|
# Make sure both fields are filled before we check this
|
|
if entries_set and exits_set:
|
|
# Combine them into one set
|
|
check_set = set()
|
|
check_set.update(entries_set, exits_set)
|
|
|
|
# If the length is 1, they are all the same direction
|
|
if len(check_set) == 1:
|
|
self._errors["entry_signals"] = self.error_class(
|
|
[
|
|
"You cannot have entry and exit signals that are the same direction. At least one must be opposing."
|
|
]
|
|
)
|
|
self._errors["exit_signals"] = self.error_class(
|
|
[
|
|
"You cannot have entry and exit signals that are the same direction. At least one must be opposing."
|
|
]
|
|
)
|
|
|
|
|
|
class TradeForm(RestrictedFormMixin, ModelForm):
|
|
class Meta:
|
|
model = Trade
|
|
fields = (
|
|
"account",
|
|
"symbol",
|
|
"type",
|
|
"time_in_force",
|
|
"amount",
|
|
"price",
|
|
"stop_loss",
|
|
"trailing_stop_loss",
|
|
"take_profit",
|
|
"direction",
|
|
)
|
|
help_texts = {
|
|
"account": "The account to use for this trade.",
|
|
"symbol": "The symbol to trade.",
|
|
"type": "Market: Buy/Sell at the current market price. Limit: Buy/Sell at a specified price. Limits protect you more against market slippage.",
|
|
"time_in_force": "The time in force controls how the order is executed.",
|
|
"amount": "The amount to trade in the quote currency (the second part of the symbol if applicable, otherwise your account base currency).",
|
|
"price": "The price to trade at. Sets this price as the trigger price for limit orders. Sets a price bound (if supported) for market orders.",
|
|
"stop_loss": "The stop loss price. This will be set at the specified price.",
|
|
"trailing_stop_loss": "The trailing stop loss price. This will be set at the specified price and will follow the price as it moves in your favor.",
|
|
"take_profit": "The take profit price. This will be set at the specified price.",
|
|
"direction": "The direction of the trade. This is used to determine if the trade is a buy or sell.",
|
|
}
|
|
|
|
|
|
class TradingTimeForm(RestrictedFormMixin, ModelForm):
|
|
class Meta:
|
|
model = TradingTime
|
|
fields = (
|
|
"name",
|
|
"description",
|
|
"start_day",
|
|
"start_time",
|
|
"end_day",
|
|
"end_time",
|
|
)
|
|
help_texts = {
|
|
"name": "Name of the trading time. Informational only.",
|
|
"description": "Description of the trading time. Informational only.",
|
|
"start_day": "The day of the week to start trading.",
|
|
"start_time": "The time of day to start trading.",
|
|
"end_day": "The day of the week to stop trading.",
|
|
"end_time": "The time of day to stop trading.",
|
|
}
|
|
|
|
|
|
class NotificationSettingsForm(RestrictedFormMixin, ModelForm):
|
|
class Meta:
|
|
model = NotificationSettings
|
|
fields = (
|
|
"ntfy_topic",
|
|
"ntfy_url",
|
|
)
|
|
help_texts = {
|
|
"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.",
|
|
}
|