model.py 30 KB

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