btc-ticker 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  5. # Copyright (C)2013-2016 Philemon <mmgen-py@yandex.com>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. """
  21. btc-ticker: ticker and alarm clock for mmgen-node-tools
  22. """
  23. import sys,os,time,subprocess
  24. import threading as th
  25. from collections import OrderedDict
  26. from decimal import Decimal
  27. from mmgen.share import Opts
  28. from mmgen.util import msg,msg_r,die,die_pause
  29. from mmgen.node_tools.Global import *
  30. from mmgen.node_tools.Util import *
  31. from mmgen.node_tools.Sound import *
  32. from mmgen.node_tools.Term import *
  33. from mmgen.color import *
  34. init_color()
  35. quit = False
  36. sound_vol = float(100)
  37. audio_host,repeat_spec = '','3s:5m,1m:30m,5m:1h,30m:1d'
  38. # repeat_spec = '1:5m' # DEBUG
  39. valid_loglevels = OrderedDict([(1,'info'),(2,'data'),(3,'debug')])
  40. logfile = 'ticker_log.txt'
  41. alrm_clock = 'off'
  42. num_digits = 6
  43. proxy = None
  44. fx_host= 'https://finance.yahoo.com'
  45. sounds_dir = nt.system_data_dir+'/audio'
  46. sounds = {
  47. 'lo': [sounds_dir+'/ringtone.wav', 95],
  48. 'hi': [sounds_dir+'/Positive.wav', 102],
  49. 'conn_err': [sounds_dir+'/Rhodes.wav', 105],
  50. 'alrm_clock': [sounds_dir+'/Counterpoint.wav', 105],
  51. }
  52. alrm_names = tuple(sounds.keys())
  53. dlock,llock,alock = th.Lock(),th.Lock(),th.Lock()
  54. data_dir = nt.data_dir+'/lib/ticker/'
  55. try: os.makedirs(data_dir)
  56. except: pass
  57. def update_fx(a,b,debug=False):
  58. if debug:
  59. with open('/tmp/ticker.out') as f: text = f.read()
  60. else:
  61. text = get_url('{}/q?s={}{}'.format(fx_host,a,b),gzip_ok=True,proxy=proxy,debug=debug_curl)
  62. if not text: return False
  63. import re
  64. ret = re.split('yfs_l10_{}{}=.+?>'.format(a,b),text,maxsplit=1)[1].split('<',1)[0][:10]
  65. try:
  66. globals()[a+b] = float(ret)
  67. with open(data_dir+'/{}{}.txt'.format(a,b),'wb') as f: f.write(ret+'\n')
  68. return True
  69. except:
  70. return False
  71. def get_fx(a,b):
  72. try:
  73. with open(data_dir+'/{}{}.txt'.format(a,b)) as f:
  74. d = f.read().rstrip()
  75. globals()[a+b] = float(d)
  76. return True
  77. except:
  78. return update_fx(a,b)
  79. with open('/etc/timezone') as f:
  80. os.environ['TZ'] = f.read().rstrip()
  81. class Xch(object): pass
  82. class Src(object): pass
  83. num_xchgs = 2
  84. xchgs = tuple([Xch() for i in range(num_xchgs)])
  85. sources = OrderedDict([('tc','ticker')])
  86. for g in xchgs:
  87. for k in sources:
  88. setattr(g,k,Src())
  89. setattr(getattr(g,k),'desc',sources[k])
  90. for g in [xchgs[0]]:
  91. g.cur = 'USD'
  92. # g.Desc = 'OKCoin USD'
  93. # g.desc = 'okcoin_usd'
  94. # g.desc_short = 'okc'
  95. # g.tc.url = 'https://www.okcoin.com/api/v1/ticker.do?symbol=btc_usd'
  96. g.Desc = 'Gemini'
  97. g.desc = 'gemini'
  98. g.desc_short = 'gem'
  99. g.tc.url = 'https://api.gemini.com/v1/pubticker/btcusd'
  100. g.poll_secs = 60
  101. g.cur_sign = '$'
  102. g.xcur_sign = '¥'
  103. g.fiat_precision = 2
  104. g.hi_alrm = 999999
  105. g.lo_alrm = 1
  106. g.cc_unit = 'BTC'
  107. for g in [xchgs[1]]:
  108. g.cur = 'CNY'
  109. g.Desc = 'OKCoin CNY'
  110. g.desc = 'okcoin_cny'
  111. g.desc_short = 'okc'
  112. g.tc.url = 'https://www.okcoin.cn/api/v1/ticker.do?symbol=btc_cny'
  113. g.poll_secs = 60
  114. g.cur_sign = '¥'
  115. g.xcur_sign = '$'
  116. g.fiat_precision = 1
  117. g.hi_alrm = 999999
  118. g.lo_alrm = 1
  119. g.cc_unit = 'BTC'
  120. # g.cur = 'USD'
  121. # g.Desc = 'BitFinex'
  122. # g.desc = 'bitfinex'
  123. # g.desc_short = 'bfx'
  124. # g.tc.url = 'https://api.bitfinex.com/v1/pubticker/btcusd'
  125. # Gemini - available symbols: btcusd ethbtc ethusd
  126. # g.cur = 'USD'
  127. # g.Desc = 'Gemini'
  128. # g.desc = 'gemini'
  129. # g.desc_short = 'gem'
  130. # g.tc.url = 'https://api.gemini.com/v1/pubticker/btcusd'
  131. opts_data = {
  132. 'prog_name': sys.argv[0].split('/')[-1],
  133. 'desc': 'Price alarm for Bitcoin exchange',
  134. 'usage': '[opts] [<low price alarm> <high price alarm>]',
  135. #-b, --big-number Print big numbers
  136. 'options': """
  137. -h, --help Print this help message
  138. -a, --alarm-clock-only Disable ticker, use as alarm clock only
  139. -c, --cur-ticker-only Display only current exchange's ticker price
  140. -d, --debug Debug mode. Use saved HTTP data from files
  141. -D, --debug-curl Debug curl
  142. -l, --log= l Log all data to file '{lf}' at levels 'l' (comma-separated: {lls})
  143. -n, --num-digits= n Display 'n' number of big digits
  144. -p, --poll-intervals=i1[,i2] Poll servers every 'i' seconds (default: '{pi}')
  145. -P, --proxy= x Connect via proxy 'x' (see PROXY EXAMPLES below for format)
  146. -r, --repeat-spec Sleep interval/duration program for the alarm
  147. (default: '{r}')
  148. (see REPEAT SPEC FORMAT below)
  149. -R, --resize-window Resize window to optimum dimensions
  150. -t, --testing Testing mode. Don't execute shell commands
  151. -u, --utc Show times in UTC rather than local time
  152. -v, --volume= n Adjust sound volume by percentage 'n' (default: {v})
  153. -V, --test-volume Test the alarm volume and exit
  154. -x, --xchgs= x,y[,…] Display only exchanges 'x,y[,…]' (comma-separated
  155. list of integers, see CONFIGURED EXCHANGES below)
  156. """.format(
  157. v=int(sound_vol),
  158. pi = ','.join([str(g.poll_secs) for g in xchgs]),
  159. r=repeat_spec,
  160. lf=logfile,
  161. lls=', '.join(['%s=%s'%(i,j) for i,j in valid_loglevels.items()])
  162. ),
  163. 'notes': '''
  164. REPEAT SPEC FORMAT:
  165. <interval>:<duration>[,<interval>:<duration>[,…]]
  166. For example, '3s:5m,1m:2h,30m:1d' means:
  167. ring alarm every 3 seconds for 5 minutes,
  168. then every minute for 2 hours,
  169. then every 30 minutes for 1 day
  170. PROXY EXAMPLES:
  171. socks5h://localhost:9050 (for Tor running on localhost)
  172. http://192.168.0.4:8118 (for Privoxy running on host 192.168.0.4)
  173. CONFIGURED EXCHANGES:
  174. {x}
  175. '''.format(
  176. x='\n '.join(['%s - %s'%(n,x.Desc) for n,x in enumerate(xchgs,1)])
  177. )
  178. }
  179. opts,args = Opts.parse_opts(sys.argv,opts_data)[:2]
  180. debug_curl = 'debug_curl' in opts
  181. proxy = opts['proxy'] if 'proxy' in opts else None
  182. # Global var: the currently displayed exchange
  183. if 'alarm_clock_only' in opts:
  184. num_digits = 4
  185. mute_alrms = False
  186. ga = None
  187. xchgs = []
  188. else:
  189. mute_alrms = True
  190. ga = xchgs[0]
  191. fx_pairs = [('usd','cny')]
  192. for a,b in fx_pairs:
  193. msg_r('Getting {}/{} exchange rate...'.format(a.upper(),b.upper()))
  194. if get_fx(a,b):
  195. msg('OK')
  196. else:
  197. die_pause(1,'Unable to get {}/{} exchange rate'.format(a.upper(),b.upper()))
  198. if 'xchgs' in opts:
  199. usr_xchgs = [int(i)-1 for i in opts['xchgs'].split(',')]
  200. xchgs = [xchgs[i] for i in usr_xchgs]
  201. # Initialize some variables for active exchanges
  202. for g in xchgs:
  203. g.retry_interval = 30
  204. g.conn_alrm_timeout = 300
  205. g.tc.bal = 0.0,0.0,0.0
  206. if not hasattr(g,'desc_short'): g.desc_short = g.desc
  207. for k in sources:
  208. s = getattr(g,k)
  209. main_thrd_names = tuple([x.desc+'_ticker' for x in xchgs])
  210. kill_flgs = dict([(k,th.Event()) for k in main_thrd_names + ('alrm','clock','log')])
  211. debug = 'debug' in opts
  212. if debug: msg('Debugging mode. Using saved data from files')
  213. def do_errmsg(s,k='ticker'):
  214. if k == 'ticker':
  215. with dlock:
  216. blank_ticker()
  217. msg_r(CUR_HOME)
  218. msgred_r(s)
  219. time.sleep(5)
  220. def toggle_option(k):
  221. with dlock:
  222. if k in opts: del opts[k]
  223. else: opts[k] = True
  224. def get_thrd_names(): return [i.name for i in th.enumerate()]
  225. def start_alrm(name):
  226. kill_flgs['alrm'].clear()
  227. t = th.Thread(
  228. target = play_sound,
  229. name = name,
  230. kwargs = {
  231. 'fn': sounds[name][0], # (fn,vol)
  232. 'repeat_spec': repeat_spec,
  233. 'remote_host': audio_host,
  234. 'vol': sound_vol * sounds[name][1] / 100,
  235. 'kill_flg': kill_flgs['alrm'],
  236. 'testing': False
  237. }
  238. )
  239. t.daemon = True
  240. t.start()
  241. def start_alrm_maybe(my_thrd_name,kill_list=None):
  242. if mute_alrms: return
  243. # Allow for an empty kill list
  244. klist = kill_list if kill_list != None else alrm_names
  245. with alock: # kill alarm thrds except mine
  246. if any([n in klist and n != my_thrd_name for n in get_thrd_names()]):
  247. kill_flgs['alrm'].set()
  248. if not my_thrd_name: return # if thread name 'None', kill first, then return
  249. if not any([n in alrm_names for n in get_thrd_names()]):
  250. start_alrm(my_thrd_name)
  251. def parse_loglevel_arg(s):
  252. m1 = 'Invalid loglevel argument: %s\n' % s
  253. try: ret = [int(i) for i in s.split(',')]
  254. except:
  255. m2 = 'Loglevels must be comma-separated int values'
  256. return False, m1+m2
  257. if not set(ret) <= set(valid_loglevels):
  258. m2 = 'Valid loglevels: %s' % ','.join([str(i) for i in valid_loglevels])
  259. return False, m1+m2
  260. return ret,'OK'
  261. def set_alrm_vals(s):
  262. ret = []
  263. m1 = 'Invalid alarm argument: %s\n' % s
  264. for e in s.split(':'):
  265. try: ret.append([Decimal(i) for i in e.split(',')])
  266. except:
  267. m2 = 'Alarms must be comma-separated decimal values'
  268. return False, m1+m2
  269. if len(ret[-1]) != 2:
  270. m2 = 'Each element of alarm list must have 2 items (lo_alrm,hi_alrm)'
  271. return False, m1+m2
  272. if len(ret) != len(xchgs):
  273. m2 = 'Alarm list must be %s colon-separated comma-separated lists' % len(xchgs)
  274. return False, m1+m2
  275. for g,a in zip(xchgs,ret):
  276. lo,hi = a
  277. if lo > hi:
  278. m2 = 'Low alarm (%s) is greater than high alarm (%s)' % (lo,hi)
  279. return False, m1+m2
  280. setattr(g,'lo_alrm',lo)
  281. setattr(g,'hi_alrm',hi)
  282. return ret,'OK'
  283. def set_poll_intervals(s,xchg=None):
  284. ret = []
  285. m1 = 'Invalid poll interval argument: %s\n' % s
  286. m2 = 'Poll intervals must be comma-separated integer values'
  287. m3 = 'Poll interval must be integer value'
  288. for e in (s.split(','),[s])[bool(xchg)]:
  289. try: ret.append(float(e))
  290. except:
  291. return False, m1+(m2,m3)[bool(xchg)]
  292. if not xchg and len(ret) != len(xchgs):
  293. m2 = 'Poll interval list have %s items' % len(xchgs)
  294. return False, m1+m2
  295. for g,p in zip((xchgs,[xchg])[bool(xchg)],ret):
  296. setattr(g,'poll_secs',float(p))
  297. return ret,'OK'
  298. def set_xch_param(source,param,s,desc):
  299. ret = []
  300. m1 = 'Invalid %s argument: %s\n' % (desc,s)
  301. for e in s.split(':'):
  302. try: ret.append(float(e))
  303. except:
  304. m2 = '%s arg must be colon-separated float values' % desc.capitalize()
  305. return False, m1+m2
  306. if len(ret) != len(xchgs):
  307. m2 = '%s list must have %s colon-separated items' % (
  308. desc.capitalize(),len(xchgs))
  309. return False, m1+m2
  310. for g,p in zip(xchgs,ret):
  311. a = getattr(g,source)
  312. setattr(a,param,float(p))
  313. return ret,'OK'
  314. if 'log' in opts:
  315. loglevels,errmsg = parse_loglevel_arg(opts['log'])
  316. if not loglevels: die_pause(1,errmsg)
  317. msg('Logging at level{} {}'.format(
  318. ('s','')[len(loglevels)==1],
  319. ' '.join([valid_loglevels[i].upper() for i in loglevels])))
  320. else:
  321. loglevels = []
  322. if 'repeat_spec' in opts:
  323. repeat_spec = opts['repeat_spec']
  324. msg("Using program '{}' for alarm".format(repeat_spec))
  325. if 'num_digits' in opts:
  326. n = opts['num_digits']
  327. if len(n) != 1 or n not in '56789':
  328. die_pause(1,"'%s': invalid value for --num-digits option" % n)
  329. num_digits = int(n)
  330. if 'volume' in opts:
  331. sound_vol = int(opts['volume'])
  332. for k in sounds:
  333. sounds[k][1] = float(sounds[k][1] * sound_vol / 100)
  334. msg('Adjusting sound volume by {}%'.format(sound_vol))
  335. if 'test_volume' in opts:
  336. for k in sounds:
  337. msg("Playing '{}' ({})".format(k,sounds[k][0]))
  338. play_sound(
  339. fn=sounds[k][0],
  340. vol=sound_vol * sounds[k][1] / 100,
  341. testing='testing' in opts
  342. )
  343. sys.exit()
  344. if len(args) > 1: Opts.usage(opts_data)
  345. if len(args) == 1:
  346. ret,errmsg = set_alrm_vals(args[0])
  347. if not ret: die_pause(1,'Error: ' + errmsg)
  348. msg('Setting alarms to %s' % ', '.join(['{} {}'.format(i,j) for i,j in ret]))
  349. if 'poll_intervals' in opts:
  350. ret,errmsg = set_poll_intervals(opts['poll_intervals'])
  351. if not ret: die_pause(1,errmsg)
  352. msg('Polling every %s seconds' % ret)
  353. tmux = 'TMUX' in os.environ
  354. if tmux:
  355. subprocess.check_output(['tmux','set','set-titles','on'])
  356. subprocess.check_output(['tmux','set','status','off'])
  357. # dcmd = "date -R%s | cut -d' ' -f2-5" % ('','u')['utc' in opts]
  358. # subprocess.check_output(['tmux','set','status-right','#(%s)' % dcmd])
  359. infoW = 15
  360. bigDigitsW = big_digits['w']*num_digits + big_digits['pw']*1
  361. lPaneW = bigDigitsW+infoW+1
  362. topPaneH,rPaneW = 6,23
  363. def CUR_UP(n): return '\033[%sA' % n
  364. def CUR_DOWN(n): return '\033[%sB' % n
  365. def CUR_RIGHT(n): return '\033[%sC' % n
  366. def CUR_LEFT(n): return '\033[%sD' % n
  367. def WIN_TITLE(s): return '\033]0;%s\033\\' % s
  368. def WIN_RESIZE(w,h): return '\033[8;%s;%st' % (h,w)
  369. def WIN_CORNER(): return '\033[3;200;0t'
  370. CUR_UP1 = '\033[A'
  371. CUR_DN1 = '\033[B'
  372. CUR_SHOW = '\033[?25h'
  373. CUR_HIDE = '\033[?25l'
  374. BLINK = '\033[5m'
  375. RESET = '\033[0m'
  376. CUR_HOME = '\033[H'
  377. ERASE_ALL = '\033[0J'
  378. def draw_rectangle(s,l,h):
  379. msg_r(s + '\n'.join([l] * h))
  380. def blank_ticker():
  381. draw_rectangle(CUR_HOME,' ' * lPaneW,topPaneH)
  382. def blank_big_digits():
  383. draw_rectangle(CUR_HOME,' ' * (bigDigitsW+1),topPaneH)
  384. def park_cursor():
  385. msg_r('\r' + CUR_RIGHT(lPaneW-1))
  386. def colorize_bal(g,n):
  387. d = g.tc
  388. fs = '{:.%sf}' % g.fiat_precision
  389. return (nocolor,green,red)[
  390. (bool(d.save_bal[n]) and
  391. (d.bal[n]!=d.save_bal[n]) + (d.bal[n]<d.save_bal[n]))
  392. ](fs.format(d.bal[n]))
  393. def display_ac_info():
  394. ac_fmt = green('--:--') if alrm_clock == 'off' else yelbg(alrm_clock)
  395. info_lines = (
  396. '{}'.format(ac_fmt),
  397. 'snd vol: {}%'.format(int(sound_vol)),
  398. '{}'.format((yellow('unmuted'),'muted')[mute_alrms]),
  399. '{}'.format(blue(audio_host[:infoW] or 'localhost')),
  400. '',
  401. "'?' for help"
  402. )
  403. r = CUR_RIGHT(bigDigitsW+1)
  404. msg_r(CUR_HOME+r+('\n'+r).join(info_lines))
  405. park_cursor()
  406. ts = 'Alarm Clock: {}{}'.format(alrm_clock.upper(),('',' (m)')[mute_alrms])
  407. if tmux:
  408. subprocess.check_output(['tmux','set','set-titles-string',ts])
  409. else:
  410. msg_r(WIN_TITLE(ts))
  411. def display_ticker(g,called_by_clock=False):
  412. if not g: return
  413. d = g.tc
  414. log(3,'display_ticker(): ' + repr(d.__dict__))
  415. if not hasattr(d,'timestamp'): return # DEBUG
  416. avg = sum((d.bal[i] or d.save_bal[i]) for i in range(3)) / 3
  417. alrm,lb,hb,rst = (
  418. (None,'','',''),
  419. ('lo',BLINK,'',RESET),
  420. ('hi','',BLINK,RESET)
  421. )[(avg<g.lo_alrm)+(avg>g.hi_alrm)*2]
  422. start_alrm_maybe(alrm,['lo','hi'])
  423. if (g is not ga) and not called_by_clock: return
  424. lfmt = '{n:.{p}f}'.format(p=g.fiat_precision,n=d.bal[2])
  425. msg_r(CUR_HOME+lb+hb+display_big_digits(lfmt,pre=' '+rst))
  426. if (g is not ga) and called_by_clock:
  427. park_cursor()
  428. return
  429. hms = get_hms(d.timestamp,utc='utc' in opts)
  430. xcur = '{:.2f}'.format(d.bal[2]/usdcny if g.cur == 'CNY' else d.bal[2]*usdcny)
  431. ac_fmt = green('--:--') if alrm_clock == 'off' else yelbg(alrm_clock)
  432. info_lines = (
  433. '{} {}'.format(hms,('%ss'%int(g.poll_secs))),
  434. '{} bid/ask'.format(cyan(g.desc_short)),
  435. '{} {}'.format(colorize_bal(g,0), colorize_bal(g,1)),
  436. '{g.xcur_sign}{x} {h}'.format(g=g,x=xcur,
  437. h=('',blue(audio_host[:infoW-len(xcur)-2]))[bool(audio_host)]),
  438. '{} {} {}'.format(yellow(('♫','-')[mute_alrms]),
  439. lb+yellow(str(g.lo_alrm))+rst,
  440. hb+yellow(str(g.hi_alrm))+rst),
  441. '{} vol {}%'.format(ac_fmt,int(sound_vol))
  442. )
  443. r = CUR_RIGHT(bigDigitsW+1)
  444. msg_r(CUR_HOME+r+('\n'+r).join(info_lines))
  445. park_cursor()
  446. ccs = ('฿','Ł')[g.cc_unit=='LTC']
  447. if len(xchgs) == 2:
  448. x1,x2 = xchgs
  449. ts = '{}{:.{}f} / {}{:.{}f}'.format(
  450. x1.cur_sign,
  451. x1.tc.bal[2],
  452. x1.fiat_precision,
  453. x2.cur_sign,
  454. x2.tc.bal[2],
  455. x2.fiat_precision,
  456. )
  457. else:
  458. ts = '{}: {}{:.{}f} ({})'.format(
  459. ccs,
  460. g.cur_sign,
  461. d.bal[2],
  462. g.fiat_precision,
  463. g.Desc
  464. )
  465. if tmux:
  466. # subprocess.call(['tmux','rename-session',g.Desc], stderr=subprocess.PIPE)
  467. subprocess.check_output(['tmux','set','set-titles-string',ts])
  468. else:
  469. msg_r(WIN_TITLE(ts))
  470. def log(*args): # [lvl,g,src,data] OR [lvl,data]
  471. if 'log' in opts and args[0] in loglevels + [0]:
  472. if len(args) == 2:
  473. s = '{}: {}\n'.format(get_day_hms(),args[1])
  474. elif len(args) == 4:
  475. s = '{}: {} {} - {}\n'.format(
  476. get_day_hms(),
  477. args[1].desc_short.upper(),
  478. args[2].upper(),
  479. args[3]
  480. )
  481. with llock:
  482. fd = os.open(logfile,os.O_RDWR|os.O_APPEND|os.O_CREAT|os.O_SYNC)
  483. os.write(fd,s)
  484. os.close(fd)
  485. def get_market_data(g,d,connfail_msg='full'):
  486. # , post_data={}
  487. tcd = 'TRADING_CONSOLE_DEBUG_CONNFAIL'
  488. debug_connfail = tcd in os.environ and os.environ[tcd]
  489. null = None # hack for eval'ing Huobi trades data
  490. if debug:
  491. fn = 'debug_market_data/%s_ticker.json' % g.desc
  492. try:
  493. with open(fn) as f: text = f.read()
  494. log(3,'get_market_data(): {} {}'.format(g.desc,text))
  495. return eval(text)
  496. except:
  497. die(2,'Unable to open datafile %s' % fn)
  498. fail_count,conn_begin_time = 0,time.time()
  499. if debug_connfail:
  500. retry_interval,conn_alrm_timeout = 10,0
  501. else:
  502. retry_interval,conn_alrm_timeout = g.retry_interval,g.conn_alrm_timeout
  503. while True:
  504. try:
  505. text = get_url(d.url,proxy=proxy,debug=debug_curl)
  506. log(2,g,d.desc,text)
  507. return eval(text)
  508. except KeyboardInterrupt:
  509. die(1,'\nUser interrupt (get_market_data)\n')
  510. except EOFError:
  511. die(1,'\nEnd of file\n')
  512. except Exception as e:
  513. fail_count += 1
  514. if connfail_msg:
  515. with dlock:
  516. if g is ga:
  517. m = {
  518. 'short':'Connect fail ({})'.format(fail_count),
  519. 'full': 'Connect fail. Retry in {} seconds ({})'.format(
  520. retry_interval,fail_count)
  521. }
  522. dn = CUR_DOWN(topPaneH-1)
  523. blank_big_digits()
  524. msg_r(CUR_HOME+dn+m[connfail_msg]+' \b')
  525. k = '%s_%s' % (g.desc,d.desc)
  526. if time.time() - conn_begin_time > conn_alrm_timeout:
  527. if fail_count == 1:
  528. log(1,'Connect error (%s)' % k)
  529. if d.desc == 'ticker':
  530. with dlock: d.bal = d.bal[:2] + (0.0,) # can't assign to tuple, so this
  531. start_alrm_maybe('conn_err')
  532. # Sleep until user interrupt
  533. if kill_flgs[k].wait(retry_interval):
  534. kill_flgs[k].clear()
  535. return False
  536. def killwait(g,d):
  537. log(3,g,d.desc,'Begin wait')
  538. k = '%s_%s' % (g.desc,d.desc)
  539. if kill_flgs[k].wait(g.poll_secs):
  540. kill_flgs[k].clear()
  541. if quit: return True
  542. log(3,g,d.desc,'End wait')
  543. return False
  544. def log_loop():
  545. while True:
  546. for g in xchgs:
  547. with dlock:
  548. lstr = '{} last: {}{}'.format(g.desc_short.upper(),g.cur_sign,g.tc.bal[2])
  549. log(1,lstr)
  550. if kill_flgs['log'].wait(30):
  551. kill_flgs['log'].clear()
  552. if quit: return True
  553. def ticker_loop(g):
  554. d = g.tc
  555. while True:
  556. ret = get_market_data(g,d)
  557. log(3,'get_market_data() returned: {}'.format(repr(ret)))
  558. if not ret: # kill flag was set
  559. if quit: break
  560. continue
  561. errmsg = 'ticker_loop: HTTP returned bad data'
  562. with dlock:
  563. millisec = False
  564. if g.desc == 'bitfinex':
  565. a = ret
  566. bal = 'bid','ask','last_price'
  567. ts = ret['timestamp']
  568. elif g.desc == 'gemini':
  569. a = ret
  570. bal = 'bid','ask','last'
  571. try:
  572. ts = ret['volume']['timestamp']
  573. except:
  574. log(1,errmsg); continue
  575. millisec = True
  576. elif g.desc in ('okcoin_usd','okcoin_cny','huobi'):
  577. try:
  578. a = ret['ticker']
  579. except:
  580. log(1,errmsg); continue
  581. bal = 'buy','sell','last'
  582. ts = ret[('time','date')[g.desc[:6]=='okcoin']]
  583. else:
  584. die(1,"Can't handle symbol '{}'".format(g.desc))
  585. # okcoin.cn CNY: {"date":"1477932232","ticker":{"buy":"4844.13","high":"4873.36","last":"4844.16","low":"4660.0","sell":"4844.14","vol":"2992115.73393084"}}
  586. # gemini: {"bid":"1025.64","ask":"1026.93","volume":{"BTC":"1710.8752181914","USD":"1734356.065049020336","timestamp":1486377600000},"last":"1026.93"}
  587. # okcoin.com USD {"date":"1486581152","ticker":{"buy":"1057.59","high":"1070.0","last":"1059.63","low":"1002.51","sell":"1058.34","vol":"4118.856"}}
  588. try:
  589. d.timestamp = int(float(ts))
  590. except:
  591. log(1,errmsg); continue
  592. if millisec: d.timestamp /= 1000
  593. d.save_bal = d.bal
  594. try:
  595. d.bal = tuple([float(a[k]) for k in bal])
  596. except:
  597. log(1,errmsg); continue
  598. log(3,'{}: timestamp {}, bal {}'.format(g.desc,d.timestamp,d.bal))
  599. if killwait(g,d): break
  600. def clock_loop():
  601. ac_active = False
  602. ac_prefix=(' ','')['alarm_clock_only' in opts]
  603. def do_ticker(x):
  604. with dlock:
  605. blank_big_digits()
  606. display_ticker(x,called_by_clock=True)
  607. if kill_flgs['clock'].wait(2): sys.exit()
  608. while True:
  609. if 'alarm_clock_only' in opts:
  610. with dlock:
  611. blank_ticker()
  612. display_ac_info()
  613. elif not ac_active:
  614. if 'cur_ticker_only' in opts:
  615. do_ticker(ga)
  616. else:
  617. for x in xchgs: do_ticker(x)
  618. if alrm_clock == 'off' and ac_active:
  619. ac_active = False
  620. if alrm_clock != 'off' or 'alarm_clock_only' in opts:
  621. now = get_hms(no_secs=True)
  622. if now == alrm_clock:
  623. ac_active = True
  624. start_alrm_maybe('alrm_clock',['alrm_clock'])
  625. if not any([(n in alrm_names and n != 'alrm_clock') for n in get_thrd_names()]):
  626. bl,rs = (('',''),(BLINK,RESET))[ac_active]
  627. with dlock:
  628. blank_big_digits()
  629. msg_r(CUR_HOME+bl+display_big_digits(now,pre=ac_prefix)+rs)
  630. park_cursor()
  631. if kill_flgs['clock'].wait(2): return
  632. def input_loop():
  633. global ga,sound_vol,alrm_clock,quit,mute_alrms
  634. from mmgen.node_tools.Term import get_keypress
  635. if 'alarm_clock_only' not in opts:
  636. msg("Type '?' for help after the ticker starts")
  637. ch = get_keypress("Hit 'q' to quit, any other key to continue: ")
  638. if ch == 'q': die(0,'')
  639. if 'resize_window' in opts:
  640. if tmux:
  641. msg('\nWARNING: Window resizing doesn\'t work in tmux')
  642. else:
  643. msg_r(WIN_RESIZE(lPaneW,topPaneH))
  644. msg_r(WIN_CORNER())
  645. time.sleep(0.1)
  646. from mmgen.term import set_terminal_vars
  647. set_terminal_vars()
  648. from mmgen.term import get_terminal_size
  649. twid = get_terminal_size()[0]
  650. if twid < lPaneW:
  651. die_pause(1,'\nTerminal window must be at least %s characters wide' % lPaneW)
  652. msg_r(CUR_HIDE)
  653. # raw_input('\nPress any key to exit'); sys.exit() # DEBUG
  654. blank_ticker()
  655. for k in xchgs:
  656. th.Thread(target=globals()['ticker_loop'],args=[k],name=k.desc+'_ticker').start()
  657. th.Thread(target=clock_loop,name='clock').start()
  658. th.Thread(target=log_loop,name='log').start()
  659. time.sleep(1) # Hack for get_keypress()
  660. def redraw():
  661. blank_ticker()
  662. display_ticker(ga)
  663. help_texts = {
  664. 'tc': '''
  665. a - set alarm clock l - set low alarm
  666. A - set remote audio host m - mute alarms
  667. e - update USD/CNY rate M - write message to log
  668. G - set log levels p - set poll interval
  669. h - set high alarm t - reload ticker
  670. k - kill alarm v - set sound volume
  671. L - log current state x - cycle thru exchanges
  672. c - toggle display of current ticker only
  673. -/+ - adjust sound volume
  674. ''',
  675. 'ac': '''
  676. a - set alarm clock m - mute alarms
  677. A - set remote audio host k - kill alarm
  678. M - write message to log v - set sound volume
  679. -/+ - adjust sound volume
  680. '''
  681. }
  682. help_text = ['{:^{w}}'.format('KEYSTROKE COMMANDS',w=lPaneW)]
  683. help_text += help_texts[('tc','ac')['alarm_clock_only' in opts]].strip().split('\n')
  684. help_text_prompt = 'ESC or ENTER to exit, ↑ and ↓ to scroll'
  685. def do_help():
  686. scrollpos = 0
  687. def fmt_help_txt(pos):
  688. return '\n'.join(help_text[pos:pos+5])+'\n'+help_text_prompt+' '
  689. with dlock:
  690. while True:
  691. blank_ticker()
  692. ch = get_keypress(CUR_HOME+fmt_help_txt(scrollpos),esc_sequences=True)
  693. if ch == CUR_DN1 and scrollpos < len(help_text) - topPaneH + 1:
  694. scrollpos += 1
  695. elif ch == CUR_UP1 and scrollpos != 0:
  696. scrollpos -= 1
  697. elif ch in '\n\033': break
  698. blank_ticker()
  699. display_ticker(ga)
  700. def ks_msg_nolock(s,delay):
  701. blank_ticker()
  702. msg_r(CUR_HOME+s)
  703. time.sleep(delay)
  704. blank_ticker()
  705. display_ticker(ga)
  706. def ks_msg(s,delay):
  707. with dlock:
  708. ks_msg_nolock(s,delay)
  709. def set_value(v,prompt,vtype=int,poll=False,source=None,
  710. all_srcs=False,global_var=False,allow_empty=False):
  711. def type_chk(vtype,val):
  712. try:
  713. vtype(val); return True
  714. except:
  715. return False
  716. errmsg = ''
  717. with dlock:
  718. while True:
  719. blank_ticker()
  720. em = errmsg+'\n' if errmsg else ''
  721. termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_termattrs)
  722. # time.sleep(0.1)
  723. s = raw_input(CUR_HOME+CUR_SHOW+em+prompt)
  724. msg_r(CUR_HIDE)
  725. if not s:
  726. if allow_empty:
  727. ks_msg_nolock('Value unset',0.5)
  728. else:
  729. blank_ticker()
  730. display_ticker(ga)
  731. return False
  732. if v == 'alrm_clock':
  733. if s == 'off':
  734. globals()[v] = s
  735. if v in get_thrd_names():
  736. kill_flgs['alrm'].set()
  737. return s
  738. a = s.split(':')
  739. ok = True
  740. if len(a) != 2: ok = False
  741. if ok:
  742. try: h,m = int(a[0]),int(a[1])
  743. except: ok = False
  744. if ok:
  745. if not (24 >= h >= 0): ok = False
  746. if not (60 >= m >= 0): ok = False
  747. if ok:
  748. globals()[v] = '{:02d}:{:02d}'.format(h,m)
  749. break
  750. else:
  751. errmsg = 'Incorrect alarm clock value'
  752. continue
  753. elif v == 'loglevels':
  754. ret,err = parse_loglevel_arg(s)
  755. if ret:
  756. globals()[v] = ret; break
  757. else:
  758. errmsg = err; continue
  759. elif v == 'poll_secs':
  760. ret,errmsg = set_poll_intervals(s,xchg=ga)
  761. if ret: break
  762. else: continue
  763. elif all_srcs:
  764. vals = s.split(',')
  765. if len(vals) != len(sources):
  766. errmsg = 'Input must be %s comma-separated %s values'%(
  767. len(sources),vtype.__name__)
  768. continue
  769. for k,val in zip(sources,vals):
  770. ret = type_chk(vtype,val)
  771. if ret: setattr(getattr(ga,k),v,vtype(val))
  772. else: break
  773. if ret: break
  774. elif source:
  775. if type_chk(vtype,s):
  776. setattr(getattr(ga,source),v,vtype(s)); break
  777. else:
  778. if type_chk(vtype,s):
  779. if v == 'hi_alrm' and vtype(s) < ga.lo_alrm:
  780. errmsg = 'High alarm must be >= low alarm'
  781. continue
  782. if v == 'lo_alrm' and vtype(s) > ga.hi_alrm:
  783. errmsg = 'Low alarm must be <= high alarm'
  784. continue
  785. if global_var:
  786. globals()[v] = vtype(s); break
  787. else:
  788. setattr(ga,v,vtype(s)); break
  789. errmsg = 'Value%s must be of type %s' % (
  790. ('','s')[all_srcs],vtype.__name__)
  791. redraw()
  792. if poll:
  793. kill_flgs[ga.desc+'_ticker'].set()
  794. return True
  795. while True:
  796. ch = get_keypress()
  797. if ch == 'q':
  798. quit = True
  799. for k in kill_flgs: kill_flgs[k].set()
  800. for i in th.enumerate():
  801. if i.name in main_thrd_names + alrm_names + ('clock',): i.join()
  802. msg('')
  803. break
  804. elif ch == 'a':
  805. m1 = 'Current alarm clock: %s' % alrm_clock
  806. m2 = "Enter alarm clock time or 'off': "
  807. if set_value('alrm_clock',m1+'\n'+m2):
  808. ks_msg("Alarm clock set to %s" % alrm_clock,1.5)
  809. elif ch == 'A':
  810. set_value('audio_host','Enter remote audio host: ',
  811. vtype=str,global_var=True,allow_empty=True)
  812. elif ch in 'H?': do_help()
  813. elif ch == 'k':
  814. if 'alrm_clock' in get_thrd_names(): alrm_clock = 'off'
  815. a = any([i in alrm_names for i in get_thrd_names()])
  816. log(3,'\n alrm_names: {}\n get_thrd_names(): {}'.format(
  817. alrm_names,get_thrd_names()))
  818. if a: kill_flgs['alrm'].set()
  819. ks_msg(('No active alarms','Killing alarm')[a],0.5)
  820. elif ch == 'M':
  821. with dlock:
  822. blank_ticker()
  823. termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_termattrs)
  824. s = raw_input(CUR_HOME+'Enter log message: ')
  825. log(0,'USR_MSG: '+s)
  826. display_ticker(ga)
  827. elif ch == 'm':
  828. mute_alrms = not mute_alrms
  829. if mute_alrms: kill_flgs['alrm'].set()
  830. ks_msg(('Unm','M')[mute_alrms] + 'uting alarms',1)
  831. with dlock:
  832. blank_ticker()
  833. display_ticker(ga)
  834. elif ch == 'v': set_value('sound_vol','Enter sound volume: ',global_var=True)
  835. elif ch in '-+':
  836. with dlock:
  837. sound_vol += (1,-1)[ch=='-']
  838. blank_ticker(); display_ticker(ga)
  839. elif not 'alarm_clock_only' in opts:
  840. if ch == 'c':
  841. toggle_option('cur_ticker_only')
  842. ks_msg('Displaying %s' %
  843. ('all tickers','current ticker only')['cur_ticker_only' in opts],0.5)
  844. elif ch == 'G': set_value('loglevels','Enter log levels: ',global_var=True)
  845. elif ch == 'h': set_value('hi_alrm','Enter high alarm: ',Decimal)
  846. elif ch == 'l': set_value('lo_alrm','Enter low alarm: ',Decimal)
  847. elif ch == 'L':
  848. ks_msg('Logging current ticker at %s' % get_hms(),1.5)
  849. with dlock:
  850. log(0,'{} CUR_STATE\n BID/ASK/LAST {}\n'.format(ga.desc.upper(),ga.tc.bal))
  851. elif ch == 'p': set_value('poll_secs',
  852. 'Enter poll interval: ',float,poll=True)
  853. elif ch == 't':
  854. key = '%s_ticker' % (ga.desc)
  855. if key in kill_flgs:
  856. kill_flgs[key].set()
  857. ks_msg('Reloading ticker data',1)
  858. else:
  859. ks_msg('%s: no such key' % key,1)
  860. elif ch == 'x':
  861. for x in range(len(xchgs)):
  862. if ga is xchgs[x]: break
  863. new_g = xchgs[x+1 if x+1 < len(xchgs) else 0]
  864. ks_msg('Switching to exchange %s' % new_g.Desc,0.5)
  865. with dlock:
  866. ga = new_g
  867. redraw()
  868. elif ch == 'e':
  869. for a,b in fx_pairs:
  870. ks_msg('Updating {}/{} rate'.format(a.upper(),b.upper()),0.5)
  871. ret = update_fx(a,b)
  872. m,d = (('Unable to update',2),('Updated',0.7))[bool(ret)]
  873. ks_msg('{} {}/{} rate'.format(m,a.upper(),b.upper()),d)
  874. def launch(name,*args,**kwargs):
  875. def at_exit():
  876. # msg_r(CUR_HOME+ERASE_ALL) # DEBUG
  877. msg_r(CUR_SHOW)
  878. termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_termattrs)
  879. for k in kill_flgs: kill_flgs[k].set()
  880. for i in th.enumerate():
  881. if i.name in main_thrd_names + alrm_names + ('clock',): i.join()
  882. if 'log' in opts: log(0,'Exiting')
  883. import atexit
  884. atexit.register(at_exit)
  885. log(0,'Starting log')
  886. try:
  887. globals()[name](*args,**kwargs)
  888. except KeyboardInterrupt:
  889. quit = True
  890. for k in kill_flgs: kill_flgs[k].set()
  891. sys.stderr.write('\nUser interrupt\n')
  892. import termios
  893. old_termattrs = termios.tcgetattr(sys.stdin.fileno())
  894. launch('input_loop')