model.py 30 KB

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