瀏覽代碼

implement selling and transaction listing

Eren Yilmaz 6 年之前
父節點
當前提交
3811e3ea33
共有 6 個文件被更改,包括 105 次插入6 次删除
  1. 3 1
      client.py
  2. 42 0
      client_controller.py
  3. 3 3
      db_setup.py
  4. 47 1
      model.py
  5. 1 1
      server.py
  6. 9 0
      server_controller.py

+ 3 - 1
client.py

@@ -57,7 +57,9 @@ allowed_commands = ['help',
                     'orders',
                     'news',
                     'activate_key',
-                    'buy']
+                    'buy',
+                    'sell',
+                    'transactions']
 
 
 def one_command():

+ 42 - 0
client_controller.py

@@ -131,6 +131,32 @@ def buy(amount=None, object_name=None, limit='', stop_loss=''):
                                         "stop_loss": stop_loss})
     if 'error_message' in response:
         print('Order placement failed with message:', response['error_message'])
+    else:
+        print('You might want to use the `transactions` or `depot` commands',
+              'to see if the order has been executed already.')
+
+
+def sell(amount=None, object_name=None, limit='', stop_loss=''):
+    if object_name is None:  # TODO list some available objects
+        object_name = input('Name of object to sell: ')
+    if amount is None:
+        amount = input('Amount: ')
+    if limit != '':
+        set_limit = yn_dialog('Do you want to place a limit?')
+        if set_limit:
+            limit = input('Limit: ')
+            stop_loss = yn_dialog('Is this a stop-loss limit?')
+    response = client_request('order', {"buy": False,
+                                        "session_id": connection.session_id,
+                                        "amount": amount,
+                                        "ownable": object_name,
+                                        "limit": limit,
+                                        "stop_loss": stop_loss})
+    if 'error_message' in response:
+        print('Order placement failed with message:', response['error_message'])
+    else:
+        print('You might want to use the `transactions` or `depot` commands',
+              'to see if the order has been executed already.')
 
 
 def orders():
@@ -159,3 +185,19 @@ def news():
             print('Order access failed with message:', response['error_message'])
         else:
             print('Order access failed.')
+
+
+def transactions(object_name=None):
+    if object_name is None:  # TODO list some available objects
+        object_name = input('Name of object to check: ')
+    response = client_request('transactions', {"session_id": connection.session_id, "ownable": object_name})
+    success = 'data' in response
+    if success:
+        print(tabulate(response['data'],
+                       # TODO headers=['Date', 'Title'],
+                       tablefmt="pipe"))
+    else:
+        if 'error_message' in response:
+            print('Transactions access failed with message:', response['error_message'])
+        else:
+            print('Transactions access failed.')

+ 3 - 3
db_setup.py

@@ -1,12 +1,12 @@
 from game import CURRENCY_NAME
 from util import debug
 
+replace = False and debug
+
 
 def setup(cursor):
     print('Database setup...')
 
-    replace = False and debug
-
     if replace:
         drop_database(cursor)
 
@@ -207,7 +207,7 @@ def tables(cursor):
                 ''')
     cursor.execute('''
                 CREATE TABLE IF NOT EXISTS news(
-                    dt DATETIME NOT NULL,
+                    dt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                     title VARCHAR(50) NOT NULL
                 )
                 ''')

+ 47 - 1
model.py

@@ -1,3 +1,4 @@
+import random
 import re
 import sqlite3 as db
 import sys
@@ -373,7 +374,7 @@ def news():
     cursor.execute('''
         SELECT *
         FROM news
-        ORDER BY dt
+        ORDER BY dt DESC
         LIMIT 20
         ''')
 
@@ -407,6 +408,28 @@ def new_stock(name=None):
         INSERT INTO ownables(name)
         VALUES (?)
         ''', (name,))
+
+    cursor.execute('''
+        INSERT INTO news(title)
+        VALUES (?)
+        ''', ('A new stock can now be bought: ' + name,))
+    if random.getrandbits(1):
+        cursor.execute('''
+            INSERT INTO news(title)
+            VALUES (?)
+            ''', ('Experts expect the price of ' + name + ' to fall',))
+    else:
+        cursor.execute('''
+            INSERT INTO news(title)
+            VALUES (?)
+            ''', ('Experts expect the price of ' + name + ' to rise',))
+
+    amount = random.randrange(100, 10000)
+    price = random.randrange(10000, 20000) / amount
+    bank_order(True,
+               ownable_id_by_name(name),
+               price,
+               amount)
     return name
 
 
@@ -560,6 +583,16 @@ def ownable_id_by_ownership_id(ownership_id):
     return cursor.fetchone()[0]
 
 
+def bank_order(buy, ownable_id, limit, amount):
+    if limit is None:
+        raise AssertionError()
+    place_order(buy,
+                get_ownership_id(ownable_id, bank_id()),
+                limit,
+                False,
+                amount)
+
+
 def place_order(buy, ownership_id, limit, stop_loss, amount):
     connect()
 
@@ -571,3 +604,16 @@ def place_order(buy, ownership_id, limit, stop_loss, amount):
 
     execute_orders(ownable_id_by_ownership_id(ownership_id))
     return True
+
+
+def transactions(ownable_id):
+    connect()
+
+    cursor.execute('''
+        SELECT dt, amount, price
+        FROM transactions
+        WHERE ownable_id = ?
+        ORDER BY dt DESC
+        ''', (ownable_id,))
+
+    return cursor.fetchall()

+ 1 - 1
server.py

@@ -13,7 +13,7 @@ if __name__ == '__main__':
 
     model.setup()
 
-    valid_routes = ['login', 'register', 'depot', 'activate_key', 'order', 'orders', 'news']
+    valid_routes = ['login', 'register', 'depot', 'activate_key', 'order', 'orders', 'news', 'transactions']
 
 
     @route('/<path>', method='POST')

+ 9 - 0
server_controller.py

@@ -115,6 +115,15 @@ def news():
     return {'data': model.news()}
 
 
+def transactions():
+    missing = missing_attributes(['session_id', 'ownable_id'])
+    if missing:
+        return bad_request(missing)
+    if not model.ownable_name_exists(request.json['ownable']):
+        return bad_request('This kind of object can not have transactions.')
+    return {'data': model.transactions()}
+
+
 def not_found(msg=''):
     response.status = 404
     if debug: