-
Notifications
You must be signed in to change notification settings - Fork 53
/
goxtool.py
executable file
·1704 lines (1467 loc) · 63 KB
/
goxtool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2
"""
Tool to display live MtGox market info and
framework for experimenting with trading bots
"""
# Copyright (c) 2013 Bernd Kreuss <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
# pylint: disable=C0301,C0302,R0902,R0903,R0912,R0913,R0914,R0915,R0922,W0703
import argparse
import curses
import curses.panel
import curses.textpad
import goxapi
import logging
import locale
import math
import os
import sys
import time
import traceback
import threading
sys_out = sys.stdout #pylint: disable=C0103
#
#
# curses user interface
#
HEIGHT_STATUS = 2
HEIGHT_CON = 7
WIDTH_ORDERBOOK = 45
COLORS = [["con_text", curses.COLOR_BLUE, curses.COLOR_CYAN]
,["con_text_buy", curses.COLOR_BLUE, curses.COLOR_GREEN]
,["con_text_sell", curses.COLOR_BLUE, curses.COLOR_RED]
,["status_text", curses.COLOR_BLUE, curses.COLOR_CYAN]
,["book_text", curses.COLOR_BLACK, curses.COLOR_CYAN]
,["book_bid", curses.COLOR_BLACK, curses.COLOR_GREEN]
,["book_ask", curses.COLOR_BLACK, curses.COLOR_RED]
,["book_own", curses.COLOR_BLACK, curses.COLOR_YELLOW]
,["book_vol", curses.COLOR_BLACK, curses.COLOR_CYAN]
,["chart_text", curses.COLOR_BLACK, curses.COLOR_WHITE]
,["chart_up", curses.COLOR_BLACK, curses.COLOR_GREEN]
,["chart_down", curses.COLOR_BLACK, curses.COLOR_RED]
,["order_pending", curses.COLOR_BLACK, curses.COLOR_RED]
,["dialog_text", curses.COLOR_BLUE, curses.COLOR_CYAN]
,["dialog_sel", curses.COLOR_CYAN, curses.COLOR_BLUE]
,["dialog_sel_text", curses.COLOR_BLUE, curses.COLOR_YELLOW]
,["dialog_sel_sel", curses.COLOR_YELLOW, curses.COLOR_BLUE]
,["dialog_bid_text", curses.COLOR_GREEN, curses.COLOR_BLACK]
,["dialog_ask_text", curses.COLOR_RED, curses.COLOR_WHITE]
]
INI_DEFAULTS = [["goxtool", "set_xterm_title", "True"]
,["goxtool", "dont_truncate_logfile", "False"]
,["goxtool", "show_orderbook_stats", "True"]
,["goxtool", "highlight_changes", "True"]
,["goxtool", "orderbook_group", "0"]
,["goxtool", "orderbook_sum_total", "False"]
,["goxtool", "display_right", "history_chart"]
,["goxtool", "depth_chart_group", "1"]
,["goxtool", "depth_chart_sum_total", "True"]
,["goxtool", "show_ticker", "True"]
,["goxtool", "show_depth", "True"]
,["goxtool", "show_trade", "True"]
,["goxtool", "show_trade_own", "True"]
]
COLOR_PAIR = {}
def init_colors():
"""initialize curses color pairs and give them names. The color pair
can then later quickly be retrieved from the COLOR_PAIR[] dict"""
index = 1
for (name, back, fore) in COLORS:
if curses.has_colors():
curses.init_pair(index, fore, back)
COLOR_PAIR[name] = curses.color_pair(index)
else:
COLOR_PAIR[name] = 0
index += 1
def dump_all_stacks():
"""dump a stack trace for all running threads for debugging purpose"""
def get_name(thread_id):
"""return the human readable name that was assigned to a thread"""
for thread in threading.enumerate():
if thread.ident == thread_id:
return thread.name
ret = "\n# Full stack trace of all running threads:\n"
#pylint: disable=W0212
for thread_id, stack in sys._current_frames().items():
ret += "\n# %s (%s)\n" % (get_name(thread_id), thread_id)
for filename, lineno, name, line in traceback.extract_stack(stack):
ret += 'File: "%s", line %d, in %s\n' % (filename, lineno, name)
if line:
ret += " %s\n" % (line.strip())
return ret
def try_get_lock_or_break_open():
"""this is an ugly hack to workaround possible deadlock problems.
It is used during shutdown to make sure we can properly exit even when
some slot is stuck (due to a programming error) and won't release the lock.
If we can't acquire it within 2 seconds we just break it open forcefully."""
#pylint: disable=W0212
time_end = time.time() + 2
while time.time() < time_end:
if goxapi.Signal._lock.acquire(False):
return
time.sleep(0.001)
# something keeps holding the lock, apparently some slot is stuck
# in an infinite loop. In order to be able to shut down anyways
# we just throw away that lock and replace it with a new one
lock = threading.RLock()
lock.acquire()
goxapi.Signal._lock = lock
print "### could not acquire signal lock, frozen slot somewhere?"
print "### please see the stacktrace log to determine the cause."
class Win:
"""represents a curses window"""
# pylint: disable=R0902
def __init__(self, stdscr):
"""create and initialize the window. This will also subsequently
call the paint() method."""
self.stdscr = stdscr
self.posx = 0
self.posy = 0
self.width = 10
self.height = 10
self.termwidth = 10
self.termheight = 10
self.win = None
self.panel = None
self.__create_win()
def __del__(self):
del self.panel
del self.win
curses.panel.update_panels()
curses.doupdate()
def calc_size(self):
"""override this method to change posx, posy, width, height.
It will be called before window creation and on resize."""
pass
def do_paint(self):
"""call this if you want the window to repaint itself"""
curses.curs_set(0)
if self.win:
self.paint()
self.done_paint()
# method could be a function - pylint: disable=R0201
def done_paint(self):
"""update the sreen after paint operations, this will invoke all
necessary stuff to refresh all (possibly overlapping) windows in
the right order and then push it to the screen"""
curses.panel.update_panels()
curses.doupdate()
def paint(self):
"""paint the window. Override this with your own implementation.
This method must paint the entire window contents from scratch.
It is automatically called after the window has been initially
created and also after every resize. Call it explicitly when
your data has changed and must be displayed"""
pass
def resize(self):
"""You must call this method from your main loop when the
terminal has been resized. It will subsequently make it
recalculate its own new size and then call its paint() method"""
del self.win
self.__create_win()
def addstr(self, *args):
"""drop-in replacement for addstr that will never raie exceptions
and that will cut off at end of line instead of wrapping"""
if len(args) > 0:
line, col = self.win.getyx()
string = args[0]
attr = 0
if len(args) > 1:
attr = args[1]
if len(args) > 2:
line, col, string = args[:3]
attr = 0
if len(args) > 3:
attr = args[3]
if line >= self.height:
return
space_left = self.width - col - 1 #always omit last column, avoids problems.
if space_left <= 0:
return
self.win.addstr(line, col, string[:space_left], attr)
def addch(self, posy, posx, character, color_pair):
"""place a character but don't throw error in lower right corner"""
if posy < 0 or posy > self.height - 1:
return
if posx < 0 or posx > self.width - 1:
return
if posx == self.width - 1 and posy == self.height - 1:
return
self.win.addch(posy, posx, character, color_pair)
def __create_win(self):
"""create the window. This will also be called on every resize,
windows won't be moved, they will be deleted and recreated."""
self.__calc_size()
try:
self.win = curses.newwin(self.height, self.width, self.posy, self.posx)
self.panel = curses.panel.new_panel(self.win)
self.win.scrollok(True)
self.win.keypad(1)
self.do_paint()
except Exception:
self.win = None
self.panel = None
def __calc_size(self):
"""calculate the default values for positionand size. By default
this will result in a window covering the entire terminal.
Implement the calc_size() method (which will be called afterwards)
to change (some of) these values according to your needs."""
maxyx = self.stdscr.getmaxyx()
self.termwidth = maxyx[1]
self.termheight = maxyx[0]
self.posx = 0
self.posy = 0
self.width = self.termwidth
self.height = self.termheight
self.calc_size()
class WinConsole(Win):
"""The console window at the bottom"""
def __init__(self, stdscr, gox):
"""create the console window and connect it to the Gox debug
callback function"""
self.gox = gox
gox.signal_debug.connect(self.slot_debug)
Win.__init__(self, stdscr)
def paint(self):
"""just empty the window after resize (I am lazy)"""
self.win.bkgd(" ", COLOR_PAIR["con_text"])
def resize(self):
"""resize and print a log message. Old messages will have been
lost after resize because of my dumb paint() implementation, so
at least print a message indicating that fact into the
otherwise now empty console window"""
Win.resize(self)
self.write("### console has been resized")
def calc_size(self):
"""put it at the bottom of the screen"""
self.height = HEIGHT_CON
self.posy = self.termheight - self.height
def slot_debug(self, dummy_gox, (txt)):
"""this slot will be connected to all debug signals."""
self.write(txt)
def write(self, txt):
"""write a line of text, scroll if needed"""
if not self.win:
return
# This code would break if the format of
# the log messages would ever change!
if " tick:" in txt:
if not self.gox.config.get_bool("goxtool", "show_ticker"):
return
if "depth:" in txt:
if not self.gox.config.get_bool("goxtool", "show_depth"):
return
if "trade:" in txt:
if "own order" in txt:
if not self.gox.config.get_bool("goxtool", "show_trade_own"):
return
else:
if not self.gox.config.get_bool("goxtool", "show_trade"):
return
col = COLOR_PAIR["con_text"]
if "trade: bid:" in txt:
col = COLOR_PAIR["con_text_buy"] + curses.A_BOLD
if "trade: ask:" in txt:
col = COLOR_PAIR["con_text_sell"] + curses.A_BOLD
self.win.addstr("\n" + txt, col)
self.done_paint()
class WinOrderBook(Win):
"""the orderbook window"""
def __init__(self, stdscr, gox):
"""create the orderbook window and connect it to the
onChanged callback of the gox.orderbook instance"""
self.gox = gox
gox.orderbook.signal_changed.connect(self.slot_changed)
Win.__init__(self, stdscr)
def calc_size(self):
"""put it into the middle left side"""
self.height = self.termheight - HEIGHT_CON - HEIGHT_STATUS
self.posy = HEIGHT_STATUS
self.width = WIDTH_ORDERBOOK
def paint(self):
"""paint the visible portion of the orderbook"""
def paint_row(pos, price, vol, ownvol, color, changevol):
"""paint a row in the orderbook (bid or ask)"""
if changevol > 0:
col2 = col_bid + curses.A_BOLD
elif changevol < 0:
col2 = col_ask + curses.A_BOLD
else:
col2 = col_vol
self.addstr(pos, 0, book.gox.quote2str(price), color)
self.addstr(pos, 12, book.gox.base2str(vol), col2)
if ownvol:
self.addstr(pos, 28, book.gox.base2str(ownvol), col_own)
self.win.bkgd(" ", COLOR_PAIR["book_text"])
self.win.erase()
gox = self.gox
book = gox.orderbook
mid = self.height / 2
col_bid = COLOR_PAIR["book_bid"]
col_ask = COLOR_PAIR["book_ask"]
col_vol = COLOR_PAIR["book_vol"]
col_own = COLOR_PAIR["book_own"]
sum_total = gox.config.get_bool("goxtool", "orderbook_sum_total")
group = gox.config.get_float("goxtool", "orderbook_group")
group = gox.quote2int(group)
if group == 0:
group = 1
#
#
# paint the asks (first we put them into bins[] then we paint them)
#
if len(book.asks):
i = 0
bins = []
pos = mid - 1
vol = 0
prev_vol = 0
# no grouping, bins can be created in one simple and fast loop
if group == 1:
cnt = len(book.asks)
while pos >= 0 and i < cnt:
level = book.asks[i]
price = level.price
if sum_total:
vol += level.volume
else:
vol = level.volume
ownvol = level.own_volume
bins.append([pos, price, vol, ownvol, 0])
pos -= 1
i += 1
# with gouping its a bit more complicated
else:
# first bin is exact lowest ask price
price = book.asks[0].price
vol = book.asks[0].volume
bins.append([pos, price, vol, 0, 0])
prev_vol = vol
pos -= 1
# now all following bins
bin_price = int(math.ceil(float(price) / group) * group)
if bin_price == price:
# first level was exact bin price already, skip to next bin
bin_price += group
while pos >= 0 and bin_price < book.asks[-1].price + group:
vol, _vol_quote = book.get_total_up_to(bin_price, True) ## 01 freeze
if vol > prev_vol:
# append only non-empty bins
if sum_total:
bins.append([pos, bin_price, vol, 0, 0])
else:
bins.append([pos, bin_price, vol - prev_vol, 0, 0])
prev_vol = vol
pos -= 1
bin_price += group
# now add the own volumes to their bins
for order in book.owns:
if order.typ == "ask" and order.price > 0:
order_bin_price = int(math.ceil(float(order.price) / group) * group)
for abin in bins:
if abin[1] == order.price:
abin[3] += order.volume
break
if abin[1] == order_bin_price:
abin[3] += order.volume
break
# mark the level where change took place (optional)
if gox.config.get_bool("goxtool", "highlight_changes"):
if book.last_change_type == "ask":
change_bin_price = int(math.ceil(float(book.last_change_price) / group) * group)
for abin in bins:
if abin[1] == book.last_change_price:
abin[4] = book.last_change_volume
break
if abin[1] == change_bin_price:
abin[4] = book.last_change_volume
break
# now finally paint the asks
for pos, price, vol, ownvol, changevol in bins:
paint_row(pos, price, vol, ownvol, col_ask, changevol)
#
#
# paint the bids (first we put them into bins[] then we paint them)
#
if len(book.bids):
i = 0
bins = []
pos = mid + 1
vol = 0
prev_vol = 0
# no grouping, bins can be created in one simple and fast loop
if group == 1:
cnt = len(book.bids)
while pos < self.height and i < cnt:
level = book.bids[i]
price = level.price
if sum_total:
vol += level.volume
else:
vol = level.volume
ownvol = level.own_volume
bins.append([pos, price, vol, ownvol, 0])
prev_vol = vol
pos += 1
i += 1
# with gouping its a bit more complicated
else:
# first bin is exact lowest ask price
price = book.bids[0].price
vol = book.bids[0].volume
bins.append([pos, price, vol, 0, 0])
prev_vol = vol
pos += 1
# now all following bins
bin_price = int(math.floor(float(price) / group) * group)
if bin_price == price:
# first level was exact bin price already, skip to next bin
bin_price -= group
while pos < self.height and bin_price >= 0:
vol, _vol_quote = book.get_total_up_to(bin_price, False)
if vol > prev_vol:
# append only non-empty bins
if sum_total:
bins.append([pos, bin_price, vol, 0, 0])
else:
bins.append([pos, bin_price, vol - prev_vol, 0, 0])
prev_vol = vol
pos += 1
bin_price -= group
# now add the own volumes to their bins
for order in book.owns:
if order.typ == "bid" and order.price > 0:
order_bin_price = int(math.floor(float(order.price) / group) * group)
for abin in bins:
if abin[1] == order.price:
abin[3] += order.volume
break
if abin[1] == order_bin_price:
abin[3] += order.volume
break
# mark the level where change took place (optional)
if gox.config.get_bool("goxtool", "highlight_changes"):
if book.last_change_type == "bid":
change_bin_price = int(math.floor(float(book.last_change_price) / group) * group)
for abin in bins:
if abin[1] == book.last_change_price:
abin[4] = book.last_change_volume
break
if abin[1] == change_bin_price:
abin[4] = book.last_change_volume
break
# now finally paint the bids
for pos, price, vol, ownvol, changevol in bins:
paint_row(pos, price, vol, ownvol, col_bid, changevol)
# update the xterm title bar
if self.gox.config.get_bool("goxtool", "set_xterm_title"):
last_candle = self.gox.history.last_candle()
if last_candle:
title = self.gox.quote2str(last_candle.cls).strip()
title += " - goxtool -"
title += " bid:" + self.gox.quote2str(book.bid).strip()
title += " ask:" + self.gox.quote2str(book.ask).strip()
term = os.environ["TERM"]
# the following is incomplete but better safe than sorry
# if you know more terminals then please provide a patch
if "xterm" in term or "rxvt" in term:
sys_out.write("\x1b]0;%s\x07" % title)
sys_out.flush()
def slot_changed(self, _book, _dummy):
"""Slot for orderbook.signal_changed"""
self.do_paint()
TYPE_HISTORY = 1
TYPE_ORDERBOOK = 2
class WinChart(Win):
"""the chart window"""
def __init__(self, stdscr, gox):
self.gox = gox
self.pmin = 0
self.pmax = 0
self.change_type = None
gox.history.signal_changed.connect(self.slot_history_changed)
gox.orderbook.signal_changed.connect(self.slot_orderbook_changed)
# some terminals do not support reverse video
# so we cannot use reverse space for candle bodies
if curses.A_REVERSE & curses.termattrs():
self.body_char = " "
self.body_attr = curses.A_REVERSE
else:
self.body_char = curses.ACS_CKBOARD # pylint: disable=E1101
self.body_attr = 0
Win.__init__(self, stdscr)
def calc_size(self):
"""position in the middle, right to the orderbook"""
self.posx = WIDTH_ORDERBOOK
self.posy = HEIGHT_STATUS
self.width = self.termwidth - WIDTH_ORDERBOOK
self.height = self.termheight - HEIGHT_CON - HEIGHT_STATUS
def is_in_range(self, price):
"""is this price in the currently visible range?"""
return price <= self.pmax and price >= self.pmin
def get_optimal_step(self, num_min):
"""return optimal step size for painting y-axis labels so that the
range will be divided into at least num_min steps"""
if self.pmax <= self.pmin:
return None
stepex = float(self.pmax - self.pmin) / num_min
step1 = math.pow(10, math.floor(math.log(stepex, 10)))
step2 = step1 * 2
step5 = step1 * 5
if step5 <= stepex:
return step5
if step2 <= stepex:
return step2
return step1
def price_to_screen(self, price):
"""convert price into screen coordinates (y=0 is at the top!)"""
relative_from_bottom = \
float(price - self.pmin) / float(self.pmax - self.pmin)
screen_from_bottom = relative_from_bottom * self.height
return int(self.height - screen_from_bottom)
def paint_y_label(self, posy, posx, price):
"""paint the y label of the history chart, formats the number
so that it needs not more room than necessary but it also uses
pmax to determine how many digits are needed so that all numbers
will be nicely aligned at the decimal point"""
fprice = self.gox.quote2float(price)
labelstr = ("%f" % fprice).rstrip("0").rstrip(".")
# look at pmax to determine the max number of digits before the decimal
# and then pad all smaller prices with spaces to make them align nicely.
need_digits = int(math.log10(self.gox.quote2float(self.pmax))) + 1
have_digits = len(str(int(fprice)))
if have_digits < need_digits:
padding = " " * (need_digits - have_digits)
labelstr = padding + labelstr
self.addstr(
posy, posx,
labelstr,
COLOR_PAIR["chart_text"]
)
def paint_candle(self, posx, candle):
"""paint a single candle"""
sopen = self.price_to_screen(candle.opn)
shigh = self.price_to_screen(candle.hig)
slow = self.price_to_screen(candle.low)
sclose = self.price_to_screen(candle.cls)
for posy in range(self.height):
if posy >= shigh and posy < sopen and posy < sclose:
# upper wick
# pylint: disable=E1101
self.addch(posy, posx, curses.ACS_VLINE, COLOR_PAIR["chart_text"])
if posy >= sopen and posy < sclose:
# red body
self.addch(posy, posx, self.body_char, self.body_attr + COLOR_PAIR["chart_down"])
if posy >= sclose and posy < sopen:
# green body
self.addch(posy, posx, self.body_char, self.body_attr + COLOR_PAIR["chart_up"])
if posy >= sopen and posy >= sclose and posy < slow:
# lower wick
# pylint: disable=E1101
self.addch(posy, posx, curses.ACS_VLINE, COLOR_PAIR["chart_text"])
def paint(self):
typ = self.gox.config.get_string("goxtool", "display_right")
if typ == "history_chart":
self.paint_history_chart()
elif typ == "depth_chart":
self.paint_depth_chart()
else:
self.paint_history_chart()
def paint_depth_chart(self):
"""paint a depth chart"""
# pylint: disable=C0103
if self.gox.curr_quote in "JPY SEK":
BAR_LEFT_EDGE = 7
FORMAT_STRING = "%6.0f"
else:
BAR_LEFT_EDGE = 8
FORMAT_STRING = "%7.2f"
def paint_depth(pos, price, vol, own, col_price, change):
"""paint one row of the depth chart"""
if change > 0:
col = col_bid + curses.A_BOLD
elif change < 0:
col = col_ask + curses.A_BOLD
else:
col = col_bar
pricestr = FORMAT_STRING % self.gox.quote2float(price)
self.addstr(pos, 0, pricestr, col_price)
length = int(vol * mult_x)
# pylint: disable=E1101
self.win.hline(pos, BAR_LEFT_EDGE, curses.ACS_CKBOARD, length, col)
if own:
self.addstr(pos, length + BAR_LEFT_EDGE, "o", col_own)
self.win.bkgd(" ", COLOR_PAIR["chart_text"])
self.win.erase()
book = self.gox.orderbook
if not (book.bid and book.ask and len(book.bids) and len(book.asks)):
# orderbook is not initialized yet, paint nothing
return
col_bar = COLOR_PAIR["book_vol"]
col_bid = COLOR_PAIR["book_bid"]
col_ask = COLOR_PAIR["book_ask"]
col_own = COLOR_PAIR["book_own"]
group = self.gox.config.get_float("goxtool", "depth_chart_group")
if group == 0:
group = 1
group = self.gox.quote2int(group)
max_vol_ask = 0
max_vol_bid = 0
bin_asks = []
bin_bids = []
mid = self.height / 2
sum_total = self.gox.config.get_bool("goxtool", "depth_chart_sum_total")
#
#
# bin the asks
#
pos = mid - 1
prev_vol = 0
bin_price = int(math.ceil(float(book.asks[0].price) / group) * group)
while pos >= 0 and bin_price < book.asks[-1].price + group:
bin_vol, _bin_vol_quote = book.get_total_up_to(bin_price, True)
if bin_vol > prev_vol:
# add only non-empty bins
if sum_total:
bin_asks.append([pos, bin_price, bin_vol, 0, 0])
max_vol_ask = max(bin_vol, max_vol_ask)
else:
bin_asks.append([pos, bin_price, bin_vol - prev_vol, 0, 0])
max_vol_ask = max(bin_vol - prev_vol, max_vol_ask)
prev_vol = bin_vol
pos -= 1
bin_price += group
#
#
# bin the bids
#
pos = mid + 1
prev_vol = 0
bin_price = int(math.floor(float(book.bids[0].price) / group) * group)
while pos < self.height and bin_price >= 0:
_bin_vol_base, bin_vol_quote = book.get_total_up_to(bin_price, False)
bin_vol = self.gox.base2int(bin_vol_quote / book.bid)
if bin_vol > prev_vol:
# add only non-empty bins
if sum_total:
bin_bids.append([pos, bin_price, bin_vol, 0, 0])
max_vol_bid = max(bin_vol, max_vol_bid)
else:
bin_bids.append([pos, bin_price, bin_vol - prev_vol, 0, 0])
max_vol_bid = max(bin_vol - prev_vol, max_vol_bid)
prev_vol = bin_vol
pos += 1
bin_price -= group
max_vol_tot = max(max_vol_ask, max_vol_bid)
if not max_vol_tot:
return
mult_x = float(self.width - BAR_LEFT_EDGE - 2) / max_vol_tot
# add the own volume to the bins
for order in book.owns:
if order.price > 0:
if order.typ == "ask":
bin_price = int(math.ceil(float(order.price) / group) * group)
for abin in bin_asks:
if abin[1] == bin_price:
abin[3] += order.volume
break
else:
bin_price = int(math.floor(float(order.price) / group) * group)
for abin in bin_bids:
if abin[1] == bin_price:
abin[3] += order.volume
break
# highlight the relative change (optional)
if self.gox.config.get_bool("goxtool", "highlight_changes"):
price = book.last_change_price
if book.last_change_type == "ask":
bin_price = int(math.ceil(float(price) / group) * group)
for abin in bin_asks:
if abin[1] == bin_price:
abin[4] = book.last_change_volume
break
if book.last_change_type == "bid":
bin_price = int(math.floor(float(price) / group) * group)
for abin in bin_bids:
if abin[1] == bin_price:
abin[4] = book.last_change_volume
break
# paint the asks
for pos, price, vol, own, change in bin_asks:
paint_depth(pos, price, vol, own, col_ask, change)
# paint the bids
for pos, price, vol, own, change in bin_bids:
paint_depth(pos, price, vol, own, col_bid, change)
def paint_history_chart(self):
"""paint a history candlestick chart"""
if self.change_type == TYPE_ORDERBOOK:
# erase only the rightmost column to redraw bid/ask and orders
# beause we won't redraw the chart, its only an orderbook change
self.win.vline(0, self.width - 1, " ", self.height, COLOR_PAIR["chart_text"])
else:
self.win.bkgd(" ", COLOR_PAIR["chart_text"])
self.win.erase()
hist = self.gox.history
book = self.gox.orderbook
self.pmax = 0
self.pmin = 9999999999
# determine y range
posx = self.width - 2
index = 0
while index < hist.length() and posx >= 0:
candle = hist.candles[index]
if self.pmax < candle.hig:
self.pmax = candle.hig
if self.pmin > candle.low:
self.pmin = candle.low
index += 1
posx -= 1
if self.pmax == self.pmin:
return
# paint the candlestick chart.
# We won't paint it if it was triggered from an orderbook change
# signal because that would be redundant and only waste CPU.
# In that case we only repaint the bid/ask markers (see below)
if self.change_type != TYPE_ORDERBOOK:
# paint the candles
posx = self.width - 2
index = 0
while index < hist.length() and posx >= 0:
candle = hist.candles[index]
self.paint_candle(posx, candle)
index += 1
posx -= 1
# paint the y-axis labels
posx = 0
step = self.get_optimal_step(4)
if step:
labelprice = int(self.pmin / step) * step
while not labelprice > self.pmax:
posy = self.price_to_screen(labelprice)
if posy < self.height - 1:
self.paint_y_label(posy, posx, labelprice)
labelprice += step
# paint bid, ask, own orders
posx = self.width - 1
for order in book.owns:
if self.is_in_range(order.price):
posy = self.price_to_screen(order.price)
if order.status == "pending":
self.addch(posy, posx,
ord("p"), COLOR_PAIR["order_pending"])
else:
self.addch(posy, posx,
ord("o"), COLOR_PAIR["book_own"])
if self.is_in_range(book.bid):
posy = self.price_to_screen(book.bid)
# pylint: disable=E1101
self.addch(posy, posx,
curses.ACS_HLINE, COLOR_PAIR["chart_up"])
if self.is_in_range(book.ask):
posy = self.price_to_screen(book.ask)
# pylint: disable=E1101
self.addch(posy, posx,
curses.ACS_HLINE, COLOR_PAIR["chart_down"])
def slot_history_changed(self, _sender, _data):
"""Slot for history changed"""
self.change_type = TYPE_HISTORY
self.do_paint()
self.change_type = None
def slot_orderbook_changed(self, _sender, _data):
"""Slot for orderbook changed"""
self.change_type = TYPE_ORDERBOOK
self.do_paint()
self.change_type = None
class WinStatus(Win):
"""the status window at the top"""
def __init__(self, stdscr, gox):
"""create the status window and connect the needed callbacks"""
self.gox = gox
self.order_lag = 0
self.order_lag_txt = ""
self.sorted_currency_list = []
gox.signal_orderlag.connect(self.slot_orderlag)
gox.signal_wallet.connect(self.slot_changed)
gox.orderbook.signal_changed.connect(self.slot_changed)
Win.__init__(self, stdscr)
def calc_size(self):
"""place it at the top of the terminal"""
self.height = HEIGHT_STATUS
def sort_currency_list_if_changed(self):
"""sort the currency list in the wallet for better display,
sort it only if it has changed, otherwise leave it as it is"""
currency_list = self.gox.wallet.keys()
if len(currency_list) == len(self.sorted_currency_list):
return
# now we will bring base and quote currency to the front and sort the
# the rest of the list of names by acount balance in descending order
if self.gox.curr_base in currency_list:
currency_list.remove(self.gox.curr_base)
if self.gox.curr_quote in currency_list:
currency_list.remove(self.gox.curr_quote)
currency_list.sort(key=lambda name: -self.gox.wallet[name])
currency_list.insert(0, self.gox.curr_quote)
currency_list.insert(0, self.gox.curr_base)
self.sorted_currency_list = currency_list
def paint(self):
"""paint the complete status"""
cbase = self.gox.curr_base
cquote = self.gox.curr_quote
self.sort_currency_list_if_changed()
self.win.bkgd(" ", COLOR_PAIR["status_text"])
self.win.erase()
#
# first line
#
line1 = "Market: %s%s | " % (cbase, cquote)
line1 += "Account: "
if len(self.sorted_currency_list):
for currency in self.sorted_currency_list:
if currency in self.gox.wallet:
line1 += currency + " " \
+ goxapi.int2str(self.gox.wallet[currency], currency).strip() \
+ " + "
line1 = line1.strip(" +")
else:
line1 += "No info (yet)"
#
# second line
#
line2 = ""
if self.gox.config.get_bool("goxtool", "show_orderbook_stats"):
str_btc = locale.format('%d', self.gox.orderbook.total_ask, 1)
str_fiat = locale.format('%d', self.gox.orderbook.total_bid, 1)
if self.gox.orderbook.total_ask:
str_ratio = locale.format('%1.2f',
self.gox.orderbook.total_bid / self.gox.orderbook.total_ask, 1)
else:
str_ratio = "-"
line2 += "sum_bid: %s %s | " % (str_fiat, cquote)
line2 += "sum_ask: %s %s | " % (str_btc, cbase)
line2 += "ratio: %s %s/%s | " % (str_ratio, cquote, cbase)
line2 += "o_lag: %s | " % self.order_lag_txt
line2 += "s_lag: %.3f s" % (self.gox.socket_lag / 1e6)
self.addstr(0, 0, line1, COLOR_PAIR["status_text"])
self.addstr(1, 0, line2, COLOR_PAIR["status_text"])
def slot_changed(self, dummy_sender, dummy_data):
"""the callback funtion called by the Gox() instance"""
self.do_paint()
def slot_orderlag(self, dummy_sender, (usec, text)):
"""slot for order_lag mesages"""
self.order_lag = usec
self.order_lag_txt = text
self.do_paint()
class DlgListItems(Win):
"""dialog with a scrollable list of items"""
def __init__(self, stdscr, width, title, hlp, keys):
self.items = []