-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqldb.py
More file actions
92 lines (74 loc) · 2.32 KB
/
sqldb.py
File metadata and controls
92 lines (74 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import mysql.connector
from alpaca.trading.enums import OrderSide, TimeInForce, OrderType
import requests
import os
from dotenv import load_dotenv
load_dotenv()
PASSWD = os.getenv('sqlpassword')
db = mysql.connector.connect(
host="localhost",
user="root",
passwd=PASSWD,
database="test"
)
c = db.cursor()
def updateData(data):
match data.type:
case OrderType.MARKET:
if(data.side == OrderSide.BUY):
updateMarketBuys(data)
else:
updateMarketSells(data)
case OrderType.LIMIT:
if(data.side == OrderSide.BUY):
updateMarketBuys(data)
else:
updateMarketSells(data)
def updateMarketBuys(data):
sql = "INSERT INTO market_order_buy (ticker, qty) VALUES (%s, %s)"
values = (data.symbol, data.qty)
c.execute(sql, values)
updatePortfolioAdd(data)
def updateMarketSells(data):
sql = "SELECT SUM(qty) AS total_quantity FROM portfolio WHERE ticker=(%s)"
values = (data.symbol,)
c.execute(sql, values)
row = c.fetchone()
print(row)
if(row is None):
print("not enough stocks owned to sell desired qtyn1")
elif(int(row[0]) >= data.qty):
sql = "INSERT INTO market_order_sell (ticker, qty) VALUES (%s, %s)"
values = (data.symbol, data.qty)
c.execute(sql, values)
updatePortfolioSubtract(data)
else:
print("not enough stocks owned to sell desired qty")
def updateLimitBuys(data):
updatePortfolioAdd(data)
pass
def updateLimitSells(data):
updatePortfolioSubtract(data)
pass
def updatePortfolioAdd(data):
sql = "INSERT INTO portfolio (ticker, qty) VALUES (%s, %s)"
values = (data.symbol, data.qty)
c.execute(sql, values)
db.commit()
pass
def updatePortfolioSubtract(data):
c.execute("SELECT d, qty FROM portfolio WHERE ticker = %s ORDER BY d ASC", (data.symbol,))
rows = c.fetchall()
remaining = data.qty
for row in rows:
d, qty = row
if qty <= remaining:
c.execute("DELETE FROM portfolio WHERE d = %s", (d,))
remaining -= qty
else:
new_qty = qty - remaining
c.execute("UPDATE portfolio SET qty = %s WHERE d = %s", (new_qty, d))
remaining = 0
break
db.commit()
pass