btc-ticker 28 KB

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