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
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.contrib.auth.models import AbstractUser
from django.db import models
@ -140,31 +142,41 @@ class Trade(models.Model):
# the trade is not placed yet
if self.account.exchange == "alpaca":
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":
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":
params = ""
order = account.create_limit_order(
self.symbol,
self.type,
self.direction,
self.amount,
self.price,
params,
limit_order_data = LimitOrderRequest(
symbol=self.symbol,
limit_price=self.price,
qty=self.amount,
side=direction,
time_in_force=TimeInForce.IOC,
)
order = trading_client.submit_order(order_data=limit_order_data)
else:
raise Exception("Unknown order type")
print("ORDER", order)
try:
parsed = ccxt_s.CCXTRoot.from_dict(order)
except ValidationError as e:
log.error(f"Error creating trade: {e}")
return False
self.status = parsed.status
self.response = order
# self.status = parsed.status
# self.response = order
else:
# there is a trade open
# get trade

View File

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