1
1

client_controller.py 26 KB

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