model.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. import random
  2. import re
  3. import sqlite3 as db
  4. import sys
  5. import uuid
  6. from math import floor
  7. from passlib.handlers.sha2_crypt import sha256_crypt
  8. import db_setup
  9. import trading_bot
  10. from debug import debug
  11. from game import CURRENCY_NAME
  12. from util import random_chars, salt
  13. # connection: db.Connection = None
  14. # cursor: db.Cursor = None
  15. connection = None # no type annotations in python 3.5
  16. cursor = None # no type annotations in python 3.5
  17. db_name = None
  18. def query_save_name():
  19. global db_name
  20. if debug:
  21. db_name = 'test.db'
  22. return
  23. while True:
  24. save_name = input('Name of the savegame: ')
  25. if re.match(r"[A-Za-z0-9.-]{0,50}", save_name):
  26. db_name = save_name + '.db'
  27. return
  28. else:
  29. print('Must match "[A-Za-z0-9.-]{0,50}"')
  30. def connect(reconnect=False):
  31. global connection
  32. global cursor
  33. global db_name
  34. if reconnect:
  35. connection.commit()
  36. connection.close()
  37. cursor = None
  38. connection = None
  39. db_name = None
  40. if connection is None or cursor is None:
  41. query_save_name()
  42. try:
  43. connection = db.connect(db_name)
  44. # connection.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')
  45. cursor = connection.cursor()
  46. except db.Error as e:
  47. print("Database error %s:" % e.args[0])
  48. sys.exit(1)
  49. # finally:
  50. # if con is not None:
  51. # con.close()
  52. def setup():
  53. connect()
  54. db_setup.setup(cursor)
  55. connection.commit()
  56. def used_key_count():
  57. connect()
  58. cursor.execute('''
  59. SELECT COUNT(*) -- rarely executed, no index needed, O(n) query
  60. FROM keys
  61. WHERE used_by_user_id IS NOT NULL
  62. ''')
  63. return cursor.fetchone()[0]
  64. def login(username, password):
  65. connect()
  66. # do not allow login as bank or with empty password
  67. if username == 'bank' and not debug:
  68. return None
  69. if password == '' and not debug:
  70. return None
  71. cursor.execute('''
  72. SELECT rowid, password
  73. FROM users
  74. WHERE username = ?
  75. ''', (username,))
  76. data = cursor.fetchone()
  77. if not data:
  78. return None
  79. hashed_password = data[1]
  80. user_id = data[0]
  81. # if a ValueError occurs here, then most likely a password that was stored as plain text
  82. if sha256_crypt.verify(password + salt, hashed_password):
  83. return new_session(user_id)
  84. else:
  85. return None
  86. def register(username, password, game_key):
  87. connect()
  88. if username == '':
  89. return False
  90. if password == '':
  91. return False
  92. cursor.execute('''
  93. INSERT INTO users
  94. (username, password)
  95. VALUES (? , ?)
  96. ''', (username, password))
  97. own(get_user_id_by_name(username), CURRENCY_NAME)
  98. if game_key != '':
  99. if valid_key(game_key):
  100. activate_key(game_key, get_user_id_by_name(username))
  101. return True
  102. def own(user_id, ownable_name, amount=0):
  103. if not isinstance(ownable_name, str):
  104. return AssertionError('A name must be a string.')
  105. cursor.execute('''
  106. INSERT OR IGNORE INTO ownership (user_id, ownable_id, amount)
  107. SELECT ?, (SELECT rowid FROM ownables WHERE name = ?), ?
  108. ''', (user_id, ownable_name, amount))
  109. def send_ownable(from_user_id, to_user_id, ownable_name, amount):
  110. connect()
  111. if amount < 0:
  112. return False
  113. if from_user_id != bank_id():
  114. cursor.execute('''
  115. UPDATE ownership
  116. SET amount = amount - ?
  117. WHERE user_id = ?
  118. AND ownable_id = (SELECT rowid FROM ownables WHERE name = ?)
  119. ''', (amount, from_user_id, ownable_name,))
  120. cursor.execute('''
  121. UPDATE ownership
  122. SET amount = amount + ?
  123. WHERE user_id = ?
  124. AND ownable_id = (SELECT rowid FROM ownables WHERE name = ?)
  125. ''', (amount, to_user_id, ownable_name))
  126. return True
  127. def valid_key(key):
  128. connect()
  129. cursor.execute('''
  130. SELECT key
  131. FROM keys
  132. WHERE used_by_user_id IS NULL
  133. AND key = ?
  134. ''', (key,))
  135. if cursor.fetchone():
  136. return True
  137. else:
  138. return False
  139. def new_session(user_id):
  140. connect()
  141. session_id = str(uuid.uuid4())
  142. cursor.execute('''
  143. INSERT INTO SESSIONS
  144. (user_id, session_id)
  145. VALUES (? , ?)
  146. ''', (user_id, session_id))
  147. return session_id
  148. def save_key(key):
  149. connect()
  150. cursor.execute('''
  151. INSERT INTO keys
  152. (key)
  153. VALUES (?)
  154. ''', (key,))
  155. def drop_old_sessions():
  156. connect()
  157. cursor.execute(''' -- no need to optimize this very well
  158. DELETE FROM sessions
  159. WHERE
  160. (SELECT COUNT(*) as newer
  161. FROM sessions s2
  162. WHERE user_id = s2.user_id
  163. AND rowid < s2.rowid) >= 10
  164. ''')
  165. def user_exists(username):
  166. connect()
  167. cursor.execute('''
  168. SELECT rowid
  169. FROM users
  170. WHERE username = ?
  171. ''', (username,))
  172. if cursor.fetchone():
  173. return True
  174. else:
  175. return False
  176. def get_user_id_by_session_id(session_id):
  177. connect()
  178. cursor.execute('''
  179. SELECT users.rowid
  180. FROM sessions, users
  181. WHERE sessions.session_id = ?
  182. AND users.rowid = sessions.user_id
  183. ''', (session_id,))
  184. ids = cursor.fetchone()
  185. if not ids:
  186. return False
  187. return ids[0]
  188. def get_user_id_by_name(username):
  189. connect()
  190. cursor.execute('''
  191. SELECT users.rowid
  192. FROM users
  193. WHERE username = ?
  194. ''', (username,))
  195. return cursor.fetchone()[0]
  196. def get_user_ownership(user_id):
  197. connect()
  198. cursor.execute('''
  199. SELECT
  200. ownables.name,
  201. ownership.amount,
  202. COALESCE (
  203. CASE -- sum score for each of the users ownables
  204. WHEN ownership.ownable_id = ? THEN 1
  205. ELSE (SELECT price
  206. FROM transactions
  207. WHERE ownable_id = ownership.ownable_id
  208. ORDER BY rowid DESC -- equivalent to ordering by dt
  209. LIMIT 1)
  210. END, 0) AS price,
  211. (SELECT MAX("limit")
  212. FROM orders, ownership o2
  213. WHERE o2.rowid = orders.ownership_id
  214. AND o2.ownable_id = ownership.ownable_id
  215. AND buy
  216. AND NOT stop_loss) AS bid,
  217. (SELECT MIN("limit")
  218. FROM orders, ownership o2
  219. WHERE o2.rowid = orders.ownership_id
  220. AND o2.ownable_id = ownership.ownable_id
  221. AND NOT buy
  222. AND NOT stop_loss) AS ask
  223. FROM ownership, ownables
  224. WHERE user_id = ?
  225. AND (ownership.amount > 0 OR ownership.ownable_id = ?)
  226. AND ownership.ownable_id = ownables.rowid
  227. ORDER BY ownables.rowid ASC
  228. ''', (currency_id(), user_id, currency_id(),))
  229. return cursor.fetchall()
  230. def activate_key(key, user_id):
  231. connect()
  232. cursor.execute('''
  233. UPDATE keys
  234. SET used_by_user_id = ?
  235. WHERE used_by_user_id IS NULL
  236. AND key = ?
  237. ''', (user_id, key,))
  238. send_ownable(bank_id(), user_id, currency_id(), 1000)
  239. def bank_id():
  240. connect()
  241. cursor.execute('''
  242. SELECT users.rowid
  243. FROM users
  244. WHERE username = 'bank'
  245. ''')
  246. return cursor.fetchone()[0]
  247. def valid_session_id(session_id):
  248. connect()
  249. cursor.execute('''
  250. SELECT rowid
  251. FROM sessions
  252. WHERE session_id = ?
  253. ''', (session_id,))
  254. if cursor.fetchone():
  255. return True
  256. else:
  257. return False
  258. def get_user_orders(user_id):
  259. connect()
  260. cursor.execute('''
  261. SELECT
  262. CASE
  263. WHEN orders.buy THEN 'Buy'
  264. ELSE 'Sell'
  265. END,
  266. ownables.name,
  267. (orders.ordered_amount - orders.executed_amount) || '/' || orders.ordered_amount,
  268. orders."limit",
  269. CASE
  270. WHEN orders."limit" IS NULL THEN NULL
  271. WHEN orders.stop_loss THEN 'Yes'
  272. ELSE 'No'
  273. END,
  274. datetime(orders.expiry_dt, 'localtime'),
  275. orders.rowid
  276. FROM orders, ownables, ownership
  277. WHERE ownership.user_id = ?
  278. AND ownership.ownable_id = ownables.rowid
  279. AND orders.ownership_id = ownership.rowid
  280. ORDER BY ownables.name ASC, orders.stop_loss ASC, orders.buy DESC, orders."limit" ASC
  281. ''', (user_id,))
  282. return cursor.fetchall()
  283. def get_ownable_orders(user_id, ownable_id):
  284. connect()
  285. cursor.execute('''
  286. SELECT
  287. CASE
  288. WHEN ownership.user_id = ? THEN 'X'
  289. ELSE NULL
  290. END,
  291. CASE
  292. WHEN orders.buy THEN 'Buy'
  293. ELSE 'Sell'
  294. END,
  295. ownables.name,
  296. orders.ordered_amount - orders.executed_amount,
  297. orders."limit",
  298. datetime(orders.expiry_dt, 'localtime'),
  299. orders.rowid
  300. FROM orders, ownables, ownership
  301. WHERE ownership.ownable_id = ?
  302. AND ownership.ownable_id = ownables.rowid
  303. AND orders.ownership_id = ownership.rowid
  304. AND (orders.stop_loss IS NULL OR NOT orders.stop_loss)
  305. ORDER BY ownables.name ASC, orders.stop_loss ASC, orders.buy DESC, orders."limit" ASC
  306. ''', (user_id, ownable_id,))
  307. return cursor.fetchall()
  308. def sell_ordered_amount(user_id, ownable_id):
  309. connect()
  310. cursor.execute('''
  311. SELECT COALESCE(SUM(orders.ordered_amount - orders.executed_amount),0)
  312. FROM orders, ownership
  313. WHERE ownership.rowid = orders.ownership_id
  314. AND ownership.user_id = ?
  315. AND ownership.ownable_id = ?
  316. AND NOT orders.buy
  317. ''', (user_id, ownable_id))
  318. return cursor.fetchone()[0]
  319. def available_amount(user_id, ownable_id):
  320. connect()
  321. cursor.execute('''
  322. SELECT amount
  323. FROM ownership
  324. WHERE user_id = ?
  325. AND ownable_id = ?
  326. ''', (user_id, ownable_id))
  327. return cursor.fetchone()[0] - sell_ordered_amount(user_id, ownable_id)
  328. def user_owns_at_least(amount, user_id, ownable_id):
  329. connect()
  330. if not isinstance(amount, float) and not isinstance(amount, int):
  331. # comparison of float with strings does not work so well in sql
  332. raise AssertionError()
  333. cursor.execute('''
  334. SELECT rowid
  335. FROM ownership
  336. WHERE user_id = ?
  337. AND ownable_id = ?
  338. AND amount - ? >= ?
  339. ''', (user_id, ownable_id, sell_ordered_amount(user_id, ownable_id), amount))
  340. if cursor.fetchone():
  341. return True
  342. else:
  343. return False
  344. def news():
  345. connect()
  346. cursor.execute('''
  347. SELECT dt, title FROM
  348. (SELECT *, rowid
  349. FROM news
  350. ORDER BY rowid DESC -- equivalent to order by dt
  351. LIMIT 20) n
  352. ORDER BY rowid ASC -- equivalent to order by dt
  353. ''')
  354. return cursor.fetchall()
  355. def ownable_name_exists(name):
  356. connect()
  357. cursor.execute('''
  358. SELECT rowid
  359. FROM ownables
  360. WHERE name = ?
  361. ''', (name,))
  362. if cursor.fetchone():
  363. return True
  364. else:
  365. return False
  366. def new_stock(expiry, name=None):
  367. connect()
  368. while name is None:
  369. name = random_chars(6)
  370. if ownable_name_exists(name):
  371. name = None
  372. cursor.execute('''
  373. INSERT INTO ownables(name)
  374. VALUES (?)
  375. ''', (name,))
  376. new_news('A new stock can now be bought: ' + name)
  377. if random.getrandbits(1):
  378. new_news('Experts expect the price of ' + name + ' to fall')
  379. else:
  380. new_news('Experts expect the price of ' + name + ' to rise')
  381. amount = random.randrange(100, 10000)
  382. price = random.randrange(10000, 20000) / amount
  383. ownable_id = ownable_id_by_name(name)
  384. own(bank_id(), name, amount)
  385. bank_order(False,
  386. ownable_id,
  387. price,
  388. amount,
  389. expiry)
  390. return name
  391. def ownable_id_by_name(ownable_name):
  392. connect()
  393. cursor.execute('''
  394. SELECT rowid
  395. FROM ownables
  396. WHERE name = ?
  397. ''', (ownable_name,))
  398. return cursor.fetchone()[0]
  399. def get_ownership_id(ownable_id, user_id):
  400. connect()
  401. cursor.execute('''
  402. SELECT rowid
  403. FROM ownership
  404. WHERE ownable_id = ?
  405. AND user_id = ?
  406. ''', (ownable_id, user_id,))
  407. return cursor.fetchone()[0]
  408. def currency_id():
  409. connect()
  410. cursor.execute('''
  411. SELECT rowid
  412. FROM ownables
  413. WHERE name = ?
  414. ''', (CURRENCY_NAME,))
  415. return cursor.fetchone()[0]
  416. def user_money(user_id):
  417. connect()
  418. cursor.execute('''
  419. SELECT amount
  420. FROM ownership
  421. WHERE user_id = ?
  422. AND ownable_id = ?
  423. ''', (user_id, currency_id()))
  424. return cursor.fetchone()[0]
  425. def delete_order(order_id, new_order_status):
  426. connect()
  427. cursor.execute('''
  428. INSERT INTO order_history
  429. (ownership_id, buy, "limit", ordered_amount, executed_amount, expiry_dt, status, order_id)
  430. SELECT
  431. ownership_id,
  432. buy,
  433. "limit",
  434. ordered_amount,
  435. executed_amount,
  436. expiry_dt,
  437. ?,
  438. rowid
  439. FROM orders
  440. WHERE rowid = ?
  441. ''', (order_id, new_order_status))
  442. cursor.execute('''
  443. DELETE FROM orders
  444. WHERE rowid = ?
  445. ''', (order_id,))
  446. def current_value(ownable_id):
  447. connect()
  448. if ownable_id == currency_id():
  449. return 1
  450. cursor.execute('''SELECT price
  451. FROM transactions
  452. WHERE ownable_id = ?
  453. ORDER BY rowid DESC -- equivalent to order by dt
  454. LIMIT 1
  455. ''', (ownable_id,))
  456. return cursor.fetchone()[0]
  457. def execute_orders(ownable_id):
  458. connect()
  459. orders_changed = False
  460. while True:
  461. # find order to execute
  462. cursor.execute('''
  463. -- two best orders
  464. SELECT * FROM (
  465. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  466. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  467. WHERE buy_order.buy AND NOT sell_order.buy
  468. AND buyer.rowid = buy_order.ownership_id
  469. AND seller.rowid = sell_order.ownership_id
  470. AND buyer.ownable_id = ?
  471. AND seller.ownable_id = ?
  472. AND buy_order."limit" IS NULL
  473. AND sell_order."limit" IS NULL
  474. ORDER BY buy_order.rowid ASC,
  475. sell_order.rowid ASC
  476. LIMIT 1)
  477. UNION ALL -- best buy orders
  478. SELECT * FROM (
  479. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  480. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  481. WHERE buy_order.buy AND NOT sell_order.buy
  482. AND buyer.rowid = buy_order.ownership_id
  483. AND seller.rowid = sell_order.ownership_id
  484. AND buyer.ownable_id = ?
  485. AND seller.ownable_id = ?
  486. AND buy_order."limit" IS NULL
  487. AND sell_order."limit" IS NOT NULL
  488. AND NOT sell_order.stop_loss
  489. ORDER BY sell_order."limit" ASC,
  490. buy_order.rowid ASC,
  491. sell_order.rowid ASC
  492. LIMIT 1)
  493. UNION ALL -- best sell orders
  494. SELECT * FROM (
  495. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  496. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  497. WHERE buy_order.buy AND NOT sell_order.buy
  498. AND buyer.rowid = buy_order.ownership_id
  499. AND seller.rowid = sell_order.ownership_id
  500. AND buyer.ownable_id = ?
  501. AND seller.ownable_id = ?
  502. AND buy_order."limit" IS NOT NULL
  503. AND NOT buy_order.stop_loss
  504. AND sell_order."limit" IS NULL
  505. ORDER BY buy_order."limit" DESC,
  506. buy_order.rowid ASC,
  507. sell_order.rowid ASC
  508. LIMIT 1)
  509. UNION ALL -- both limit orders
  510. SELECT * FROM (
  511. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  512. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  513. WHERE buy_order.buy AND NOT sell_order.buy
  514. AND buyer.rowid = buy_order.ownership_id
  515. AND seller.rowid = sell_order.ownership_id
  516. AND buyer.ownable_id = ?
  517. AND seller.ownable_id = ?
  518. AND buy_order."limit" IS NOT NULL
  519. AND sell_order."limit" IS NOT NULL
  520. AND sell_order."limit" <= buy_order."limit"
  521. AND NOT sell_order.stop_loss
  522. AND NOT buy_order.stop_loss
  523. ORDER BY buy_order."limit" DESC,
  524. sell_order."limit" ASC,
  525. buy_order.rowid ASC,
  526. sell_order.rowid ASC
  527. LIMIT 1)
  528. LIMIT 1
  529. ''', tuple(ownable_id for _ in range(8)))
  530. matching_orders = cursor.fetchone()
  531. # return type: (ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  532. # ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  533. # user_id,user_id,rowid,rowid)
  534. if not matching_orders:
  535. if not orders_changed:
  536. break
  537. # check if the trading bot has any new offers to make
  538. new_order_was_placed = trading_bot.notify_order_traded(ownable_id)
  539. if new_order_was_placed:
  540. orders_changed = False
  541. continue
  542. else:
  543. break
  544. buy_ownership_id, _, buy_limit, _, buy_order_amount, buy_executed_amount, buy_expiry_dt, \
  545. sell_ownership_id, _, sell_limit, _, sell_order_amount, sell_executed_amount, sell_expiry_dt, \
  546. buyer_id, seller_id, buy_order_id, sell_order_id \
  547. = matching_orders
  548. if buy_limit is None and sell_limit is None:
  549. price = current_value(ownable_id)
  550. elif buy_limit is None:
  551. price = sell_limit
  552. elif sell_limit is None:
  553. price = buy_limit
  554. else: # both not NULL
  555. # the price of the older order is used, just like in the real exchange
  556. if buy_order_id < sell_order_id:
  557. price = buy_limit
  558. else:
  559. price = sell_limit
  560. buyer_money = user_money(buyer_id)
  561. def _my_division(x, y):
  562. try:
  563. return floor(x / y)
  564. except ZeroDivisionError:
  565. return float('Inf')
  566. amount = min(buy_order_amount - buy_executed_amount,
  567. sell_order_amount - sell_executed_amount,
  568. _my_division(buyer_money, price))
  569. if amount == 0: # probable because buyer has not enough money
  570. delete_order(buy_order_id, 'Unable to pay')
  571. continue
  572. buy_order_finished = (buy_order_amount - buy_executed_amount - amount <= 0) or (
  573. buyer_money - amount * price < price)
  574. sell_order_finished = (sell_order_amount - sell_executed_amount - amount <= 0)
  575. if price < 0 or amount <= 0: # price of 0 is possible though unlikely
  576. return AssertionError()
  577. # actually execute the order, but the bank does not send or receive anything
  578. send_ownable(buyer_id, seller_id, ownable_id, price * amount)
  579. send_ownable(seller_id, buyer_id, ownable_id, amount)
  580. # update order execution state
  581. cursor.execute('''
  582. UPDATE orders
  583. SET executed_amount = executed_amount + ?
  584. WHERE rowid = ?
  585. OR rowid = ?
  586. ''', (amount, buy_order_id, sell_order_id))
  587. if buy_order_finished:
  588. delete_order(buy_order_id, 'Executed')
  589. orders_changed = True
  590. if sell_order_finished:
  591. delete_order(sell_order_id, 'Executed')
  592. orders_changed = True
  593. if seller_id != buyer_id: # prevent showing self-transactions
  594. cursor.execute('''
  595. INSERT INTO transactions
  596. (price, ownable_id, amount, buyer_id, seller_id)
  597. VALUES(?, ?, ?, ?, ?)
  598. ''', (price, ownable_id, amount, buyer_id, seller_id))
  599. # trigger stop-loss orders
  600. if buyer_id != seller_id:
  601. cursor.execute('''
  602. UPDATE orders
  603. SET stop_loss = NULL,
  604. "limit" = NULL
  605. WHERE stop_loss IS NOT NULL
  606. AND stop_loss
  607. AND ? IN (SELECT ownable_id FROM ownership WHERE rowid = ownership_id)
  608. AND ((buy AND "limit" < ?) OR (NOT buy AND "limit" > ?))
  609. ''', (ownable_id, price, price,))
  610. def ownable_id_by_ownership_id(ownership_id):
  611. connect()
  612. cursor.execute('''
  613. SELECT ownable_id
  614. FROM ownership
  615. WHERE rowid = ?
  616. ''', (ownership_id,))
  617. return cursor.fetchone()[0]
  618. def ownable_name_by_id(ownable_id):
  619. connect()
  620. cursor.execute('''
  621. SELECT name
  622. FROM ownables
  623. WHERE rowid = ?
  624. ''', (ownable_id,))
  625. return cursor.fetchone()[0]
  626. def bank_order(buy, ownable_id, limit, amount, expiry):
  627. if not limit:
  628. raise AssertionError('The bank does not give away anything.')
  629. place_order(buy,
  630. get_ownership_id(ownable_id, bank_id()),
  631. limit,
  632. False,
  633. amount,
  634. expiry)
  635. ownable_name = ownable_name_by_id(ownable_id)
  636. new_news('External investors are selling ' + ownable_name + ' atm')
  637. def current_db_time(): # might differ from datetime.datetime.now() for time zone reasons
  638. connect()
  639. cursor.execute('''
  640. SELECT datetime('now')
  641. ''')
  642. return cursor.fetchone()[0]
  643. def place_order(buy, ownership_id, limit, stop_loss, amount, expiry):
  644. connect()
  645. cursor.execute('''
  646. INSERT INTO orders
  647. (buy, ownership_id, "limit", stop_loss, ordered_amount, expiry_dt)
  648. VALUES (?, ?, ?, ?, ?, ?)
  649. ''', (buy, ownership_id, limit, stop_loss, amount, expiry))
  650. execute_orders(ownable_id_by_ownership_id(ownership_id))
  651. return True
  652. def trades_on(ownable_id, limit):
  653. connect()
  654. cursor.execute('''
  655. SELECT datetime(dt,'localtime'), amount, price
  656. FROM transactions
  657. WHERE ownable_id = ?
  658. ORDER BY rowid DESC -- equivalent to order by dt
  659. LIMIT ?
  660. ''', (ownable_id, limit,))
  661. return cursor.fetchall()
  662. def trades(user_id, limit):
  663. connect()
  664. cursor.execute('''
  665. SELECT
  666. (CASE WHEN seller_id = ? THEN 'Sell' ELSE 'Buy' END),
  667. (SELECT name FROM ownables WHERE rowid = transactions.ownable_id),
  668. amount,
  669. price,
  670. datetime(dt,'localtime')
  671. FROM transactions
  672. WHERE seller_id = ? OR buyer_id = ?
  673. LIMIT ?
  674. ''', (user_id, user_id, user_id, limit,))
  675. return cursor.fetchall()
  676. def drop_expired_orders():
  677. connect()
  678. cursor.execute('''
  679. SELECT rowid, * FROM orders
  680. WHERE expiry_dt < DATETIME('now')
  681. ''')
  682. data = cursor.fetchall()
  683. cursor.execute('''
  684. DELETE FROM orders
  685. WHERE expiry_dt < DATETIME('now')
  686. ''')
  687. return data
  688. def generate_keys(count=1):
  689. # source https://stackoverflow.com/questions/17049308/python-3-3-serial-key-generator-list-problems
  690. for i in range(count):
  691. key = '-'.join(random_chars(5) for _ in range(5))
  692. save_key(key)
  693. print(key)
  694. def user_has_order_with_id(session_id, order_id):
  695. connect()
  696. cursor.execute('''
  697. SELECT orders.rowid
  698. FROM orders, ownership, sessions
  699. WHERE orders.rowid = ?
  700. AND sessions.session_id = ?
  701. AND sessions.user_id = ownership.user_id
  702. AND ownership.rowid = orders.ownership_id
  703. ''', (order_id, session_id,))
  704. if cursor.fetchone():
  705. return True
  706. else:
  707. return False
  708. def leaderboard():
  709. connect()
  710. cursor.execute('''
  711. SELECT *
  712. FROM ( -- one score for each user
  713. SELECT
  714. username,
  715. SUM(CASE -- sum score for each of the users ownables
  716. WHEN ownership.ownable_id = ? THEN ownership.amount
  717. ELSE ownership.amount * (SELECT price
  718. FROM transactions
  719. WHERE ownable_id = ownership.ownable_id
  720. ORDER BY rowid DESC -- equivalent to ordering by dt
  721. LIMIT 1)
  722. END
  723. ) score
  724. FROM users, ownership
  725. WHERE ownership.user_id = users.rowid
  726. AND users.username != 'bank'
  727. GROUP BY users.rowid
  728. ) AS scores
  729. ORDER BY score DESC
  730. LIMIT 50
  731. ''', (currency_id(),))
  732. return cursor.fetchall()
  733. def user_wealth(user_id):
  734. connect()
  735. cursor.execute('''
  736. SELECT SUM(
  737. CASE -- sum score for each of the users ownables
  738. WHEN ownership.ownable_id = ? THEN ownership.amount
  739. ELSE ownership.amount * (SELECT price
  740. FROM transactions
  741. WHERE ownable_id = ownership.ownable_id
  742. ORDER BY rowid DESC -- equivalent to ordering by dt
  743. LIMIT 1)
  744. END
  745. ) score
  746. FROM ownership
  747. WHERE ownership.user_id = ?
  748. ''', (currency_id(), user_id,))
  749. return cursor.fetchone()[0]
  750. def change_password(session_id, password):
  751. connect()
  752. cursor.execute('''
  753. UPDATE users
  754. SET password = ?
  755. WHERE rowid = (SELECT user_id FROM sessions WHERE sessions.session_id = ?)
  756. ''', (password, session_id,))
  757. def sign_out_user(session_id):
  758. connect()
  759. cursor.execute('''
  760. DELETE FROM sessions
  761. WHERE user_id = (SELECT user_id FROM sessions s2 WHERE s2.session_id = ?)
  762. ''', (session_id,))
  763. def delete_user(user_id):
  764. connect()
  765. cursor.execute('''
  766. DELETE FROM sessions
  767. WHERE user_id = ?
  768. ''', (user_id,))
  769. cursor.execute('''
  770. DELETE FROM orders
  771. WHERE ownership_id IN (
  772. SELECT rowid FROM ownership WHERE user_id = ?)
  773. ''', (user_id,))
  774. cursor.execute('''
  775. DELETE FROM ownership
  776. WHERE user_id = ?
  777. ''', (user_id,))
  778. cursor.execute('''
  779. DELETE FROM keys
  780. WHERE used_by_user_id = ?
  781. ''', (user_id,))
  782. cursor.execute('''
  783. INSERT INTO news(title)
  784. VALUES ((SELECT username FROM users WHERE rowid = ?) || ' retired.')
  785. ''', (user_id,))
  786. cursor.execute('''
  787. DELETE FROM users
  788. WHERE rowid = ?
  789. ''', (user_id,))
  790. def delete_ownable(ownable_id):
  791. connect()
  792. cursor.execute('''
  793. DELETE FROM transactions
  794. WHERE ownable_id = ?
  795. ''', (ownable_id,))
  796. cursor.execute('''
  797. DELETE FROM orders
  798. WHERE ownership_id IN (
  799. SELECT rowid FROM ownership WHERE ownable_id = ?)
  800. ''', (ownable_id,))
  801. # only delete empty ownerships
  802. cursor.execute('''
  803. DELETE FROM ownership
  804. WHERE ownable_id = ?
  805. AND amount = 0
  806. ''', (ownable_id,))
  807. cursor.execute('''
  808. INSERT INTO news(title)
  809. VALUES ((SELECT name FROM ownables WHERE rowid = ?) || ' can not be traded any more.')
  810. ''', (ownable_id,))
  811. cursor.execute('''
  812. DELETE FROM ownables
  813. WHERE rowid = ?
  814. ''', (ownable_id,))
  815. def hash_all_users_passwords():
  816. connect()
  817. cursor.execute('''
  818. SELECT rowid, password
  819. FROM users
  820. ''')
  821. users = cursor.fetchall()
  822. for user in users:
  823. user_id = user[0]
  824. pw = user[1]
  825. valid_hash = True
  826. try:
  827. sha256_crypt.verify('password' + salt, pw)
  828. except ValueError:
  829. valid_hash = False
  830. if valid_hash:
  831. raise AssertionError('There is already a hashed password in the database! Be careful what you are doing!')
  832. pw = sha256_crypt.encrypt(pw + salt)
  833. cursor.execute('''
  834. UPDATE users
  835. SET password = ?
  836. WHERE rowid = ?
  837. ''', (pw, user_id,))
  838. def new_news(message):
  839. connect()
  840. cursor.execute('''
  841. INSERT INTO news(title)
  842. VALUES (?)
  843. ''', (message,))
  844. def abs_spread(ownable_id):
  845. connect()
  846. cursor.execute('''
  847. SELECT
  848. (SELECT MAX("limit")
  849. FROM orders, ownership
  850. WHERE ownership.rowid = orders.ownership_id
  851. AND ownership.ownable_id = ?
  852. AND buy
  853. AND NOT stop_loss) AS bid,
  854. (SELECT MIN("limit")
  855. FROM orders, ownership
  856. WHERE ownership.rowid = orders.ownership_id
  857. AND ownership.ownable_id = ?
  858. AND NOT buy
  859. AND NOT stop_loss) AS ask
  860. ''', (ownable_id, ownable_id,))
  861. return cursor.fetchone()
  862. def ownables():
  863. connect()
  864. cursor.execute('''
  865. SELECT name, course,
  866. (SELECT SUM(amount)
  867. FROM ownership
  868. WHERE ownership.ownable_id = ownables_with_course.rowid) market_size
  869. FROM (SELECT
  870. name, ownables.rowid,
  871. CASE WHEN ownables.rowid = ?
  872. THEN 1
  873. ELSE (SELECT price
  874. FROM transactions
  875. WHERE ownable_id = ownables.rowid
  876. ORDER BY rowid DESC -- equivalent to ordering by dt
  877. LIMIT 1) END course
  878. FROM ownables) ownables_with_course
  879. ''', (currency_id(),))
  880. data = cursor.fetchall()
  881. for idx in range(len(data)):
  882. # compute market cap
  883. row = data[idx]
  884. if row[1] is None:
  885. market_cap = None
  886. elif row[2] is None:
  887. market_cap = None
  888. else:
  889. market_cap = row[1] * row[2]
  890. data[idx] = (row[0], row[1], market_cap)
  891. return data
  892. def reset_bank():
  893. connect()
  894. cursor.execute('''
  895. DELETE FROM ownership
  896. WHERE user_id = ?
  897. ''', (bank_id(),))
  898. def cleanup():
  899. if connection is not None:
  900. connection.commit()
  901. connection.close()
  902. def ownable_ids():
  903. connect()
  904. cursor.execute('''
  905. SELECT rowid FROM ownables
  906. ''')
  907. return [ownable_id[0] for ownable_id in cursor.fetchall()]
  908. def get_old_orders(user_id, include_executed, include_canceled, limit):
  909. connect() # TODO testen
  910. # TODO indices prüfen
  911. cursor.execute('''
  912. SELECT
  913. (CASE WHEN order_history.buy THEN 'Buy' ELSE 'Sell' END),
  914. ownables.name,
  915. (order_history.ordered_amount - order_history.executed_amount) || '/' || order_history.ordered_amount,
  916. order_history."limit",
  917. order_history.expiry_dt,
  918. order_history.order_id,
  919. order_history.status
  920. FROM order_history, ownership, ownables
  921. WHERE ownership.user_id = ?
  922. AND ownership.rowid = order_history.ownership_id
  923. AND ownables.rowid = ownership.ownable_id
  924. AND (
  925. (order_history.status = 'Executed' AND ?)
  926. OR
  927. ((order_history.status = 'Expired' OR order_history.status = 'Canceled') AND ?)
  928. )
  929. LIMIT ?
  930. ''', (user_id, include_executed, include_canceled, limit))
  931. return cursor.fetchall()