Implement strategies and posting trades
parent
7e4f3f52d1
commit
061c6f6ca7
@ -0,0 +1,115 @@
|
||||
from alpaca.common.exceptions import APIError
|
||||
|
||||
from core.models import Strategy, Trade
|
||||
from core.util import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
def get_balance(account):
|
||||
account_info = account.client.get_account()
|
||||
cash = account_info["equity"]
|
||||
try:
|
||||
return float(cash)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def get_market_value(account, symbol):
|
||||
try:
|
||||
position = account.client.get_position(symbol)
|
||||
return float(position["market_value"])
|
||||
except APIError:
|
||||
return False
|
||||
|
||||
|
||||
def execute_strategy(callback, strategy):
|
||||
cash_balance = get_balance(strategy.account)
|
||||
log.debug(f"Cash balance: {cash_balance}")
|
||||
if not cash_balance:
|
||||
return None
|
||||
|
||||
user = strategy.user
|
||||
account = strategy.account
|
||||
hook = callback.hook
|
||||
base = callback.base
|
||||
quote = callback.quote
|
||||
direction = hook.direction
|
||||
if quote not in ["usd", "usdt", "usdc", "busd"]:
|
||||
log.error(f"Quote not compatible with Dollar: {quote}")
|
||||
return False
|
||||
quote = "usd" # TODO: MASSIVE HACK
|
||||
symbol = f"{base.upper()}/{quote.upper()}"
|
||||
|
||||
if symbol not in account.supported_assets:
|
||||
log.error(f"Symbol not supported by account: {symbol}")
|
||||
return False
|
||||
|
||||
print(f"Identified pair from callback {symbol}")
|
||||
|
||||
# market_from_alpaca = get_market_value(account, symbol)
|
||||
# change_percent = abs(((float(market_from_alpaca)-price)/price)*100)
|
||||
# if change_percent > strategy.price_slippage_percent:
|
||||
# log.error(f"Price slippage too high: {change_percent}")
|
||||
# return False
|
||||
|
||||
# type = "limit"
|
||||
type = "market"
|
||||
trade_size_as_ratio = strategy.trade_size_percent / 100
|
||||
log.debug(f"Trade size as ratio: {trade_size_as_ratio}")
|
||||
amount_usd = trade_size_as_ratio * cash_balance
|
||||
log.debug(f"Trade size: {amount_usd}")
|
||||
price = callback.price
|
||||
if not price:
|
||||
return
|
||||
log.debug(f"Extracted price of quote: {price}")
|
||||
|
||||
# We can do this because the quote IS in $ or equivalent
|
||||
trade_size_in_quote = amount_usd / price
|
||||
log.debug(f"Trade size in quote: {trade_size_in_quote}")
|
||||
|
||||
# calculate sl/tp
|
||||
stop_loss_as_ratio = strategy.stop_loss_percent / 100
|
||||
take_profit_as_ratio = strategy.take_profit_percent / 100
|
||||
log.debug(f"Stop loss as ratio: {stop_loss_as_ratio}")
|
||||
log.debug(f"Take profit as ratio: {take_profit_as_ratio}")
|
||||
|
||||
stop_loss_subtract = price * stop_loss_as_ratio
|
||||
take_profit_add = price * take_profit_as_ratio
|
||||
log.debug(f"Stop loss subtract: {stop_loss_subtract}")
|
||||
log.debug(f"Take profit add: {take_profit_add}")
|
||||
|
||||
stop_loss = price - stop_loss_subtract
|
||||
take_profit = price + take_profit_add
|
||||
|
||||
log.debug(f"Stop loss: {stop_loss}")
|
||||
log.debug(f"Take profit: {take_profit}")
|
||||
|
||||
new_trade = Trade.objects.create(
|
||||
user=user,
|
||||
account=account,
|
||||
hook=hook,
|
||||
symbol=symbol,
|
||||
type=type,
|
||||
# amount_usd=amount_usd,
|
||||
amount=trade_size_in_quote,
|
||||
# price=price,
|
||||
stop_loss=stop_loss,
|
||||
take_profit=take_profit,
|
||||
direction=direction,
|
||||
)
|
||||
new_trade.save()
|
||||
posted, info = new_trade.post()
|
||||
log.debug(f"Posted trade: {posted} - {info}")
|
||||
|
||||
|
||||
def process_callback(callback):
|
||||
log.info(f"Received callback for {callback.hook}")
|
||||
strategies = Strategy.objects.filter(hooks=callback.hook, enabled=True)
|
||||
log.debug(f"Matched strategies: {strategies}")
|
||||
for strategy in strategies:
|
||||
log.debug(f"Executing strategy {strategy}")
|
||||
if callback.hook.user != strategy.user:
|
||||
log.error("Ownership differs between callback and strategy.")
|
||||
return
|
||||
execute_strategy(callback, strategy)
|
@ -1,5 +1,83 @@
|
||||
# Trade handling
|
||||
from alpaca.common.exceptions import APIError
|
||||
from alpaca.trading.enums import OrderSide, TimeInForce
|
||||
from alpaca.trading.requests import LimitOrderRequest, MarketOrderRequest
|
||||
|
||||
from core.util import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
def sync_trades_with_db(user):
|
||||
pass
|
||||
|
||||
|
||||
def post_trade(trade):
|
||||
# the trade is not placed yet
|
||||
trading_client = trade.account.get_client()
|
||||
if trade.direction == "buy":
|
||||
direction = OrderSide.BUY
|
||||
elif trade.direction == "sell":
|
||||
direction = OrderSide.SELL
|
||||
else:
|
||||
raise Exception("Unknown direction")
|
||||
|
||||
cast = {"symbol": trade.symbol, "side": direction, "time_in_force": TimeInForce.IOC}
|
||||
if trade.amount is not None:
|
||||
cast["qty"] = trade.amount
|
||||
if trade.amount_usd is not None:
|
||||
cast["notional"] = trade.amount_usd
|
||||
if not trade.amount and not trade.amount_usd:
|
||||
return (False, "No amount specified")
|
||||
if trade.take_profit:
|
||||
cast["take_profit"] = {"limit_price": trade.take_profit}
|
||||
if trade.stop_loss:
|
||||
stop_limit_price = trade.stop_loss - (trade.stop_loss * 0.005)
|
||||
cast["stop_loss"] = {
|
||||
"stop_price": trade.stop_loss,
|
||||
"limit_price": stop_limit_price,
|
||||
}
|
||||
if trade.type == "market":
|
||||
market_order_data = MarketOrderRequest(**cast)
|
||||
try:
|
||||
order = trading_client.submit_order(order_data=market_order_data)
|
||||
except APIError as e:
|
||||
log.error(f"Error placing market order: {e}")
|
||||
return (False, e)
|
||||
elif trade.type == "limit":
|
||||
if not trade.price:
|
||||
return (False, "Limit order with no price")
|
||||
cast["limit_price"] = trade.price
|
||||
limit_order_data = LimitOrderRequest(**cast)
|
||||
try:
|
||||
order = trading_client.submit_order(order_data=limit_order_data)
|
||||
except APIError as e:
|
||||
log.error(f"Error placing limit order: {e}")
|
||||
return (False, e)
|
||||
|
||||
print("ORDER", order)
|
||||
else:
|
||||
raise Exception("Unknown trade type")
|
||||
trade.response = order
|
||||
trade.status = "posted"
|
||||
trade.order_id = order["id"]
|
||||
trade.client_order_id = order["client_order_id"]
|
||||
trade.save()
|
||||
return (True, order)
|
||||
|
||||
|
||||
def update_trade(self):
|
||||
pass
|
||||
|
||||
|
||||
def close_trade(trade):
|
||||
pass
|
||||
|
||||
|
||||
def get_position_info(account, asset_id):
|
||||
trading_client = account.get_client()
|
||||
try:
|
||||
position = trading_client.get_open_position(asset_id)
|
||||
except APIError as e:
|
||||
return (False, e)
|
||||
return (True, position)
|
||||
|
@ -0,0 +1,27 @@
|
||||
# Generated by Django 4.1.2 on 2022-10-25 21:08
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0014_alter_account_exchange'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Strategy',
|
||||
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)),
|
||||
('enabled', models.BooleanField(default=False)),
|
||||
('take_profit_percent', models.FloatField(default=300.0)),
|
||||
('stop_loss_percent', models.FloatField(default=100.0)),
|
||||
('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.account')),
|
||||
('hooks', models.ManyToManyField(to='core.hook')),
|
||||
],
|
||||
),
|
||||
]
|
@ -0,0 +1,27 @@
|
||||
# Generated by Django 4.1.2 on 2022-10-25 21:26
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0015_strategy'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='strategy',
|
||||
name='user',
|
||||
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='trade',
|
||||
name='user',
|
||||
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
|
||||
preserve_default=False,
|
||||
),
|
||||
]
|
@ -0,0 +1,24 @@
|
||||
# Generated by Django 4.1.2 on 2022-10-26 09:34
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0016_strategy_user_trade_user'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='hook',
|
||||
name='direction',
|
||||
field=models.CharField(choices=[('buy', 'Buy'), ('sell', 'Sell')], default='buy', max_length=255),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='strategy',
|
||||
name='price_slippage_percent',
|
||||
field=models.FloatField(default=2.5),
|
||||
),
|
||||
]
|
@ -0,0 +1,28 @@
|
||||
# Generated by Django 4.1.2 on 2022-10-26 09:54
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0017_hook_direction_strategy_price_slippage_percent'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='strategy',
|
||||
name='trade_size_percent',
|
||||
field=models.FloatField(default=2.5),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='trade',
|
||||
name='amount_usd',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='trade',
|
||||
name='amount',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
]
|
@ -0,0 +1,33 @@
|
||||
# Generated by Django 4.1.2 on 2022-10-27 16:33
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0018_strategy_trade_size_percent_trade_amount_usd_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='account',
|
||||
name='supported_symbols',
|
||||
field=models.JSONField(default=list),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='strategy',
|
||||
name='stop_loss_percent',
|
||||
field=models.FloatField(default=1.0),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='strategy',
|
||||
name='take_profit_percent',
|
||||
field=models.FloatField(default=3.0),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='trade',
|
||||
name='symbol',
|
||||
field=models.CharField(max_length=255),
|
||||
),
|
||||
]
|
@ -0,0 +1,54 @@
|
||||
# Generated by Django 4.1.2 on 2022-10-27 16:51
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0019_account_supported_symbols_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RenameField(
|
||||
model_name='callback',
|
||||
old_name='market_item',
|
||||
new_name='base',
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='callback',
|
||||
old_name='market_contract',
|
||||
new_name='contract',
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='callback',
|
||||
old_name='market_exchange',
|
||||
new_name='exchange',
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='callback',
|
||||
old_name='market_currency',
|
||||
new_name='quote',
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='callback',
|
||||
old_name='timestamp_sent',
|
||||
new_name='sent',
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='callback',
|
||||
old_name='timestamp_trade',
|
||||
new_name='trade',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='callback',
|
||||
name='price',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='callback',
|
||||
name='symbol',
|
||||
field=models.CharField(default='NUL/NUL', max_length=255),
|
||||
preserve_default=False,
|
||||
),
|
||||
]
|
@ -0,0 +1,88 @@
|
||||
{% include 'partials/notify.html' %}
|
||||
|
||||
<table class="table is-fullwidth is-hoverable" id="strategies-table">
|
||||
<thead>
|
||||
<th>id</th>
|
||||
<th>name</th>
|
||||
<th>description</th>
|
||||
<th>account</th>
|
||||
<th>enabled</th>
|
||||
<th>TP</th>
|
||||
<th>SL</th>
|
||||
<th>actions</th>
|
||||
</thead>
|
||||
{% for item in items %}
|
||||
<tr>
|
||||
<td>{{ item.id }}</td>
|
||||
<td>{{ item.name }}</td>
|
||||
<td>{{ item.description }}</td>
|
||||
<td>{{ item.account }}</td>
|
||||
<td>
|
||||
{% if item.enabled %}
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-check"></i>
|
||||
</span>
|
||||
{% else %}
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ item.take_profit_percent }}</td>
|
||||
<td>{{ item.stop_loss_percent }}</td>
|
||||
<td>
|
||||
<div class="buttons">
|
||||
<button
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
hx-get="{% url 'strategies_action' type=type strategy_id=item.id %}"
|
||||
hx-trigger="click"
|
||||
hx-target="#{{ type }}s-here"
|
||||
class="button is-info">
|
||||
<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 'strategies_action' type=type strategy_id=item.id %}"
|
||||
hx-trigger="click"
|
||||
hx-target="#strategies-table"
|
||||
class="button is-danger">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-trash"></i>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
{% if type == 'page' %}
|
||||
<a href="{% url 'strategies_action' type=type strategy_id=item.id %}"><button
|
||||
class="button is-success">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-eye"></i>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</a>
|
||||
{% else %}
|
||||
<button
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
hx-get="{% url 'strategies_action' type=type strategy_id=item.id %}"
|
||||
hx-trigger="click"
|
||||
hx-target="#{{ type }}s-here"
|
||||
class="button is-success">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-eye"></i>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
</table>
|
@ -0,0 +1,19 @@
|
||||
{% extends "base.html" %}
|
||||
{% load static %}
|
||||
{% load crispy_forms_tags %}
|
||||
|
||||
{% block content %}
|
||||
<section class="hero is-fullheight">
|
||||
<div class="hero-body">
|
||||
<div class="container">
|
||||
<div class="columns is-centered">
|
||||
<div class="column is-5-tablet is-4-desktop is-3-widescreen">
|
||||
<div class="box">
|
||||
<p class="has-text-danger">Registration closed.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
@ -0,0 +1,31 @@
|
||||
{% include 'partials/notify.html' %}
|
||||
|
||||
{% load crispy_forms_tags %}
|
||||
|
||||
{% load crispy_forms_bulma_field %}
|
||||
<form
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
{% if strategy_id is not None %}
|
||||
hx-put="{% url 'strategies_action' type=type strategy_id=strategy_id %}"
|
||||
{% else %}
|
||||
hx-put="{% url 'strategies_action' type=type %}"
|
||||
{% endif %}
|
||||
hx-target="#strategies-table"
|
||||
hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
{{ form|crispy }}
|
||||
<button
|
||||
type="button"
|
||||
class="button is-light modal-close-button">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" class="button is-info modal-close-button">Submit</button>
|
||||
</form>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -1,19 +1,6 @@
|
||||
<div class="buttons">
|
||||
<button
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
hx-get="#"
|
||||
hx-trigger="click"
|
||||
hx-target="#modals-here"
|
||||
class="button is-info">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-plus"></i>
|
||||
</span>
|
||||
<span>Trade</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<h1 class="title is-4">Live positions from all exchanges</h1>
|
||||
<h1 class="subtitle">Manual trades are editable under "Bot Trades" tab.</h1>
|
||||
|
||||
{% include 'partials/notify.html' %}
|
||||
{% include 'partials/position-list.html' %}
|
||||
|
||||
{% include 'partials/position-list.html' %}
|
@ -0,0 +1,21 @@
|
||||
{% include 'partials/notify.html' %}
|
||||
<h1 class="title is-4">List of strategies</h1>
|
||||
|
||||
<div class="buttons">
|
||||
<button
|
||||
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||
hx-get="{% url 'strategies_action' type=type %}"
|
||||
hx-trigger="click"
|
||||
hx-target="#modals-here"
|
||||
class="button is-info">
|
||||
<span class="icon-text">
|
||||
<span class="icon">
|
||||
<i class="fa-solid fa-plus"></i>
|
||||
</span>
|
||||
<span>Strategy</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{% include 'partials/strategy-list.html' %}
|
||||
|
@ -0,0 +1,20 @@
|
||||
{% include 'partials/notify.html' %}
|
||||
<h1 class="title">Live information</h1>
|
||||
<table class="table is-fullwidth is-hoverable">
|
||||
<thead>
|
||||
<th>attribute</th>
|
||||
<th>value</th>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for key, item in items.items %}
|
||||
<tr>
|
||||
<th>{{ key }}</th>
|
||||
<td>
|
||||
{% if item is not None %}
|
||||
{{ item }}
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
@ -0,0 +1,188 @@
|
||||
import uuid
|
||||
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.http import HttpResponseBadRequest
|
||||
from django.shortcuts import render
|
||||
from django.views import View # , CreateView, UpdateView, DeleteView
|
||||
from rest_framework.parsers import FormParser
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from core.forms import StrategyForm
|
||||
from core.models import Strategy
|
||||
from core.util import logs
|
||||
|
||||
# from django.urls import reverse
|
||||
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
def get_strategies(user):
|
||||
strategies = Strategy.objects.filter(user=user)
|
||||
return strategies
|
||||
|
||||
|
||||
class Strategies(LoginRequiredMixin, View):
|
||||
allowed_types = ["modal", "widget", "window", "page"]
|
||||
window_content = "window-content/strategies.html"
|
||||
|
||||
async def get(self, request, type):
|
||||
if type not in self.allowed_types:
|
||||
return HttpResponseBadRequest
|
||||
template_name = f"wm/{type}.html"
|
||||
unique = str(uuid.uuid4())[:8]
|
||||
strategies = get_strategies(request.user)
|
||||
if type == "page":
|
||||
type = "modal"
|
||||
context = {
|
||||
"title": f"Accounts ({type})",
|
||||
"unique": unique,
|
||||
"window_content": self.window_content,
|
||||
"items": strategies,
|
||||
"type": type,
|
||||
}
|
||||
return render(request, template_name, context)
|
||||
|
||||
|
||||
# class AddStrategy(CreateView):
|
||||
# model = Strategy
|
||||
# form_class = StrategyForm
|
||||
# template_name = "window-content/add-strategy.html"
|
||||
# success_url = reverse("strategies")
|
||||
|
||||
# def form_valid(self, form):
|
||||
# form.instance.user = self.request.user
|
||||
# return super().form_valid(form)
|
||||
|
||||
# def get_context_data(self, **kwargs):
|
||||
# context = super().get_context_data(**kwargs)
|
||||
# context["title"] = "Add Strategy"
|
||||
# context["window_content"] = "window-content/add_strategy.html"
|
||||
# return context
|
||||
|
||||
|
||||
class StrategiesAction(LoginRequiredMixin, APIView):
|
||||
allowed_types = ["modal", "widget", "window", "page"]
|
||||
window_content = "window-content/add-strategy.html"
|
||||
parser_classes = [FormParser]
|
||||
|
||||
def get(self, request, type, strategy_id=None):
|
||||
"""
|
||||
Get the form for adding or editing a strategy.
|
||||
:param strategy_id: The id of the strategy to edit. Optional.
|
||||
"""
|
||||
if type not in self.allowed_types:
|
||||
return HttpResponseBadRequest
|
||||
template_name = f"wm/{type}.html"
|
||||
unique = str(uuid.uuid4())[:8]
|
||||
if strategy_id:
|
||||
try:
|
||||
account = Strategy.objects.get(id=strategy_id)
|
||||
form = StrategyForm(instance=account)
|
||||
except Strategy.DoesNotExist:
|
||||
message = "Strategy does not exist"
|
||||
message_class = "danger"
|
||||
context = {
|
||||
"message": message,
|
||||
"message_class": message_class,
|
||||
"window_content": self.window_content,
|
||||
}
|
||||
return render(request, template_name, context)
|
||||
else:
|
||||
form = StrategyForm()
|
||||
if type == "page":
|
||||
type = "modal"
|
||||
context = {
|
||||
"form": form,
|
||||
"strategy_id": strategy_id,
|
||||
"type": type,
|
||||
"unique": unique,
|
||||
"window_content": self.window_content,
|
||||
}
|
||||
|
||||
return render(request, template_name, context)
|
||||
|
||||
def put(self, request, type, strategy_id=None):
|
||||
"""
|
||||
Add or edit a account.
|
||||
:param account_id: The id of the strategy to edit. Optional.
|
||||
"""
|
||||
if type not in self.allowed_types:
|
||||
return HttpResponseBadRequest
|
||||
message = None
|
||||
message_class = "success"
|
||||
|
||||
if strategy_id:
|
||||
try:
|
||||
form = StrategyForm(
|
||||
request.data,
|
||||
instance=Strategy.objects.get(
|
||||
id=strategy_id, account__user=request.user
|
||||
),
|
||||
)
|
||||
except Strategy.DoesNotExist:
|
||||
message = "Strategy does not exist"
|
||||
message_class = "danger"
|
||||
context = {
|
||||
"message": message,
|
||||
"class": message_class,
|
||||
}
|
||||
return render(request, self.template_name, context)
|
||||
else:
|
||||
form = StrategyForm(request.data)
|
||||
if form.is_valid():
|
||||
hooks = list(form.cleaned_data.get("hooks"))
|
||||
strategy = form.save(commit=False)
|
||||
strategy.user = request.user
|
||||
strategy.hooks.set(hooks)
|
||||
strategy.save()
|
||||
print("HOOKS SET", strategy.hooks)
|
||||
if strategy_id:
|
||||
message = f"Strategy {strategy_id} edited successfully"
|
||||
else:
|
||||
message = f"Strategy {strategy.id} added successfully"
|
||||
else:
|
||||
message = "Error adding strategy"
|
||||
message_class = "danger"
|
||||
|
||||
accounts = get_strategies(request.user)
|
||||
|
||||
context = {
|
||||
"items": accounts,
|
||||
"type": type,
|
||||
}
|
||||
if message:
|
||||
context["message"] = message
|
||||
context["class"] = message_class
|
||||
template_name = "partials/strategy-list.html"
|
||||
return render(request, template_name, context)
|
||||
|
||||
def delete(self, request, type, strategy_id):
|
||||
"""
|
||||
Delete a strategy.
|
||||
:param strategy_id: The id of the strategy to delete.
|
||||
"""
|
||||
if type not in self.allowed_types:
|
||||
return HttpResponseBadRequest
|
||||
message = None
|
||||
message_class = "success"
|
||||
try:
|
||||
strategy = Strategy.objects.get(id=strategy_id, user=request.user)
|
||||
strategy.delete()
|
||||
message = "Strategy deleted successfully"
|
||||
except Strategy.DoesNotExist:
|
||||
message = "Error deleting strategy"
|
||||
message_class = "danger"
|
||||
|
||||
strategies = get_strategies(request.user)
|
||||
|
||||
context = {
|
||||
"items": strategies,
|
||||
"type": strategies,
|
||||
}
|
||||
if message:
|
||||
context["message"] = message
|
||||
context["class"] = message_class
|
||||
|
||||
template_name = "partials/strategy-list.html"
|
||||
return render(request, template_name, context)
|
Loading…
Reference in New Issue