This repository has been archived by the owner on Jul 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
api.py
1639 lines (1457 loc) · 80.3 KB
/
api.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
import os
import json
import re
import time
import datetime
import base64
import decimal
import operator
import logging
import copy
import uuid
import urllib
import functools
from logging import handlers as logging_handlers
from gevent import wsgi
from geventhttpclient import HTTPClient
from geventhttpclient.url import URL
import flask
import jsonrpc
from jsonrpc import dispatcher
import pymongo
from bson import json_util
from bson.son import SON
from lib import config, siofeeds, util, blockchain, util_bitcoin
from lib.components import betting, rps, assets_trading, dex
PREFERENCES_MAX_LENGTH = 100000 #in bytes, as expressed in JSON
API_MAX_LOG_SIZE = 10 * 1024 * 1024 #max log size of 20 MB before rotation (make configurable later)
API_MAX_LOG_COUNT = 10
decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
D = decimal.Decimal
def serve_api(mongo_db, redis_client):
# Preferneces are just JSON objects... since we don't force a specific form to the wallet on
# the server side, this makes it easier for 3rd party wallets (i.e. not Counterwallet) to fully be able to
# use counterblockd to not only pull useful data, but also load and store their own preferences, containing
# whatever data they need
DEFAULT_COUNTERPARTYD_API_CACHE_PERIOD = 60 #in seconds
app = flask.Flask(__name__)
tx_logger = logging.getLogger("transaction_log") #get transaction logger
@dispatcher.add_method
def is_ready():
"""this method used by the client to check if the server is alive, caught up, and ready to accept requests.
If the server is NOT caught up, a 525 error will be returned actually before hitting this point. Thus,
if we actually return data from this function, it should always be true. (may change this behaviour later)"""
blockchainInfo = blockchain.getinfo()
ip = flask.request.headers.get('X-Real-Ip', flask.request.remote_addr)
country = config.GEOIP.country_code_by_addr(ip)
return {
'caught_up': util.is_caught_up_well_enough_for_government_work(),
'last_message_index': config.LAST_MESSAGE_INDEX,
'block_height': blockchainInfo['info']['blocks'],
'testnet': config.TESTNET,
'ip': ip,
'country': country
}
@dispatcher.add_method
def get_reflected_host_info():
"""Allows the requesting host to get some info about itself, such as its IP. Used for troubleshooting."""
ip = flask.request.headers.get('X-Real-Ip', flask.request.remote_addr)
country = config.GEOIP.country_code_by_addr(ip)
return {
'ip': ip,
'cookie': flask.request.headers.get('Cookie', ''),
'country': country
}
@dispatcher.add_method
def get_messagefeed_messages_by_index(message_indexes):
messages = util.call_jsonrpc_api("get_messages_by_index", {'message_indexes': message_indexes}, abort_on_error=True)['result']
events = []
for m in messages:
events.append(util.decorate_message_for_feed(m))
return events
@dispatcher.add_method
def get_chain_block_height():
data = blockchain.getinfo()
return data['info']['blocks']
@dispatcher.add_method
def get_chain_address_info(addresses, with_uxtos=True, with_last_txn_hashes=4, with_block_height=False):
if not isinstance(addresses, list):
raise Exception("addresses must be a list of addresses, even if it just contains one address")
results = []
if with_block_height:
block_height_response = blockchain.getinfo()
block_height = block_height_response['info']['blocks'] if block_height_response else None
for address in addresses:
info = blockchain.getaddressinfo(address)
txns = info['transactions']
del info['transactions']
result = {}
result['addr'] = address
result['info'] = info
if with_block_height: result['block_height'] = block_height
#^ yeah, hacky...it will be the same block height for each address (we do this to avoid an extra API call to get_block_height)
if with_uxtos:
result['uxtos'] = blockchain.listunspent(address)
if with_last_txn_hashes:
#with last_txns, only show CONFIRMED txns (so skip the first info['unconfirmedTxApperances'] # of txns, if not 0
result['last_txns'] = txns[info['unconfirmedTxApperances']:with_last_txn_hashes+info['unconfirmedTxApperances']]
results.append(result)
return results
@dispatcher.add_method
def get_chain_txns_status(txn_hashes):
if not isinstance(txn_hashes, list):
raise Exception("txn_hashes must be a list of txn hashes, even if it just contains one hash")
results = []
for tx_hash in txn_hashes:
tx_info = blockchain.gettransaction(tx_hash);
if tx_info:
assert tx_info['txid'] == tx_hash
results.append({
'tx_hash': tx_info['txid'],
'blockhash': tx_info.get('blockhash', None), #not provided if not confirmed on network
'confirmations': tx_info.get('confirmations', 0), #not provided if not confirmed on network
'blocktime': tx_info.get('time', None),
})
return results
@dispatcher.add_method
def get_normalized_balances(addresses):
"""
This call augments counterpartyd's get_balances with a normalized_quantity field. It also will include any owned
assets for an address, even if their balance is zero.
NOTE: Does not retrieve BTC balance. Use get_address_info for that.
"""
if not isinstance(addresses, list):
raise Exception("addresses must be a list of addresses, even if it just contains one address")
if not len(addresses):
raise Exception("Invalid address list supplied")
filters = []
for address in addresses:
filters.append({'field': 'address', 'op': '==', 'value': address})
mappings = {}
result = util.call_jsonrpc_api("get_balances",
{'filters': filters, 'filterop': 'or'}, abort_on_error=True)['result']
isowner = {}
owned_assets = mongo_db.tracked_assets.find( { '$or': [{'owner': a } for a in addresses] }, { '_history': 0, '_id': 0 } )
for o in owned_assets:
isowner[o['owner'] + o['asset']] = o
data = []
for d in result:
if not d['quantity'] and ((d['address'] + d['asset']) not in isowner):
continue #don't include balances with a zero asset value
asset_info = mongo_db.tracked_assets.find_one({'asset': d['asset']})
d['normalized_quantity'] = util_bitcoin.normalize_quantity(d['quantity'], asset_info['divisible'])
d['owner'] = (d['address'] + d['asset']) in isowner
mappings[d['address'] + d['asset']] = d
data.append(d)
#include any owned assets for each address, even if their balance is zero
for key in isowner:
if key not in mappings:
o = isowner[key]
data.append({
'address': o['owner'],
'asset': o['asset'],
'quantity': 0,
'normalized_quantity': 0,
'owner': True,
})
return data
def _get_address_history(address, start_block=None, end_block=None):
address_dict = {}
address_dict['balances'] = util.call_jsonrpc_api("get_balances",
{ 'filters': [{'field': 'address', 'op': '==', 'value': address},],
}, abort_on_error=True)['result']
address_dict['debits'] = util.call_jsonrpc_api("get_debits",
{ 'filters': [{'field': 'address', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['credits'] = util.call_jsonrpc_api("get_credits",
{ 'filters': [{'field': 'address', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['burns'] = util.call_jsonrpc_api("get_burns",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['sends'] = util.call_jsonrpc_api("get_sends",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address}, {'field': 'destination', 'op': '==', 'value': address}],
'filterop': 'or',
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
#^ with filterop == 'or', we get all sends where this address was the source OR destination
address_dict['orders'] = util.call_jsonrpc_api("get_orders",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['order_matches'] = util.call_jsonrpc_api("get_order_matches",
{ 'filters': [{'field': 'tx0_address', 'op': '==', 'value': address}, {'field': 'tx1_address', 'op': '==', 'value': address},],
'filterop': 'or',
'order_by': 'tx0_block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['btcpays'] = util.call_jsonrpc_api("get_btcpays",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address}, {'field': 'destination', 'op': '==', 'value': address}],
'filterop': 'or',
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['issuances'] = util.call_jsonrpc_api("get_issuances",
{ 'filters': [{'field': 'issuer', 'op': '==', 'value': address}, {'field': 'source', 'op': '==', 'value': address}],
'filterop': 'or',
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['broadcasts'] = util.call_jsonrpc_api("get_broadcasts",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['bets'] = util.call_jsonrpc_api("get_bets",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['bet_matches'] = util.call_jsonrpc_api("get_bet_matches",
{ 'filters': [{'field': 'tx0_address', 'op': '==', 'value': address}, {'field': 'tx1_address', 'op': '==', 'value': address},],
'filterop': 'or',
'order_by': 'tx0_block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['dividends'] = util.call_jsonrpc_api("get_dividends",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['cancels'] = util.call_jsonrpc_api("get_cancels",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['callbacks'] = util.call_jsonrpc_api("get_callbacks",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['bet_expirations'] = util.call_jsonrpc_api("get_bet_expirations",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['order_expirations'] = util.call_jsonrpc_api("get_order_expirations",
{ 'filters': [{'field': 'source', 'op': '==', 'value': address},],
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['bet_match_expirations'] = util.call_jsonrpc_api("get_bet_match_expirations",
{ 'filters': [{'field': 'tx0_address', 'op': '==', 'value': address}, {'field': 'tx1_address', 'op': '==', 'value': address},],
'filterop': 'or',
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
address_dict['order_match_expirations'] = util.call_jsonrpc_api("get_order_match_expirations",
{ 'filters': [{'field': 'tx0_address', 'op': '==', 'value': address}, {'field': 'tx1_address', 'op': '==', 'value': address},],
'filterop': 'or',
'order_by': 'block_index',
'order_dir': 'asc',
'start_block': start_block,
'end_block': end_block,
}, abort_on_error=True)['result']
return address_dict
@dispatcher.add_method
def get_last_n_messages(count=100):
if count > 1000:
raise Exception("The count is too damn high")
message_indexes = range(max(config.LAST_MESSAGE_INDEX - count, 0) + 1, config.LAST_MESSAGE_INDEX+1)
messages = util.call_jsonrpc_api("get_messages_by_index",
{ 'message_indexes': message_indexes }, abort_on_error=True)['result']
for i in xrange(len(messages)):
messages[i] = util.decorate_message_for_feed(messages[i])
return messages
@dispatcher.add_method
def get_raw_transactions(address, start_ts=None, end_ts=None, limit=500):
"""Gets raw transactions for a particular address
@param address: A single address string
@param start_ts: The starting date & time. Should be a unix epoch object. If passed as None, defaults to 60 days before the end_date
@param end_ts: The ending date & time. Should be a unix epoch object. If passed as None, defaults to the current date & time
@param limit: the maximum number of transactions to return; defaults to ten thousand
@return: Returns the data, ordered from newest txn to oldest. If any limit is applied, it will cut back from the oldest results
"""
def get_asset_cached(asset, asset_cache):
if asset in asset_cache:
return asset_cache[asset]
asset_data = mongo_db.tracked_assets.find_one({'asset': asset})
asset_cache[asset] = asset_data
return asset_data
asset_cache = {} #ghetto cache to speed asset lookups within the scope of a function call
now_ts = time.mktime(datetime.datetime.utcnow().timetuple())
if not end_ts: #default to current datetime
end_ts = now_ts
if not start_ts: #default to 60 days before the end date
start_ts = end_ts - (60 * 24 * 60 * 60)
start_block_index, end_block_index = util.get_block_indexes_for_dates(
start_dt=datetime.datetime.utcfromtimestamp(start_ts),
end_dt=datetime.datetime.utcfromtimestamp(end_ts) if now_ts != end_ts else None)
#make API call to counterpartyd to get all of the data for the specified address
txns = []
d = _get_address_history(address, start_block=start_block_index, end_block=end_block_index)
#mash it all together
for category, entries in d.iteritems():
if category in ['balances',]:
continue
for e in entries:
e['_category'] = category
e = util.decorate_message(e, for_txn_history=True) #DRY
txns += entries
txns = util.multikeysort(txns, ['-_block_time', '-_tx_index'])
txns = txns[0:limit] #TODO: we can trunk before sorting. check if we can use the messages table and use sql order and limit
#^ won't be a perfect sort since we don't have tx_indexes for cancellations, but better than nothing
#txns.sort(key=operator.itemgetter('block_index'))
return txns
@dispatcher.add_method
def get_base_quote_asset(asset1, asset2):
"""Given two arbitrary assets, returns the base asset and the quote asset.
"""
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
base_asset_info = mongo_db.tracked_assets.find_one({'asset': base_asset})
quote_asset_info = mongo_db.tracked_assets.find_one({'asset': quote_asset})
pair_name = "%s/%s" % (base_asset, quote_asset)
if not base_asset_info or not quote_asset_info:
raise Exception("Invalid asset(s)")
return {
'base_asset': base_asset,
'quote_asset': quote_asset,
'pair_name': pair_name
}
@dispatcher.add_method
def get_market_price_summary(asset1, asset2, with_last_trades=0):
result = assets_trading.get_market_price_summary(asset1, asset2, with_last_trades)
return result if result is not None else False
#^ due to current bug in our jsonrpc stack, just return False if None is returned
@dispatcher.add_method
def get_market_cap_history(start_ts=None, end_ts=None):
now_ts = time.mktime(datetime.datetime.utcnow().timetuple())
if not end_ts: #default to current datetime
end_ts = now_ts
if not start_ts: #default to 30 days before the end date
start_ts = end_ts - (30 * 24 * 60 * 60)
data = {}
results = {}
#^ format is result[market_cap_as][asset] = [[block_time, market_cap], [block_time2, market_cap2], ...]
for market_cap_as in (config.XCP, config.BTC):
caps = mongo_db.asset_marketcap_history.aggregate([
{"$match": {
"market_cap_as": market_cap_as,
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}},
{"$project": {
"year": {"$year": "$block_time"},
"month": {"$month": "$block_time"},
"day": {"$dayOfMonth": "$block_time"},
"hour": {"$hour": "$block_time"},
"asset": 1,
"market_cap": 1,
}},
{"$sort": {"block_time": pymongo.ASCENDING}},
{"$group": {
"_id": {"asset": "$asset", "year": "$year", "month": "$month", "day": "$day", "hour": "$hour"},
"market_cap": {"$avg": "$market_cap"}, #use the average marketcap during the interval
}},
])
caps = [] if not caps['ok'] else caps['result']
data[market_cap_as] = {}
for e in caps:
interval_time = int(time.mktime(datetime.datetime(e['_id']['year'], e['_id']['month'], e['_id']['day'], e['_id']['hour']).timetuple()) * 1000)
data[market_cap_as].setdefault(e['_id']['asset'], [])
data[market_cap_as][e['_id']['asset']].append([interval_time, e['market_cap']])
results[market_cap_as] = []
for asset in data[market_cap_as]:
#for z in data[market_cap_as][asset]: assert z[0] and z[0] > 0 and z[1] and z[1] >= 0
results[market_cap_as].append({'name': asset,
'data': sorted(data[market_cap_as][asset], key=operator.itemgetter(0))})
return results
@dispatcher.add_method
def get_market_info(assets):
assets_market_info = list(mongo_db.asset_market_info.find({'asset': {'$in': assets}}, {'_id': 0}))
extended_asset_info = mongo_db.asset_extended_info.find({'asset': {'$in': assets}})
extended_asset_info_dict = {}
for e in extended_asset_info:
if not e.get('disabled', False): #skip assets marked disabled
extended_asset_info_dict[e['asset']] = e
for a in assets_market_info:
if a['asset'] in extended_asset_info_dict and extended_asset_info_dict[a['asset']].get('processed', False):
extended_info = extended_asset_info_dict[a['asset']]
a['extended_image'] = bool(extended_info.get('image', ''))
a['extended_description'] = extended_info.get('description', '')
a['extended_website'] = extended_info.get('website', '')
a['extended_pgpsig'] = extended_info.get('pgpsig', '')
else:
a['extended_image'] = a['extended_description'] = a['extended_website'] = a['extended_pgpsig'] = ''
return assets_market_info
@dispatcher.add_method
def get_market_info_leaderboard(limit=100):
"""returns market leaderboard data for both the XCP and BTC markets"""
#do two queries because we limit by our sorted results, and we might miss an asset with a high BTC trading value
# but with little or no XCP trading activity, for instance if we just did one query
assets_market_info_xcp = list(mongo_db.asset_market_info.find({}, {'_id': 0}).sort('market_cap_in_{}'.format(config.XCP.lower()), pymongo.DESCENDING).limit(limit))
assets_market_info_btc = list(mongo_db.asset_market_info.find({}, {'_id': 0}).sort('market_cap_in_{}'.format(config.BTC.lower()), pymongo.DESCENDING).limit(limit))
assets_market_info = {
config.XCP.lower(): [a for a in assets_market_info_xcp if a['price_in_{}'.format(config.XCP.lower())]],
config.BTC.lower(): [a for a in assets_market_info_btc if a['price_in_{}'.format(config.BTC.lower())]]
}
#throw on extended info, if it exists for a given asset
assets = list(set([a['asset'] for a in assets_market_info[config.XCP.lower()]] + [a['asset'] for a in assets_market_info[config.BTC.lower()]]))
extended_asset_info = mongo_db.asset_extended_info.find({'asset': {'$in': assets}})
extended_asset_info_dict = {}
for e in extended_asset_info:
if not e.get('disabled', False): #skip assets marked disabled
extended_asset_info_dict[e['asset']] = e
for r in (assets_market_info[config.XCP.lower()], assets_market_info[config.BTC.lower()]):
for a in r:
if a['asset'] in extended_asset_info_dict:
extended_info = extended_asset_info_dict[a['asset']]
if 'extended_image' not in a or 'extended_description' not in a or 'extended_website' not in a:
continue #asset has been recognized as having a JSON file description, but has not been successfully processed yet
a['extended_image'] = bool(extended_info.get('image', ''))
a['extended_description'] = extended_info.get('description', '')
a['extended_website'] = extended_info.get('website', '')
else:
a['extended_image'] = a['extended_description'] = a['extended_website'] = ''
return assets_market_info
@dispatcher.add_method
def get_market_price_history(asset1, asset2, start_ts=None, end_ts=None, as_dict=False):
"""Return block-by-block aggregated market history data for the specified asset pair, within the specified date range.
@returns List of lists (or list of dicts, if as_dict is specified).
* If as_dict is False, each embedded list has 8 elements [block time (epoch in MS), open, high, low, close, volume, # trades in block, block index]
* If as_dict is True, each dict in the list has the keys: block_time (epoch in MS), block_index, open, high, low, close, vol, count
Aggregate on an an hourly basis
"""
now_ts = time.mktime(datetime.datetime.utcnow().timetuple())
if not end_ts: #default to current datetime
end_ts = now_ts
if not start_ts: #default to 180 days before the end date
start_ts = end_ts - (180 * 24 * 60 * 60)
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
#get ticks -- open, high, low, close, volume
result = mongo_db.trades.aggregate([
{"$match": {
"base_asset": base_asset,
"quote_asset": quote_asset,
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}},
{"$project": {
"year": {"$year": "$block_time"},
"month": {"$month": "$block_time"},
"day": {"$dayOfMonth": "$block_time"},
"hour": {"$hour": "$block_time"},
"block_index": 1,
"unit_price": 1,
"base_quantity_normalized": 1 #to derive volume
}},
{"$group": {
"_id": {"year": "$year", "month": "$month", "day": "$day", "hour": "$hour"},
"open": {"$first": "$unit_price"},
"high": {"$max": "$unit_price"},
"low": {"$min": "$unit_price"},
"close": {"$last": "$unit_price"},
"vol": {"$sum": "$base_quantity_normalized"},
"count": {"$sum": 1},
}},
{"$sort": SON([("_id.year", pymongo.ASCENDING), ("_id.month", pymongo.ASCENDING), ("_id.day", pymongo.ASCENDING), ("_id.hour", pymongo.ASCENDING)])},
])
if not result['ok'] or not len(result['result']):
return False
result = result['result']
midline = [((r['high'] + r['low']) / 2.0) for r in result]
if as_dict:
for i in xrange(len(result)):
result[i]['interval_time'] = int(time.mktime(datetime.datetime(
result[i]['_id']['year'], result[i]['_id']['month'], result[i]['_id']['day'], result[i]['_id']['hour']).timetuple()) * 1000)
result[i]['midline'] = midline[i]
del result[i]['_id']
return result
else:
list_result = []
for i in xrange(len(result)):
list_result.append([
int(time.mktime(datetime.datetime(
result[i]['_id']['year'], result[i]['_id']['month'], result[i]['_id']['day'], result[i]['_id']['hour']).timetuple()) * 1000),
result[i]['open'], result[i]['high'], result[i]['low'], result[i]['close'], result[i]['vol'],
result[i]['count'], midline[i]
])
return list_result
@dispatcher.add_method
def get_trade_history(asset1=None, asset2=None, start_ts=None, end_ts=None, limit=50):
"""
Gets last N of trades within a specific date range (normally, for a specified asset pair, but this can
be left blank to get any/all trades).
"""
assert (asset1 and asset2) or (not asset1 and not asset2) #cannot have one asset, but not the other
if limit > 500:
raise Exception("Requesting history of too many trades")
now_ts = time.mktime(datetime.datetime.utcnow().timetuple())
if not end_ts: #default to current datetime
end_ts = now_ts
if not start_ts: #default to 30 days before the end date
start_ts = end_ts - (30 * 24 * 60 * 60)
filters = {
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}
if asset1 and asset2:
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
filters["base_asset"] = base_asset
filters["quote_asset"] = quote_asset
last_trades = mongo_db.trades.find(filters, {'_id': 0}).sort("block_time", pymongo.DESCENDING).limit(limit)
if not last_trades.count():
return False #no suitable trade data to form a market price
last_trades = list(last_trades)
return last_trades
def _get_order_book(base_asset, quote_asset,
bid_book_min_pct_fee_provided=None, bid_book_min_pct_fee_required=None, bid_book_max_pct_fee_required=None,
ask_book_min_pct_fee_provided=None, ask_book_min_pct_fee_required=None, ask_book_max_pct_fee_required=None):
"""Gets the current order book for a specified asset pair
@param: normalized_fee_required: Only specify if buying BTC. If specified, the order book will be pruned down to only
show orders at and above this fee_required
@param: normalized_fee_provided: Only specify if selling BTC. If specified, the order book will be pruned down to only
show orders at and above this fee_provided
"""
base_asset_info = mongo_db.tracked_assets.find_one({'asset': base_asset})
quote_asset_info = mongo_db.tracked_assets.find_one({'asset': quote_asset})
if not base_asset_info or not quote_asset_info:
raise Exception("Invalid asset(s)")
#TODO: limit # results to 8 or so for each book (we have to sort as well to limit)
base_bid_filters = [
{"field": "get_asset", "op": "==", "value": base_asset},
{"field": "give_asset", "op": "==", "value": quote_asset},
]
base_ask_filters = [
{"field": "get_asset", "op": "==", "value": quote_asset},
{"field": "give_asset", "op": "==", "value": base_asset},
]
if base_asset == config.BTC or quote_asset == config.BTC:
extra_filters = [
{'field': 'give_remaining', 'op': '>', 'value': 0}, #don't show empty BTC orders
{'field': 'get_remaining', 'op': '>', 'value': 0}, #don't show empty BTC orders
{'field': 'fee_required_remaining', 'op': '>=', 'value': 0},
{'field': 'fee_provided_remaining', 'op': '>=', 'value': 0},
]
base_bid_filters += extra_filters
base_ask_filters += extra_filters
base_bid_orders = util.call_jsonrpc_api("get_orders", {
'filters': base_bid_filters,
'show_expired': False,
'status': 'open',
'order_by': 'block_index',
'order_dir': 'asc',
}, abort_on_error=True)['result']
base_ask_orders = util.call_jsonrpc_api("get_orders", {
'filters': base_ask_filters,
'show_expired': False,
'status': 'open',
'order_by': 'block_index',
'order_dir': 'asc',
}, abort_on_error=True)['result']
def get_o_pct(o):
if o['give_asset'] == config.BTC: #NB: fee_provided could be zero here
pct_fee_provided = float(( D(o['fee_provided_remaining']) / D(o['give_quantity']) ))
else: pct_fee_provided = None
if o['get_asset'] == config.BTC: #NB: fee_required could be zero here
pct_fee_required = float(( D(o['fee_required_remaining']) / D(o['get_quantity']) ))
else: pct_fee_required = None
return pct_fee_provided, pct_fee_required
#filter results by pct_fee_provided and pct_fee_required for BTC pairs as appropriate
filtered_base_bid_orders = []
filtered_base_ask_orders = []
if base_asset == config.BTC or quote_asset == config.BTC:
for o in base_bid_orders:
pct_fee_provided, pct_fee_required = get_o_pct(o)
addToBook = True
if bid_book_min_pct_fee_provided is not None and pct_fee_provided is not None and pct_fee_provided < bid_book_min_pct_fee_provided:
addToBook = False
if bid_book_min_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required < bid_book_min_pct_fee_required:
addToBook = False
if bid_book_max_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required > bid_book_max_pct_fee_required:
addToBook = False
if addToBook: filtered_base_bid_orders.append(o)
for o in base_ask_orders:
pct_fee_provided, pct_fee_required = get_o_pct(o)
addToBook = True
if ask_book_min_pct_fee_provided is not None and pct_fee_provided is not None and pct_fee_provided < ask_book_min_pct_fee_provided:
addToBook = False
if ask_book_min_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required < ask_book_min_pct_fee_required:
addToBook = False
if ask_book_max_pct_fee_required is not None and pct_fee_required is not None and pct_fee_required > ask_book_max_pct_fee_required:
addToBook = False
if addToBook: filtered_base_ask_orders.append(o)
else:
filtered_base_bid_orders += base_bid_orders
filtered_base_ask_orders += base_ask_orders
def make_book(orders, isBidBook):
book = {}
for o in orders:
if o['give_asset'] == base_asset:
if base_asset == config.BTC and o['give_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF:
continue #filter dust orders, if necessary
give_quantity = util_bitcoin.normalize_quantity(o['give_quantity'], base_asset_info['divisible'])
get_quantity = util_bitcoin.normalize_quantity(o['get_quantity'], quote_asset_info['divisible'])
unit_price = float(( D(get_quantity) / D(give_quantity) ))
remaining = util_bitcoin.normalize_quantity(o['give_remaining'], base_asset_info['divisible'])
else:
if quote_asset == config.BTC and o['give_quantity'] <= config.ORDER_BTC_DUST_LIMIT_CUTOFF:
continue #filter dust orders, if necessary
give_quantity = util_bitcoin.normalize_quantity(o['give_quantity'], quote_asset_info['divisible'])
get_quantity = util_bitcoin.normalize_quantity(o['get_quantity'], base_asset_info['divisible'])
unit_price = float(( D(give_quantity) / D(get_quantity) ))
remaining = util_bitcoin.normalize_quantity(o['get_remaining'], base_asset_info['divisible'])
id = "%s_%s_%s" % (base_asset, quote_asset, unit_price)
#^ key = {base}_{bid}_{unit_price}, values ref entries in book
book.setdefault(id, {'unit_price': unit_price, 'quantity': 0, 'count': 0})
book[id]['quantity'] += remaining #base quantity outstanding
book[id]['count'] += 1 #num orders at this price level
book = sorted(book.itervalues(), key=operator.itemgetter('unit_price'), reverse=isBidBook)
#^ convert to list and sort -- bid book = descending, ask book = ascending
return book
#compile into a single book, at volume tiers
base_bid_book = make_book(filtered_base_bid_orders, True)
base_ask_book = make_book(filtered_base_ask_orders, False)
#get stats like the spread and median
if base_bid_book and base_ask_book:
#don't do abs(), as this is "the amount by which the ask price exceeds the bid", so I guess it could be negative
# if there is overlap in the book (right?)
bid_ask_spread = float(( D(base_ask_book[0]['unit_price']) - D(base_bid_book[0]['unit_price']) ))
bid_ask_median = float(( D( max(base_ask_book[0]['unit_price'], base_bid_book[0]['unit_price']) ) - (D(abs(bid_ask_spread)) / 2) ))
else:
bid_ask_spread = 0
bid_ask_median = 0
#compose depth and round out quantities
bid_depth = D(0)
for o in base_bid_book:
o['quantity'] = float(D(o['quantity']))
bid_depth += D(o['quantity'])
o['depth'] = float(D(bid_depth))
bid_depth = float(D(bid_depth))
ask_depth = D(0)
for o in base_ask_book:
o['quantity'] = float(D(o['quantity']))
ask_depth += D(o['quantity'])
o['depth'] = float(D(ask_depth))
ask_depth = float(D(ask_depth))
#compose raw orders
orders = filtered_base_bid_orders + filtered_base_ask_orders
for o in orders:
#add in the blocktime to help makes interfaces more user-friendly (i.e. avoid displaying block
# indexes and display datetimes instead)
o['block_time'] = time.mktime(util.get_block_time(o['block_index']).timetuple()) * 1000
#for orders where BTC is the give asset, also return online status of the user
for o in orders:
if o['give_asset'] == config.BTC:
r = mongo_db.btc_open_orders.find_one({'order_tx_hash': o['tx_hash']})
o['_is_online'] = (r['wallet_id'] in siofeeds.onlineClients) if r else False
else:
o['_is_online'] = None #does not apply in this case
result = {
'base_bid_book': base_bid_book,
'base_ask_book': base_ask_book,
'bid_depth': bid_depth,
'ask_depth': ask_depth,
'bid_ask_spread': bid_ask_spread,
'bid_ask_median': bid_ask_median,
'raw_orders': orders,
'base_asset': base_asset,
'quote_asset': quote_asset
}
return result
@dispatcher.add_method
def get_order_book_simple(asset1, asset2, min_pct_fee_provided=None, max_pct_fee_required=None):
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
result = _get_order_book(base_asset, quote_asset,
bid_book_min_pct_fee_provided=min_pct_fee_provided,
bid_book_max_pct_fee_required=max_pct_fee_required,
ask_book_min_pct_fee_provided=min_pct_fee_provided,
ask_book_max_pct_fee_required=max_pct_fee_required)
return result
@dispatcher.add_method
def get_order_book_buysell(buy_asset, sell_asset, pct_fee_provided=None, pct_fee_required=None):
base_asset, quote_asset = util.assets_to_asset_pair(buy_asset, sell_asset)
bid_book_min_pct_fee_provided = None
bid_book_min_pct_fee_required = None
bid_book_max_pct_fee_required = None
ask_book_min_pct_fee_provided = None
ask_book_min_pct_fee_required = None
ask_book_max_pct_fee_required = None
if base_asset == config.BTC:
if buy_asset == config.BTC:
#if BTC is base asset and we're buying it, we're buying the BASE. we require a BTC fee (we're on the bid (bottom) book and we want a lower price)
# - show BASE buyers (bid book) that require a BTC fee >= what we require (our side of the book)
# - show BASE sellers (ask book) that provide a BTC fee >= what we require
bid_book_min_pct_fee_required = pct_fee_required #my competition at the given fee required
ask_book_min_pct_fee_provided = pct_fee_required
elif sell_asset == config.BTC:
#if BTC is base asset and we're selling it, we're selling the BASE. we provide a BTC fee (we're on the ask (top) book and we want a higher price)
# - show BASE buyers (bid book) that provide a BTC fee >= what we provide
# - show BASE sellers (ask book) that require a BTC fee <= what we provide (our side of the book)
bid_book_max_pct_fee_required = pct_fee_provided
ask_book_min_pct_fee_provided = pct_fee_provided #my competition at the given fee provided
elif quote_asset == config.BTC:
assert base_asset == config.XCP #only time when this is the case
if buy_asset == config.BTC:
#if BTC is quote asset and we're buying it, we're selling the BASE. we require a BTC fee (we're on the ask (top) book and we want a higher price)
# - show BASE buyers (bid book) that provide a BTC fee >= what we require
# - show BASE sellers (ask book) that require a BTC fee >= what we require (our side of the book)
bid_book_min_pct_fee_provided = pct_fee_required
ask_book_min_pct_fee_required = pct_fee_required #my competition at the given fee required
elif sell_asset == config.BTC:
#if BTC is quote asset and we're selling it, we're buying the BASE. we provide a BTC fee (we're on the bid (bottom) book and we want a lower price)
# - show BASE buyers (bid book) that provide a BTC fee >= what we provide (our side of the book)
# - show BASE sellers (ask book) that require a BTC fee <= what we provide
bid_book_min_pct_fee_provided = pct_fee_provided #my compeitition at the given fee provided
ask_book_max_pct_fee_required = pct_fee_provided
result = _get_order_book(base_asset, quote_asset,
bid_book_min_pct_fee_provided=bid_book_min_pct_fee_provided,
bid_book_min_pct_fee_required=bid_book_min_pct_fee_required,
bid_book_max_pct_fee_required=bid_book_max_pct_fee_required,
ask_book_min_pct_fee_provided=ask_book_min_pct_fee_provided,
ask_book_min_pct_fee_required=ask_book_min_pct_fee_required,
ask_book_max_pct_fee_required=ask_book_max_pct_fee_required)
#filter down raw_orders to be only open sell orders for what the caller is buying
open_sell_orders = []
for o in result['raw_orders']:
if o['give_asset'] == buy_asset:
open_sell_orders.append(o)
result['raw_orders'] = open_sell_orders
return result
@dispatcher.add_method
def get_transaction_stats(start_ts=None, end_ts=None):
now_ts = time.mktime(datetime.datetime.utcnow().timetuple())
if not end_ts: #default to current datetime
end_ts = now_ts
if not start_ts: #default to 360 days before the end date
start_ts = end_ts - (360 * 24 * 60 * 60)
stats = mongo_db.transaction_stats.aggregate([
{"$match": {
"block_time": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
}
}},
{"$project": {
"year": {"$year": "$block_time"},
"month": {"$month": "$block_time"},
"day": {"$dayOfMonth": "$block_time"},
"category": 1,
}},
{"$group": {
"_id": {"year": "$year", "month": "$month", "day": "$day", "category": "$category"},
"count": {"$sum": 1},
}}
#{"$sort": SON([("_id.year", pymongo.ASCENDING), ("_id.month", pymongo.ASCENDING), ("_id.day", pymongo.ASCENDING), ("_id.hour", pymongo.ASCENDING), ("_id.category", pymongo.ASCENDING)])},
])
times = {}
categories = {}
stats = [] if not stats['ok'] else stats['result']
for e in stats:
categories.setdefault(e['_id']['category'], {})
time_val = int(time.mktime(datetime.datetime(e['_id']['year'], e['_id']['month'], e['_id']['day']).timetuple()) * 1000)
times.setdefault(time_val, True)
categories[e['_id']['category']][time_val] = e['count']
times_list = times.keys()
times_list.sort()
#fill in each array with all found timestamps
for e in categories:
a = []
for t in times_list:
a.append([t, categories[e][t] if t in categories[e] else 0])
categories[e] = a #replace with array data
#take out to final data structure
categories_list = []
for k, v in categories.iteritems():
categories_list.append({'name': k, 'data': v})
return categories_list
@dispatcher.add_method
def get_wallet_stats(start_ts=None, end_ts=None):
now_ts = time.mktime(datetime.datetime.utcnow().timetuple())
if not end_ts: #default to current datetime
end_ts = now_ts
if not start_ts: #default to 360 days before the end date
start_ts = end_ts - (360 * 24 * 60 * 60)
num_wallets_mainnet = mongo_db.preferences.find({'network': 'mainnet'}).count()
num_wallets_testnet = mongo_db.preferences.find({'network': 'testnet'}).count()
num_wallets_unknown = mongo_db.preferences.find({'network': None}).count()
wallet_stats = []
for net in ['mainnet', 'testnet']:
filters = {
"when": {
"$gte": datetime.datetime.utcfromtimestamp(start_ts)
} if end_ts == now_ts else {
"$gte": datetime.datetime.utcfromtimestamp(start_ts),
"$lte": datetime.datetime.utcfromtimestamp(end_ts)
},
'network': net
}
stats = mongo_db.wallet_stats.find(filters).sort('when', pymongo.ASCENDING)
new_wallet_counts = []
login_counts = []
distinct_login_counts = []
for e in stats:
d = int(time.mktime(datetime.datetime(e['when'].year, e['when'].month, e['when'].day).timetuple()) * 1000)
if 'distinct_login_count' in e: distinct_login_counts.append([ d, e['distinct_login_count'] ])
if 'login_count' in e: login_counts.append([ d, e['login_count'] ])
if 'new_count' in e: new_wallet_counts.append([ d, e['new_count'] ])
wallet_stats.append({'name': '%s: Logins' % net.capitalize(), 'data': login_counts})
wallet_stats.append({'name': '%s: Active Wallets' % net.capitalize(), 'data': distinct_login_counts})
wallet_stats.append({'name': '%s: New Wallets' % net.capitalize(), 'data': new_wallet_counts})
return {
'num_wallets_mainnet': num_wallets_mainnet,
'num_wallets_testnet': num_wallets_testnet,
'num_wallets_unknown': num_wallets_unknown,
'wallet_stats': wallet_stats}
@dispatcher.add_method
def get_owned_assets(addresses):
"""Gets a list of owned assets for one or more addresses"""
result = mongo_db.tracked_assets.find({
'owner': {"$in": addresses}
}, {"_id":0}).sort("asset", pymongo.ASCENDING)
return list(result)
@dispatcher.add_method
def get_asset_pair_market_info(asset1=None, asset2=None, limit=50):
"""Given two arbitrary assets, returns the base asset and the quote asset.
"""
assert (asset1 and asset2) or (asset1 is None and asset2 is None)
if asset1 and asset2:
base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)
pair_info = mongo_db.asset_pair_market_info.find({'base_asset': base_asset, 'quote_asset': quote_asset}, {'_id': 0})
else:
pair_info = mongo_db.asset_pair_market_info.find({}, {'_id': 0}).sort('completed_trades_count', pymongo.DESCENDING).limit(limit)
#^ sort by this for now, may want to sort by a market_cap value in the future
return list(pair_info) or []
@dispatcher.add_method
def get_asset_extended_info(asset):
ext_info = mongo_db.asset_extended_info.find_one({'asset': asset}, {'_id': 0})
return ext_info or False
@dispatcher.add_method
def get_asset_history(asset, reverse=False):
"""
Returns a list of changes for the specified asset, from its inception to the current time.
@param asset: The asset to retrieve a history on
@param reverse: By default, the history is returned in the order of oldest to newest. Set this parameter to True
to return items in the order of newest to oldest.
@return:
Changes are returned as a list of dicts, with each dict having the following format:
* type: One of 'created', 'issued_more', 'changed_description', 'locked', 'transferred', 'called_back'
* 'at_block': The block number this change took effect
* 'at_block_time': The block time this change took effect
* IF type = 'created': Has the following fields, as specified when the asset was initially created: