1
1

client_controller.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. import sys
  2. from getpass import getpass
  3. from inspect import signature
  4. import connection
  5. from connection import client_request
  6. from debug import debug
  7. from game import DEFAULT_ORDER_EXPIRY, CURRENCY_NAME, MIN_INTEREST_INTERVAL
  8. from routes import client_commands
  9. from run_client import fake_loading_bar
  10. from util import my_tabulate, yn_dialog
  11. exiting = False
  12. def login(username=None, password=None):
  13. if connection.session_id is not None:
  14. fake_loading_bar('Signing out', duration=0.7)
  15. connection.session_id = None
  16. if username is None:
  17. username = input('Username: ')
  18. if password is None:
  19. if sys.stdin.isatty():
  20. password = getpass('Password: ')
  21. else:
  22. password = input('Password: ')
  23. fake_loading_bar('Signing in', duration=2.3)
  24. response = client_request('login', {"username": username, "password": password})
  25. success = 'session_id' in response
  26. if success:
  27. connection.session_id = response['session_id']
  28. print('Login successful.')
  29. else:
  30. if 'error' in response:
  31. print('Login failed with message:', response['error'])
  32. else:
  33. print('Login failed.')
  34. def register(username=None, game_key='', password=None, retype_pw=None):
  35. if connection.session_id is not None:
  36. connection.session_id = None
  37. fake_loading_bar('Signing out', duration=0.7)
  38. if username is None:
  39. username = input('Username: ')
  40. if password is None:
  41. if sys.stdin.isatty():
  42. password = getpass('New password: ')
  43. retype_pw = getpass('Retype password: ')
  44. else:
  45. password = input('New password: ')
  46. retype_pw = input('Retype password: ')
  47. if password != retype_pw:
  48. print('Passwords do not match.')
  49. return
  50. elif retype_pw is None:
  51. if sys.stdin.isatty():
  52. retype_pw = getpass('Retype password: ')
  53. else:
  54. retype_pw = input('Retype password: ')
  55. if password != retype_pw:
  56. print('Passwords do not match.')
  57. return
  58. if not debug:
  59. if game_key == '':
  60. print('Entering a game key will provide you with some starting money and other useful stuff.')
  61. game_key = input('Game key (leave empty if you don\'t have one): ')
  62. fake_loading_bar('Validating Registration', duration=5.2)
  63. if game_key != '':
  64. fake_loading_bar('Validating Game Key', duration=0.4)
  65. response = client_request('register', {"username": username, "password": password, "game_key": game_key})
  66. if 'error' in response:
  67. print('Registration failed with message:', response['error'])
  68. def cancel_order(order_no=None):
  69. if order_no is None:
  70. order_no = input('Order No.: ')
  71. fake_loading_bar('Validating Request', duration=0.6)
  72. response = client_request('cancel_order', {"session_id": connection.session_id, "order_id": order_no})
  73. if 'error' in response:
  74. print('Order cancelling failed with message:', response['error'])
  75. def change_pw(password=None, retype_pw=None):
  76. if password != retype_pw:
  77. password = None
  78. if password is None:
  79. if sys.stdin.isatty():
  80. password = getpass('New password: ')
  81. retype_pw = getpass('Retype password: ')
  82. else:
  83. password = input('New password: ')
  84. retype_pw = input('Retype password: ')
  85. if password != retype_pw:
  86. print('Passwords do not match.')
  87. return
  88. elif retype_pw is None:
  89. if sys.stdin.isatty():
  90. retype_pw = getpass('Retype password: ')
  91. else:
  92. retype_pw = input('Retype password: ')
  93. if password != retype_pw:
  94. print('Passwords do not match.')
  95. return
  96. fake_loading_bar('Validating password', duration=1.2)
  97. fake_loading_bar('Changing password', duration=5.2)
  98. response = client_request('change_password', {"session_id": connection.session_id, "password": password})
  99. if 'error' in response:
  100. print('Changing password failed with message:', response['error'])
  101. fake_loading_bar('Signing out', duration=0.7)
  102. connection.session_id = None
  103. # noinspection PyShadowingBuiltins
  104. def help():
  105. print('Allowed commands:')
  106. command_table = []
  107. for cmd in client_commands:
  108. this_module = sys.modules[__name__]
  109. method = getattr(this_module, cmd)
  110. params = signature(method).parameters
  111. command_table.append([cmd] + [p for p in params])
  112. print(my_tabulate(command_table, tablefmt='pipe', headers=['command',
  113. 'param 1',
  114. 'param 2',
  115. 'param 3',
  116. 'param 4',
  117. 'param 5',
  118. ]))
  119. print('NOTE:')
  120. print(' All parameters for all commands are optional!')
  121. print(' Commands can be combined in one line with ; between them.')
  122. print(' Parameters are separated with whitespace.')
  123. print(' Use . as a decimal separator.')
  124. print(' Use 0/1 for boolean parameters (other strings might work).')
  125. def depot():
  126. fake_loading_bar('Loading data', duration=1.3)
  127. response = client_request('depot', {"session_id": connection.session_id})
  128. success = 'data' in response and 'own_wealth' in response
  129. if success:
  130. data = response['data']
  131. for row in data:
  132. row.append(row[1] * row[2])
  133. print(my_tabulate(data,
  134. headers=['Object', 'Amount', 'Course', 'Bid', 'Ask', 'Est. Value'],
  135. tablefmt="pipe",
  136. floatfmt='.2f'))
  137. wealth = response['own_wealth']
  138. print(f'Taking into account the amount of loans you have, this results in a wealth of roughly {wealth}.')
  139. if response['banking_license']:
  140. print(f'Also, you have a banking license.')
  141. else:
  142. if 'error' in response:
  143. print('Depot access failed with message:', response['error'])
  144. else:
  145. print('Depot access failed.')
  146. def leaderboard():
  147. fake_loading_bar('Loading data', duration=1.3)
  148. response = client_request('leaderboard', {})
  149. success = 'data' in response
  150. if success:
  151. print(my_tabulate(response['data'], headers=['Trader', 'Wealth'], tablefmt="pipe"))
  152. # print('Remember that the goal is to be as rich as possible, not to be richer than other traders!')
  153. else:
  154. if 'error' in response:
  155. print('Leaderboard access failed with message:', response['error'])
  156. else:
  157. print('Leaderboard access failed.')
  158. def activate_key(key=''):
  159. if key == '':
  160. print('Entering a game key may get you some money or other useful stuff.')
  161. key = input('Key: ')
  162. if key == '':
  163. print('Invalid key.')
  164. fake_loading_bar('Validating Key', duration=0.4)
  165. response = client_request('activate_key', {"session_id": connection.session_id, 'key': key})
  166. if 'error' in response:
  167. print('Key activation failed with message:', response['error'])
  168. def _order(is_buy_order, obj_name, amount, limit, stop_loss, expiry):
  169. if stop_loss not in [None, '1', '0']:
  170. print('Invalid value for flag stop loss (only 0 or 1 allowed).')
  171. return
  172. if obj_name is None: # TODO list some available objects
  173. obj_name = input('Name of object to sell: ')
  174. if amount is None:
  175. amount = input('Amount: ')
  176. if limit is None:
  177. set_limit = yn_dialog('Do you want to place a limit?')
  178. if set_limit:
  179. limit = input('Limit: ')
  180. stop_loss = yn_dialog('Is this a stop-loss limit?')
  181. if limit is not None:
  182. try:
  183. limit = float(limit)
  184. except ValueError:
  185. print('Invalid limit.')
  186. return
  187. if stop_loss is None:
  188. stop_loss = yn_dialog('Is this a stop-loss limit?')
  189. question = 'Are you sure you want to use such a low limit (limit=' + str(limit) + ')?:'
  190. if not is_buy_order and limit <= 0 and not yn_dialog(question):
  191. print('Order was not placed.')
  192. return
  193. if expiry is None:
  194. expiry = input('Time until order expires (minutes, default ' + str(DEFAULT_ORDER_EXPIRY) + '):')
  195. if expiry == '':
  196. expiry = DEFAULT_ORDER_EXPIRY
  197. try:
  198. expiry = float(expiry)
  199. except ValueError:
  200. print('Invalid expiration time.')
  201. return
  202. fake_loading_bar('Sending Data', duration=1.3)
  203. response = client_request('order', {
  204. "buy": is_buy_order,
  205. "session_id": connection.session_id,
  206. "amount": amount,
  207. "ownable": obj_name,
  208. "limit": limit,
  209. "stop_loss": stop_loss,
  210. "time_until_expiration": expiry
  211. })
  212. if 'error' in response:
  213. print('Order placement failed with message:', response['error'])
  214. else:
  215. print('You might want to use the `trades` or `depot` commands',
  216. 'to see if the order has been executed already.')
  217. def sell(obj_name=None, amount=None, limit=None, stop_loss=None, expiry=None):
  218. _order(is_buy_order=False,
  219. obj_name=obj_name,
  220. amount=amount,
  221. limit=limit,
  222. stop_loss=stop_loss,
  223. expiry=expiry)
  224. def buy(obj_name=None, amount=None, limit=None, stop_loss=None, expiry=None):
  225. _order(is_buy_order=True,
  226. obj_name=obj_name,
  227. amount=amount,
  228. limit=limit,
  229. stop_loss=stop_loss,
  230. expiry=expiry)
  231. def orders():
  232. fake_loading_bar('Loading Data', duration=0.9)
  233. response = client_request('orders', {"session_id": connection.session_id})
  234. success = 'data' in response
  235. if success:
  236. print(my_tabulate(response['data'],
  237. headers=['Buy?', 'Name', 'Size', 'Limit', 'stop-loss', 'Expires', 'No.'],
  238. tablefmt="pipe"))
  239. else:
  240. if 'error' in response:
  241. print('Order access failed with message:', response['error'])
  242. else:
  243. print('Order access failed.')
  244. def buy_banking_license():
  245. fake_loading_bar('Loading data', duration=2.3)
  246. fake_loading_bar('Hiring some lawyers and consultants', duration=4.6)
  247. fake_loading_bar('Overcoming some bureaucratic hurdles', duration=8.95)
  248. fake_loading_bar('Filling the necessary forms', duration=14.4)
  249. fake_loading_bar('Waiting for bank regulation\'s response', duration=26.8)
  250. response = client_request('buy_banking_license', {"session_id": connection.session_id})
  251. success = 'message' in response and 'error' not in response
  252. if success:
  253. print('Success. You are now a bank.')
  254. print()
  255. summarize_bank_rules()
  256. # print('Remember that the goal is to be as rich as possible, not to be richer than other traders!')
  257. else:
  258. if 'error' in response:
  259. print('Banking license application failed with message:', response['error'])
  260. else:
  261. print('Banking license application access failed.')
  262. def summarize_bank_rules(): # TODO rework this stuff, does not work like this in real life
  263. variables = _global_variables()
  264. banking_license_price = variables['banking_license_price']
  265. marginal_lending_facility = variables['marginal_lending_facility']
  266. cash_reserve_free_amount = variables['cash_reserve_free_amount']
  267. cash_reserve_ratio = variables['cash_reserve_ratio']
  268. deposit_facility = variables['deposit_facility']
  269. print(f'A bank is by definition anyone who has a banking license.')
  270. print(f'A banking license can be for {banking_license_price} {CURRENCY_NAME}.')
  271. print(f'This includes payment of lawyers and consultants to deal with the formal application.')
  272. print()
  273. print(f'Banks are allowed to borrow money from the central bank at the marginal '
  274. f'lending facility (currently {marginal_lending_facility * 100}% p.a.).')
  275. print(f'For every {CURRENCY_NAME} above {cash_reserve_free_amount} banks have to '
  276. f'deposit a cash reserve of {cash_reserve_ratio * 100}% at the central bank.')
  277. print(f'Banks receive a deposit facility of {deposit_facility * 100}% p.a. for cash reserves.')
  278. def summarize_loan_rules():
  279. variables = _global_variables()
  280. personal_loan_interest_rate = variables['personal_loan_interest_rate']
  281. print(f'You can take personal loans at an interest rate of {personal_loan_interest_rate * 100}% p.a.')
  282. print(f'You can repay personal loans at any time if you have the liquidity.')
  283. print(f'Interest rates will be automatically be debited from your account.')
  284. print(f'Note that this debit may be delayed by up to {MIN_INTEREST_INTERVAL} seconds.')
  285. print(f'If you have no {CURRENCY_NAME} available (or negative account balance), you can still')
  286. print(f' - pay any further interests (account will move further into the negative)')
  287. print(f' - take a new loan (if we think that you will be able to repay it)')
  288. print(f' - sell any securities you own')
  289. print(f'However you can not')
  290. print(f' - spend money to buy securities')
  291. print(f' - spend money to buy a banking license')
  292. def take_out_personal_loan(amount=None):
  293. if amount is None:
  294. summarize_loan_rules()
  295. print()
  296. amount = input('Please enter your desired loan volume: ')
  297. try:
  298. amount = float(amount)
  299. except ValueError:
  300. print('Amount must be a number larger than 0.')
  301. return
  302. if amount <= 0:
  303. print('Amount must be a number larger than 0.')
  304. fake_loading_bar('Checking if you are trustworthy', duration=0.0)
  305. fake_loading_bar('Checking if you are credit-worthy', duration=0.0)
  306. fake_loading_bar('Transferring the money', duration=1.6)
  307. response = client_request('take_out_personal_loan', {"session_id": connection.session_id, 'amount': amount})
  308. success = 'message' in response and 'error' not in response
  309. if success:
  310. print(f'You took a personal loan of {amount} {CURRENCY_NAME}.')
  311. else:
  312. if 'error' in response:
  313. print('Taking a personal loan failed with message:', response['error'])
  314. else:
  315. print('Taking a personal loan failed.')
  316. def loans():
  317. fake_loading_bar('Loading Data', duration=0.9)
  318. response = client_request('loans', {"session_id": connection.session_id})
  319. success = 'data' in response
  320. if success:
  321. for row in response['data']:
  322. row[-1] = f'{row[-1] * 100:.2f}%'
  323. print(my_tabulate(response['data'],
  324. headers=['Loan ID', 'Total amount', 'Remaining', 'Interest p.a.', ],
  325. floatfmt='.2f',
  326. tablefmt="pipe"))
  327. else:
  328. if 'error' in response:
  329. print('Order access failed with message:', response['error'])
  330. else:
  331. print('Order access failed.')
  332. def repay_loan(loan_id=None, amount=None):
  333. if loan_id is None:
  334. loans()
  335. print('Which loan would you like to pay back?')
  336. loan_id = input('Loan id:')
  337. if amount is None:
  338. print('How much would you like to pay back?')
  339. amount = input('Amount (type `all` for the remaining loan):')
  340. if amount != 'all':
  341. try:
  342. amount = float(amount) # this can also raise a ValueError
  343. if amount <= 0:
  344. raise ValueError
  345. except ValueError:
  346. print('Amount must be a number larger than 0 or \'all\' (for paying back the remaining loan).')
  347. return
  348. fake_loading_bar('Transferring the money', duration=1.7)
  349. response = client_request('repay_loan', {"session_id": connection.session_id, 'amount': amount, 'loan_id': loan_id})
  350. success = 'message' in response and 'error' not in response
  351. if success:
  352. print(f'You repayed the specified amount of {CURRENCY_NAME}.')
  353. else:
  354. if 'error' in response:
  355. print('Repaying the loan failed with message:', response['error'])
  356. else:
  357. print('Repaying the loan failed.')
  358. def _global_variables():
  359. return client_request('global_variables')
  360. def orders_on(obj_name=None):
  361. if obj_name is None: # TODO list some available objects
  362. obj_name = input('Name of object to check: ')
  363. fake_loading_bar('Loading Data', duration=2.3)
  364. response = client_request('orders_on', {"session_id": connection.session_id, "ownable": obj_name})
  365. success = 'data' in response
  366. if success:
  367. print(my_tabulate(response['data'],
  368. headers=['My', 'Buy?', 'Name', 'Size', 'Limit', 'Expires', 'No.'],
  369. tablefmt="pipe"))
  370. else:
  371. if 'error' in response:
  372. print('Order access failed with message:', response['error'])
  373. else:
  374. print('Order access failed.')
  375. def gift(username=None, obj_name=None, amount=None):
  376. if username is None:
  377. username = input('Username of recipient: ')
  378. if obj_name is None:
  379. obj_name = input('Name of object to give: ')
  380. if amount is None:
  381. amount = input('How many?: ')
  382. fake_loading_bar('Sending Gift', duration=4.2)
  383. response = client_request('gift',
  384. {"session_id": connection.session_id,
  385. "username": username,
  386. "object_name": obj_name,
  387. "amount": amount})
  388. if 'error' in response:
  389. print('Order access failed with message:', response['error'])
  390. elif 'message' in response:
  391. print(response['message'])
  392. def news():
  393. fake_loading_bar('Loading Data', duration=0.76)
  394. response = client_request('news', {})
  395. success = 'data' in response
  396. if success:
  397. print(my_tabulate(response['data'],
  398. headers=['Date', 'Title'],
  399. tablefmt="pipe"))
  400. else:
  401. if 'error' in response:
  402. print('News access failed with message:', response['error'])
  403. else:
  404. print('News access failed.')
  405. def tradables():
  406. fake_loading_bar('Loading Data', duration=12.4)
  407. response = client_request('tradables', {})
  408. success = 'data' in response
  409. if success:
  410. print(my_tabulate(response['data'],
  411. headers=['Name', 'Course', 'Market Cap.'],
  412. tablefmt="pipe"))
  413. world_wealth = 0
  414. for row in response['data']:
  415. if row[2] is not None:
  416. world_wealth += row[2]
  417. print('Estimated worldwide wealth:', world_wealth)
  418. else:
  419. if 'error' in response:
  420. print('Data access failed with message:', response['error'])
  421. else:
  422. print('Data access failed.')
  423. def trades_on(obj_name=None, limit=5):
  424. limit = float(limit)
  425. if obj_name is None: # TODO list some available objects
  426. obj_name = input('Name of object to check: ')
  427. fake_loading_bar('Loading Data', duration=0.34 * limit)
  428. response = client_request('trades_on', {"session_id": connection.session_id,
  429. "ownable": obj_name,
  430. "limit": limit})
  431. success = 'data' in response
  432. if success:
  433. print(my_tabulate(response['data'],
  434. headers=['Time', 'Volume', 'Price'],
  435. tablefmt="pipe"))
  436. else:
  437. if 'error' in response:
  438. print('Trades access failed with message:', response['error'])
  439. else:
  440. print('Trades access failed.')
  441. def trades(limit=10):
  442. limit = float(limit)
  443. fake_loading_bar('Loading Data', duration=limit * 0.21)
  444. response = client_request('trades', {"session_id": connection.session_id,
  445. "limit": limit})
  446. success = 'data' in response
  447. if success:
  448. print(my_tabulate(response['data'],
  449. headers=['Buy?', 'Name', 'Volume', 'Price', 'Time'],
  450. tablefmt="pipe"))
  451. else:
  452. if 'error' in response:
  453. print('Trades access failed with message:', response['error'])
  454. else:
  455. print('Trades access failed.')
  456. def old_orders(include_canceled=None, include_executed=None, limit=10):
  457. limit = float(limit)
  458. if include_canceled is None:
  459. include_canceled = yn_dialog('Include canceled/expired orders in list?')
  460. if include_executed is None:
  461. include_executed = yn_dialog('Include fully executed orders in list?')
  462. fake_loading_bar('Loading Data', duration=limit * 0.27)
  463. response = client_request('old_orders', {"session_id": connection.session_id,
  464. "include_canceled": include_canceled,
  465. "include_executed": include_executed,
  466. "limit": limit})
  467. success = 'data' in response
  468. if success:
  469. print(my_tabulate(response['data'],
  470. headers=['Buy?', 'Name', 'Size', 'Limit', 'Expiry', 'No.', 'Status'],
  471. tablefmt="pipe"))
  472. else:
  473. if 'error' in response:
  474. print('Order access failed with message:', response['error'])
  475. else:
  476. print('Order access failed.')
  477. # noinspection PyShadowingBuiltins
  478. def exit():
  479. global exiting
  480. exiting = True