model.py 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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(timeout=60, 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. timeout)
  396. return name
  397. def new_stocks(timeout=60, count=1):
  398. return [new_stock(timeout=timeout) for _ in range(count)]
  399. def ownable_id_by_name(ownable_name):
  400. connect()
  401. cursor.execute('''
  402. SELECT rowid
  403. FROM ownables
  404. WHERE name = ?
  405. ''', (ownable_name,))
  406. return cursor.fetchone()[0]
  407. def get_ownership_id(ownable_id, user_id):
  408. connect()
  409. cursor.execute('''
  410. SELECT rowid
  411. FROM ownership
  412. WHERE ownable_id = ?
  413. AND user_id = ?
  414. ''', (ownable_id, user_id,))
  415. return cursor.fetchone()[0]
  416. def currency_id():
  417. connect()
  418. cursor.execute('''
  419. SELECT rowid
  420. FROM ownables
  421. WHERE name = ?
  422. ''', (CURRENCY_NAME,))
  423. return cursor.fetchone()[0]
  424. def user_money(user_id):
  425. connect()
  426. cursor.execute('''
  427. SELECT amount
  428. FROM ownership
  429. WHERE user_id = ?
  430. AND ownable_id = ?
  431. ''', (user_id, currency_id()))
  432. return cursor.fetchone()[0]
  433. def delete_order(order_id):
  434. connect()
  435. cursor.execute('''
  436. DELETE FROM orders
  437. WHERE rowid = ?
  438. ''', (order_id,))
  439. def current_value(ownable_id):
  440. connect()
  441. if ownable_id == currency_id():
  442. return 1
  443. cursor.execute('''SELECT price
  444. FROM transactions
  445. WHERE ownable_id = ?
  446. ORDER BY rowid DESC -- equivalent to order by dt
  447. LIMIT 1
  448. ''', (ownable_id,))
  449. return cursor.fetchone()[0]
  450. def execute_orders(ownable_id):
  451. connect()
  452. while True:
  453. # find order to execute
  454. cursor.execute('''
  455. -- two best orders
  456. SELECT * FROM (
  457. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  458. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  459. WHERE buy_order.buy AND NOT sell_order.buy
  460. AND buyer.rowid = buy_order.ownership_id
  461. AND seller.rowid = sell_order.ownership_id
  462. AND buyer.ownable_id = ?
  463. AND seller.ownable_id = ?
  464. AND buy_order."limit" IS NULL
  465. AND sell_order."limit" IS NULL
  466. ORDER BY buy_order.rowid ASC,
  467. sell_order.rowid ASC
  468. LIMIT 1)
  469. UNION ALL -- best buy orders
  470. SELECT * FROM (
  471. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  472. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  473. WHERE buy_order.buy AND NOT sell_order.buy
  474. AND buyer.rowid = buy_order.ownership_id
  475. AND seller.rowid = sell_order.ownership_id
  476. AND buyer.ownable_id = ?
  477. AND seller.ownable_id = ?
  478. AND buy_order."limit" IS NULL
  479. AND sell_order."limit" IS NOT NULL
  480. AND NOT sell_order.stop_loss
  481. ORDER BY sell_order."limit" ASC,
  482. buy_order.rowid ASC,
  483. sell_order.rowid ASC
  484. LIMIT 1)
  485. UNION ALL -- best sell orders
  486. SELECT * FROM (
  487. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  488. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  489. WHERE buy_order.buy AND NOT sell_order.buy
  490. AND buyer.rowid = buy_order.ownership_id
  491. AND seller.rowid = sell_order.ownership_id
  492. AND buyer.ownable_id = ?
  493. AND seller.ownable_id = ?
  494. AND buy_order."limit" IS NOT NULL
  495. AND NOT buy_order.stop_loss
  496. AND sell_order."limit" IS NULL
  497. ORDER BY buy_order."limit" DESC,
  498. buy_order.rowid ASC,
  499. sell_order.rowid ASC
  500. LIMIT 1)
  501. UNION ALL -- both limit orders
  502. SELECT * FROM (
  503. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  504. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  505. WHERE buy_order.buy AND NOT sell_order.buy
  506. AND buyer.rowid = buy_order.ownership_id
  507. AND seller.rowid = sell_order.ownership_id
  508. AND buyer.ownable_id = ?
  509. AND seller.ownable_id = ?
  510. AND buy_order."limit" IS NOT NULL
  511. AND sell_order."limit" IS NOT NULL
  512. AND sell_order."limit" <= buy_order."limit"
  513. AND NOT sell_order.stop_loss
  514. AND NOT buy_order.stop_loss
  515. ORDER BY buy_order."limit" DESC,
  516. sell_order."limit" ASC,
  517. buy_order.rowid ASC,
  518. sell_order.rowid ASC
  519. LIMIT 1)
  520. LIMIT 1
  521. ''', tuple(ownable_id for _ in range(8)))
  522. matching_orders = cursor.fetchone()
  523. # return type: (ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  524. # ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  525. # user_id,user_id,rowid,rowid)
  526. if not matching_orders:
  527. break
  528. buy_ownership_id, _, buy_limit, _, buy_order_amount, buy_executed_amount, buy_expiry_dt, \
  529. sell_ownership_id, _, sell_limit, _, sell_order_amount, sell_executed_amount, sell_expiry_dt, \
  530. buyer_id, seller_id, buy_order_id, sell_order_id \
  531. = matching_orders
  532. if buy_limit is None and sell_limit is None:
  533. price = current_value(ownable_id)
  534. elif buy_limit is None:
  535. price = sell_limit
  536. elif sell_limit is None:
  537. price = buy_limit
  538. else: # both not NULL
  539. # the price of the older order is used, just like in the real exchange
  540. if buy_order_id < sell_order_id:
  541. price = buy_limit
  542. else:
  543. price = sell_limit
  544. buyer_money = user_money(buyer_id)
  545. def _my_division(x, y):
  546. try:
  547. return floor(x/y)
  548. except ZeroDivisionError:
  549. return float('Inf')
  550. amount = min(buy_order_amount - buy_executed_amount,
  551. sell_order_amount - sell_executed_amount,
  552. _my_division(buyer_money, price))
  553. if amount == 0: # probable because buyer has not enough money
  554. delete_order(buy_order_id)
  555. continue
  556. buy_order_finished = (buy_order_amount - buy_executed_amount - amount <= 0) or (
  557. buyer_money - amount * price < price)
  558. sell_order_finished = (sell_order_amount - sell_executed_amount - amount <= 0)
  559. if price < 0 or amount <= 0: # price of 0 is possible though unlikely
  560. return AssertionError()
  561. # actually execute the order, but the bank does not send or receive anything
  562. if buyer_id != bank_id(): # buyer pays
  563. cursor.execute('''
  564. UPDATE ownership
  565. SET amount = amount - ?
  566. WHERE user_id = ?
  567. AND ownable_id = ?
  568. ''', (price * amount, buyer_id, currency_id()))
  569. if seller_id != bank_id(): # seller pays
  570. cursor.execute('''
  571. UPDATE ownership
  572. SET amount = amount - ?
  573. WHERE rowid = ?
  574. ''', (amount, sell_ownership_id))
  575. if buyer_id != bank_id(): # buyer receives
  576. cursor.execute('''
  577. UPDATE ownership
  578. SET amount = amount + ?
  579. WHERE rowid = ?
  580. ''', (amount, buy_ownership_id))
  581. if seller_id != bank_id(): # seller receives
  582. cursor.execute('''
  583. UPDATE ownership
  584. SET amount = amount + ?
  585. WHERE user_id = ?
  586. AND ownable_id = ?
  587. ''', (price * amount, seller_id, currency_id()))
  588. # update order execution state
  589. cursor.execute('''
  590. UPDATE orders
  591. SET executed_amount = executed_amount + ?
  592. WHERE rowid = ?
  593. OR rowid = ?
  594. ''', (amount, buy_order_id, sell_order_id))
  595. if buy_order_finished:
  596. delete_order(buy_order_id)
  597. if sell_order_finished:
  598. delete_order(sell_order_id)
  599. if seller_id != buyer_id: # prevent showing self-transactions
  600. cursor.execute('''
  601. INSERT INTO transactions
  602. (price, ownable_id, amount)
  603. VALUES(?, ?, ?)
  604. ''', (price, ownable_id, amount,))
  605. # trigger stop-loss orders
  606. if buyer_id != seller_id:
  607. cursor.execute('''
  608. UPDATE orders
  609. SET stop_loss = NULL,
  610. "limit" = NULL
  611. WHERE stop_loss IS NOT NULL
  612. AND stop_loss
  613. AND ? IN (SELECT ownable_id FROM ownership WHERE rowid = ownership_id)
  614. AND ((buy AND "limit" < ?) OR (NOT buy AND "limit" > ?))
  615. ''', (ownable_id, price, price,))
  616. def ownable_id_by_ownership_id(ownership_id):
  617. connect()
  618. cursor.execute('''
  619. SELECT ownable_id
  620. FROM ownership
  621. WHERE rowid = ?
  622. ''', (ownership_id,))
  623. return cursor.fetchone()[0]
  624. def ownable_name_by_id(ownable_id):
  625. connect()
  626. cursor.execute('''
  627. SELECT name
  628. FROM ownables
  629. WHERE rowid = ?
  630. ''', (ownable_id,))
  631. return cursor.fetchone()[0]
  632. def bank_order(buy, ownable_id, limit, amount, time_until_expiration):
  633. if not limit:
  634. raise AssertionError('The bank does not give away anything.')
  635. place_order(buy,
  636. get_ownership_id(ownable_id, bank_id()),
  637. limit,
  638. False,
  639. amount,
  640. time_until_expiration)
  641. ownable_name = ownable_name_by_id(ownable_id)
  642. new_news('External investors are selling ' + ownable_name + ' atm')
  643. def current_db_time(): # might differ from datetime.datetime.now() for time zone reasons
  644. connect()
  645. cursor.execute('''
  646. SELECT datetime('now')
  647. ''')
  648. return cursor.fetchone()[0]
  649. def place_order(buy, ownership_id, limit, stop_loss, amount, time_until_expiration):
  650. connect()
  651. expiry = datetime.strptime(current_db_time(), '%Y-%m-%d %H:%M:%S') + timedelta(minutes=time_until_expiration)
  652. cursor.execute('''
  653. INSERT INTO orders
  654. (buy, ownership_id, "limit", stop_loss, ordered_amount, expiry_dt)
  655. VALUES (?, ?, ?, ?, ?, ?)
  656. ''', (buy, ownership_id, limit, stop_loss, amount, expiry))
  657. execute_orders(ownable_id_by_ownership_id(ownership_id))
  658. return True
  659. def transactions(ownable_id, limit):
  660. connect()
  661. cursor.execute('''
  662. SELECT datetime(dt,'localtime'), amount, price
  663. FROM transactions
  664. WHERE ownable_id = ?
  665. ORDER BY rowid DESC -- equivalent to order by dt
  666. LIMIT ?
  667. ''', (ownable_id, limit,))
  668. return cursor.fetchall()
  669. def drop_expired_orders():
  670. connect()
  671. cursor.execute('''
  672. DELETE FROM orders
  673. WHERE expiry_dt < DATETIME('now')
  674. ''')
  675. return cursor.fetchall()
  676. def generate_keys(count=1):
  677. # source https://stackoverflow.com/questions/17049308/python-3-3-serial-key-generator-list-problems
  678. for i in range(count):
  679. key = '-'.join(random_chars(5) for _ in range(5))
  680. save_key(key)
  681. print(key)
  682. def user_has_order_with_id(session_id, order_id):
  683. connect()
  684. cursor.execute('''
  685. SELECT orders.rowid
  686. FROM orders, ownership, sessions
  687. WHERE orders.rowid = ?
  688. AND sessions.session_id = ?
  689. AND sessions.user_id = ownership.user_id
  690. AND ownership.rowid = orders.ownership_id
  691. ''', (order_id, session_id,))
  692. if cursor.fetchone():
  693. return True
  694. else:
  695. return False
  696. def leaderboard():
  697. connect()
  698. cursor.execute('''
  699. SELECT *
  700. FROM ( -- one score for each user
  701. SELECT
  702. username,
  703. SUM(CASE -- sum score for each of the users ownables
  704. WHEN ownership.ownable_id = ? THEN ownership.amount
  705. ELSE ownership.amount * (SELECT price
  706. FROM transactions
  707. WHERE ownable_id = ownership.ownable_id
  708. ORDER BY rowid DESC -- equivalent to ordering by dt
  709. LIMIT 1)
  710. END
  711. ) score
  712. FROM users, ownership
  713. WHERE ownership.user_id = users.rowid
  714. AND users.username != 'bank'
  715. GROUP BY users.rowid
  716. ) AS scores
  717. ORDER BY score DESC
  718. LIMIT 50
  719. ''', (currency_id(),))
  720. return cursor.fetchall()
  721. def user_wealth(user_id):
  722. connect()
  723. cursor.execute('''
  724. SELECT SUM(
  725. CASE -- sum score for each of the users ownables
  726. WHEN ownership.ownable_id = ? THEN ownership.amount
  727. ELSE ownership.amount * (SELECT price
  728. FROM transactions
  729. WHERE ownable_id = ownership.ownable_id
  730. ORDER BY rowid DESC -- equivalent to ordering by dt
  731. LIMIT 1)
  732. END
  733. ) score
  734. FROM ownership
  735. WHERE ownership.user_id = ?
  736. ''', (currency_id(), user_id,))
  737. return cursor.fetchone()[0]
  738. def change_password(session_id, password):
  739. connect()
  740. cursor.execute('''
  741. UPDATE users
  742. SET password = ?
  743. WHERE rowid = (SELECT user_id FROM sessions WHERE sessions.session_id = ?)
  744. ''', (password, session_id,))
  745. def sign_out_user(session_id):
  746. connect()
  747. cursor.execute('''
  748. DELETE FROM sessions
  749. WHERE user_id = (SELECT user_id FROM sessions s2 WHERE s2.session_id = ?)
  750. ''', (session_id,))
  751. def delete_user(user_id):
  752. connect()
  753. cursor.execute('''
  754. DELETE FROM sessions
  755. WHERE user_id = ?
  756. ''', (user_id,))
  757. cursor.execute('''
  758. DELETE FROM orders
  759. WHERE ownership_id IN (
  760. SELECT rowid FROM ownership WHERE user_id = ?)
  761. ''', (user_id,))
  762. cursor.execute('''
  763. DELETE FROM ownership
  764. WHERE user_id = ?
  765. ''', (user_id,))
  766. cursor.execute('''
  767. DELETE FROM keys
  768. WHERE used_by_user_id = ?
  769. ''', (user_id,))
  770. cursor.execute('''
  771. INSERT INTO news(title)
  772. VALUES ((SELECT username FROM users WHERE rowid = ?) || ' retired.')
  773. ''', (user_id,))
  774. cursor.execute('''
  775. DELETE FROM users
  776. WHERE rowid = ?
  777. ''', (user_id,))
  778. def delete_ownable(ownable_id):
  779. connect()
  780. cursor.execute('''
  781. DELETE FROM transactions
  782. WHERE ownable_id = ?
  783. ''', (ownable_id,))
  784. cursor.execute('''
  785. DELETE FROM orders
  786. WHERE ownership_id IN (
  787. SELECT rowid FROM ownership WHERE ownable_id = ?)
  788. ''', (ownable_id,))
  789. # only delete empty ownerships
  790. cursor.execute('''
  791. DELETE FROM ownership
  792. WHERE ownable_id = ?
  793. AND amount = 0
  794. ''', (ownable_id,))
  795. cursor.execute('''
  796. INSERT INTO news(title)
  797. VALUES ((SELECT name FROM ownables WHERE rowid = ?) || ' can not be traded any more.')
  798. ''', (ownable_id,))
  799. cursor.execute('''
  800. DELETE FROM ownables
  801. WHERE rowid = ?
  802. ''', (ownable_id,))
  803. def hash_all_users_passwords():
  804. connect()
  805. cursor.execute('''
  806. SELECT rowid, password
  807. FROM users
  808. ''')
  809. users = cursor.fetchall()
  810. for user in users:
  811. user_id = user[0]
  812. pw = user[1]
  813. valid_hash = True
  814. try:
  815. sha256_crypt.verify('password' + salt, pw)
  816. except ValueError:
  817. valid_hash = False
  818. if valid_hash:
  819. raise AssertionError('There is already a hashed password in the database! Be careful what you are doing!')
  820. pw = sha256_crypt.encrypt(pw + salt)
  821. cursor.execute('''
  822. UPDATE users
  823. SET password = ?
  824. WHERE rowid = ?
  825. ''', (pw, user_id,))
  826. def new_news(message):
  827. connect()
  828. cursor.execute('''
  829. INSERT INTO news(title)
  830. VALUES (?)
  831. ''', (message,))
  832. def ownables():
  833. connect()
  834. cursor.execute('''
  835. SELECT name, course,
  836. (SELECT SUM(amount)
  837. FROM ownership
  838. WHERE ownership.ownable_id = ownables_with_course.rowid) market_size
  839. FROM (SELECT
  840. name, ownables.rowid,
  841. CASE WHEN ownables.rowid = ?
  842. THEN 1
  843. ELSE (SELECT price
  844. FROM transactions
  845. WHERE ownable_id = ownables.rowid
  846. ORDER BY rowid DESC -- equivalent to ordering by dt
  847. LIMIT 1) END course
  848. FROM ownables) ownables_with_course
  849. ''', (currency_id(),))
  850. data = cursor.fetchall()
  851. for idx in range(len(data)):
  852. # compute market cap
  853. row = data[idx]
  854. if row[1] is None:
  855. market_cap = None
  856. elif row[2] is None:
  857. market_cap = None
  858. else:
  859. market_cap = row[1] * row[2]
  860. data[idx] = (row[0], row[1], market_cap)
  861. return data