model.py 31 KB

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