Begin implementing proper trade management

This commit is contained in:
Mark Veidemanis 2022-10-24 09:07:22 +01:00
parent 30d516ebf9
commit 98a2300ae1
Signed by: m
GPG Key ID: 5ACFCEED46C0904F
2 changed files with 31 additions and 19 deletions

View File

@ -1,5 +1,7 @@
import stripe import stripe
from alpaca.trading.client import TradingClient from alpaca.trading.client import TradingClient
from alpaca.trading.enums import OrderSide, TimeInForce
from alpaca.trading.requests import LimitOrderRequest, MarketOrderRequest
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
from django.db import models from django.db import models
@ -140,31 +142,41 @@ class Trade(models.Model):
# the trade is not placed yet # the trade is not placed yet
if self.account.exchange == "alpaca": if self.account.exchange == "alpaca":
trading_client = TradingClient( trading_client = TradingClient(
self.account.api_key, self.account.api_secret, paper=self.sandbox self.account.api_key,
self.account.api_secret,
paper=self.account.sandbox,
) )
if self.direction == "buy":
direction = OrderSide.BUY
elif self.direction == "sell":
direction = OrderSide.SELL
else:
raise Exception("Unknown direction")
if self.type == "market": if self.type == "market":
order = account.create_order(
self.symbol, self.type, self.direction, self.amount market_order_data = MarketOrderRequest(
symbol=self.symbol,
qty=self.amount,
side=OrderSide.BUY,
time_in_force=TimeInForce.IOC,
) )
order = trading_client.submit_order(order_data=market_order_data)
elif self.type == "limit": elif self.type == "limit":
params = "" limit_order_data = LimitOrderRequest(
order = account.create_limit_order( symbol=self.symbol,
self.symbol, limit_price=self.price,
self.type, qty=self.amount,
self.direction, side=direction,
self.amount, time_in_force=TimeInForce.IOC,
self.price,
params,
) )
order = trading_client.submit_order(order_data=limit_order_data)
else:
raise Exception("Unknown order type")
print("ORDER", order) print("ORDER", order)
try:
parsed = ccxt_s.CCXTRoot.from_dict(order) # self.status = parsed.status
except ValidationError as e: # self.response = order
log.error(f"Error creating trade: {e}")
return False
self.status = parsed.status
self.response = order
else: else:
# there is a trade open # there is a trade open
# get trade # get trade

View File

@ -159,7 +159,7 @@ class TradeAction(LoginRequiredMixin, APIView):
try: try:
trade = Trade.objects.get(id=trade_id, account__user=request.user) trade = Trade.objects.get(id=trade_id, account__user=request.user)
trade.delete() trade.delete()
message = "trade deleted successfully" message = "Trade deleted successfully"
except Trade.DoesNotExist: except Trade.DoesNotExist:
message = "Error deleting trade" message = "Error deleting trade"
message_class = "danger" message_class = "danger"