-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathterra_oracle_vote.py
executable file
·1248 lines (1097 loc) · 43.7 KB
/
terra_oracle_vote.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/python3 -u
# -*- coding: utf-8 -*-
"""
Autovoting script for Terra oracle by B-Harvest
https://github.com/b-harvest/terra_oracle_voter
WARNING : this script is for terra blockchain with version v0.3.0+ only
"""
import hashlib
import json
import logging
import multiprocessing
import concurrent.futures
import os
import subprocess
import time
import functools
import asyncio
# External libraries - installation required:
# pip3 install --user -r requirements.txt
#
import requests
from prometheus_client import start_http_server, Summary, Counter, Gauge, Histogram
import aiohttp
import statistics
from pyband.obi import PyObi
from pyband.client import Client
import binance.client
# User setup
# Slack webhook
slackurl = os.getenv("SLACK_URL", "")
telegram_token = os.getenv("TELEGRAM_TOKEN", "")
telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID", "")
# https://www.alphavantage.co/
alphavantage_key = os.getenv("ALPHAVANTAGE_KEY", "")
# https://python-binance.readthedocs.io/
binance_key = os.getenv("BINANCE_KEY","")
binance_secret = os.getenv("BINANCE_SECRET","")
# no using alphavantage
fx_api_option = os.getenv("FX_API_OPTION", "alphavantage,free_api,band")
# stop oracle when price change exceeds stop_oracle_trigger
stop_oracle_trigger_recent_diverge = float(os.getenv("STOP_ORACLE_RECENT_DIVERGENCE", "999999999999"))
# stop oracle when price change exceeds stop_oracle_trigger
stop_oracle_trigger_exchange_diverge = float(os.getenv("STOP_ORACLE_EXCHANGE_DIVERGENCE", "0.1"))
# vote negative price when bid-ask price is wider than bid_ask_spread_max
bid_ask_spread_max = float(os.getenv("BID_ASK_SPREAD_MAX", "0.05"))
# oracle feeder address
feeder = os.getenv("FEEDER_ADDRESS", "")
# validator address
validator = os.getenv("VALIDATOR_ADDRESS", "")
key_name = os.getenv("KEY_NAME", "")
key_password = os.getenv("KEY_PASSWORD", "").encode()
fee_denom = os.getenv("FEE_DENOM", "ukrw")
fee_gas = os.getenv("FEE_GAS", "250000")
fee_amount = os.getenv("FEE_AMOUNT", "500000")
home_cli = os.getenv("HOME_CLI", "/home/ubuntu/.terracli")
# node to broadcast the txs
node = os.getenv("NODE_RPC", "tcp://127.0.0.1:26657")
# path to terracli binary
terracli = os.getenv("TERRACLI_BIN", "sudo /home/ubuntu/go/bin/terracli")
# lcd to receive swap price information
lcd_address = os.getenv("TERRA_LCD", "https://lcd.terra.dev")
# default coinone weight
coinone_share_default = float(os.getenv("COINONE_SHARE_DEFAULT", "1.0"))
# default bithumb weight
bithumb_share_default = float(os.getenv("BITHUMB_SHARE_DEFAULT", "0"))
# default gopax weight
gopax_share_default = float(os.getenv("GOPAX_SHARE_DEFAULT", "0"))
# default gdac weight
gdac_share_default = float(os.getenv("GDAC_SHARE_DEFAULT", "0"))
price_divergence_alert = os.getenv("PRICE_ALERTS", "false") == "true"
vwma_period = int(os.getenv("VWMA_PERIOD", str(3 * 600))) # in seconds
misses = int(os.getenv("MISSES", "0"))
alertmisses = os.getenv("MISS_ALERTS", "true") == "true"
debug = os.getenv("DEBUG", "false") == "true"
metrics_port = os.getenv("METRICS_PORT", "19000")
band_endpoint = os.getenv("BAND_ENDPOINT", "https://terra-lcd.bandchain.org")
band_luna_price_params = os.getenv("BAND_LUNA_PRICE_PARAMS", "13,1_000_000_000,10,16")
METRIC_MISSES = Gauge("terra_oracle_misses_total", "Total number of oracle misses")
METRIC_HEIGHT = Gauge("terra_oracle_height", "Block height of the LCD node")
METRIC_VOTES = Counter("terra_oracle_votes", "Counter of oracle votes")
METRIC_MARKET_PRICE = Gauge("terra_oracle_market_price", "Last market price", ['denom'])
METRIC_SWAP_PRICE = Gauge("terra_oracle_swap_price", "Last swap price", ['denom'])
METRIC_EXCHANGE_ASK_PRICE = Gauge("terra_oracle_exchange_ask_price", "Exchange ask price", ['exchange', 'denom'])
METRIC_EXCHANGE_MID_PRICE = Gauge("terra_oracle_exchange_mid_price", "Exchange mid price", ['exchange', 'denom'])
METRIC_EXCHANGE_BID_PRICE = Gauge("terra_oracle_exchange_bid_price", "Exchange bid price", ['exchange', 'denom'])
METRIC_OUTBOUND_ERROR = Counter("terra_oracle_request_errors", "Outbound HTTP request error count", ["remote"])
METRIC_OUTBOUND_LATENCY = Histogram("terra_oracle_request_latency", "Outbound HTTP request latency", ["remote"])
# binance client
binance_client = binance.client.Client(binance_key, binance_secret)
# parameters
fx_map = {
"uusd": "USDUSD",
"ukrw": "USDKRW",
"usdr": "USDSDR",
"umnt": "USDMNT",
"ueur": "USDEUR",
"ujpy": "USDJPY",
"ugbp": "USDGBP",
"uinr": "USDINR",
"ucad": "USDCAD",
"uchf": "USDCHF",
"uhkd": "USDHKD",
"uaud": "USDAUD",
"usgd": "USDSGD",
"ucny": "USDCNY",
"uthb": "USDTHB",
}
active_candidate = [
"uusd",
"ukrw",
"usdr",
"umnt",
"ueur",
"ujpy",
"ugbp",
"uinr",
"ucad",
"uchf",
"uhkd",
"uaud",
"usgd",
"ucny",
"uthb",
]
# hardfix the active set. does not care about stop_oracle_trigger_recent_diverge
hardfix_active_set = [
"uusd",
"ukrw",
"usdr",
"umnt",
"ueur",
"ujpy",
"ugbp",
"uinr",
"ucad",
"uchf",
"uhkd",
"uaud",
"usgd",
"ucny",
"uthb",
]
# denoms for abstain votes. it will vote abstain for all denoms in this list.
abstain_set = [
#"uusd",
#"ukrw",
#"usdr",
#"umnt"
]
chain_id = os.getenv("CHAIN_ID", "columbus-4")
round_block_num = 5.0
# set last update time
last_height = 0
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
logger = logging.root
# By default, python-requests does not use a timeout. We need to specify
# a timeout on each call to ensure we never get stuck in network IO.
http_timeout = 4
# Separate timeout for alerting calls
alert_http_timeout = 4
# Global requests session for HTTP/1.1 keepalive
# (unfortunately, the timeout cannot be set globally)
session = requests.session()
# Be friendly to the APIs we use and specify a user-agent
session.headers['User-Agent'] = "bharvest-oracle-voter/0 (+https://github.com/b-harvest/terra_oracle_voter)"
# Start metrics server in a background thread
start_http_server(int(metrics_port))
def time_request(remote):
"""Returns a decorator that measures execution time."""
return METRIC_OUTBOUND_LATENCY.labels(remote).time()
@time_request('telegram')
def telegram(message):
if not telegram_token:
return
try:
requests.post(
"https://api.telegram.org/bot{}/sendMessage".format(telegram_token),
json={
'chat_id': telegram_chat_id,
'text': message
},
timeout=alert_http_timeout
)
except:
logging.exception("Error while sending telegram alert")
@time_request('slack')
def slack(message):
if not slackurl:
return
try:
requests.post(slackurl, json={"text": message}, timeout=alert_http_timeout)
except:
METRIC_OUTBOUND_ERROR.labels('slack').inc()
logging.exception("Error while sending Slack alert")
@time_request('lcd')
def get_current_misses():
try:
result = session.get(
"{}/oracle/voters/{}/miss".format(lcd_address, validator),
timeout=http_timeout).json()
misses = int(result["result"])
height = int(result["height"])
return misses, height
except:
METRIC_OUTBOUND_ERROR.labels('lcd').inc()
logging.exception("Error in get_current_misses")
return 0, 0
@time_request('lcd')
def get_current_prevotes(denom):
try:
return session.get(
"{}/oracle/denoms/{}/prevotes".format(lcd_address, denom),
timeout=http_timeout).json()
except:
METRIC_OUTBOUND_ERROR.labels('lcd').inc()
logging.exception("Error in get_current_prevotes")
return False
@time_request('lcd')
def get_current_votes(denom):
try:
result = session.get(
"{}/oracle/denoms/{}/votes".format(lcd_address, denom),
timeout=http_timeout).json()
return result
except:
METRIC_OUTBOUND_ERROR.labels('lcd').inc()
logging.exception("Error in get_current_votes")
return False
@time_request('lcd')
def get_my_current_prevotes():
try:
result = session.get(
"{}/oracle/voters/{}/prevotes".format(lcd_address, validator),
timeout=http_timeout).json()
result_vote = []
for vote in result["result"]:
if str(vote["voter"]) == str(validator):
result_vote.append(vote)
return result_vote
except:
METRIC_OUTBOUND_ERROR.labels('lcd').inc()
logging.exception("Error in get_my_current_prevotes")
return False
# get latest block info
@time_request('lcd')
def get_latest_block():
err_flag = False
try:
result = session.get("{}/blocks/latest".format(lcd_address), timeout=http_timeout).json()
latest_block_height = int(result["block"]["header"]["height"])
latest_block_time = result["block"]["header"]["time"]
except:
METRIC_OUTBOUND_ERROR.labels('lcd').inc()
logger.exception("Error in get_latest_block")
err_flag = True
latest_block_height = None
latest_block_time = None
return err_flag, latest_block_height, latest_block_time
'''Option, receive sdr with paid service switch.
# get real sdr rates
@time_request('imf')
def get_sdr_rate():
err_flag = False
try:
# get sdr
url = "https://www.imf.org/external/np/fin/data/rms_five.aspx?tsvflag=Y"
data = session.get(url, timeout=http_timeout).text
result_sdr_rate = next(filter(lambda x: x.startswith("U.S. dollar"),
data.splitlines())).split('\t')[2]
except:
METRIC_OUTBOUND_ERROR.labels('imf').inc()
logging.exception("Error in get_sdr_rate")
err_flag = True
result_sdr_rate = None
return err_flag, result_sdr_rate
'''
# get currency rate async def
async def fx_for(symbol_to):
try:
async with aiohttp.ClientSession() as async_session:
async with async_session.get(
"https://www.alphavantage.co/query",
timeout=http_timeout,
params={
'function': 'CURRENCY_EXCHANGE_RATE',
'from_currency': 'USD',
'to_currency': symbol_to,
'apikey': alphavantage_key
}
) as response:
api_result = await response.json(content_type=None)
return api_result
except:
print("for_fx_error")
# get currency rate async def
async def fx_for_free(symbol_to):
try:
async with aiohttp.ClientSession() as async_session:
async with async_session.get(
"https://api.exchangerate.host/latest",
timeout=http_timeout,
params={
'base': 'USD',
'symbols': symbol_to
}
) as response:
api_result = await response.json(content_type=None)
return api_result
except:
print("for_fx_error")
# get real fx rates
@time_request('alphavantage')
def get_fx_rate():
err_flag = False
try:
# get currency rate
symbol_list = [
"KRW",
"EUR",
"CNY",
"JPY",
"XDR",
"MNT",
"GBP",
"INR",
"CAD",
"CHF",
"HKD",
"AUD",
"SGD",
"THB"
]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
futures = [fx_for(symbol_lists) for symbol_lists in symbol_list]
api_result = loop.run_until_complete(asyncio.gather(*futures))
result_real_fx = {
"USDUSD": 1.0,
"USDKRW": 1.0,
"USDEUR": 1.0,
"USDCNY": 1.0,
"USDJPY": 1.0,
"USDSDR": 1.0,
"USDMNT": 1.0,
"USDGBP": 1.0,
"USDINR": 1.0,
"USDCAD": 1.0,
"USDCHF": 1.0,
"USDHKD": 1.0,
"USDAUD": 1.0,
"USDSGD": 1.0,
"USDTHB": 1.0,
}
list_number = 0
for symbol in symbol_list:
if symbol == "XDR":
symbol = "SDR"
result_real_fx["USD"+symbol] = float(
api_result[list_number]["Realtime Currency Exchange Rate"]["5. Exchange Rate"])
list_number = list_number +1
except:
METRIC_OUTBOUND_ERROR.labels('alphavantage').inc()
logger.exception("Error in get_fx_rate")
err_flag = True
result_real_fx = None
return err_flag, result_real_fx
#"fx_for" has been merged.
@time_request('band-fx')
def get_fx_rate_from_band():
err_flag = False
result_real_fx = None
try:
result_real_fx = {"USDUSD": 1.0}
symbol_list = ["KRW","EUR","CNY","JPY","XDR","MNT","GBP","INR","CAD","CHF","HKD","AUD","SGD","THB"]
prices = requests.post(
f"{band_endpoint}/oracle/request_prices",
json={"symbols": symbol_list, "min_count": 10,"ask_count": 16}
).json()['result']
for (symbol, price) in zip(symbol_list,prices):
if symbol == "XDR":
symbol = "SDR"
result_real_fx["USD"+symbol] = int(price['multiplier'],10) / int(price['px'],10)
except:
METRIC_OUTBOUND_ERROR.labels('band-fx').inc()
logger.exception("Error in def get_fx_rate_from_band")
err_flag = True
return err_flag, result_real_fx
# get real fx rates
@time_request('exchangerateapi')
def get_fx_rate_free():
err_flag = False
try:
# get currency rate
symbol_list = [
"KRW",
"EUR",
"CNY",
"JPY",
"XDR",
"MNT",
"GBP",
"INR",
"CAD",
"CHF",
"HKD",
"AUD",
"SGD",
"THB"
]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
futures = [fx_for_free(symbol_lists) for symbol_lists in symbol_list]
api_result = loop.run_until_complete(asyncio.gather(*futures))
result_real_fx = {
"USDUSD": 1.0,
"USDKRW": 1.0,
"USDEUR": 1.0,
"USDCNY": 1.0,
"USDJPY": 1.0,
"USDSDR": 1.0,
"USDMNT": 1.0,
"USDGBP": 1.0,
"USDINR": 1.0,
"USDCAD": 1.0,
"USDCHF": 1.0,
"USDHKD": 1.0,
"USDAUD": 1.0,
"USDSGD": 1.0,
"USDTHB": 1.0
}
list_number = 0
for symbol in symbol_list:
fx_symbol="USD"+symbol
if symbol == "XDR":
fx_symbol = "USDSDR"
result_real_fx[fx_symbol] = float(
api_result[list_number]["rates"][symbol])
list_number = list_number +1
except:
METRIC_OUTBOUND_ERROR.labels('exchangerateapi').inc()
logger.exception("Error in get_fx_rate_free")
err_flag = True
result_real_fx = None
return err_flag, result_real_fx
# combine all fx rate from sources
def combine_fx(res_fxs):
fx_combined = {
"USDUSD":[],
"USDKRW":[],
"USDEUR":[],
"USDCNY":[],
"USDJPY":[],
"USDSDR":[],
"USDMNT":[],
"USDGBP":[],
"USDINR":[],
"USDCAD":[],
"USDCHF":[],
"USDHKD":[],
"USDAUD":[],
"USDSGD":[],
"USDTHB":[],
}
all_fx_err_flag = True
for res_fx in res_fxs:
err_flag, fx = res_fx.result()
all_fx_err_flag = all_fx_err_flag and err_flag
if not err_flag:
for key in fx_combined:
if key in fx:
fx_combined[key].append(fx[key])
for key in fx_combined:
if len(fx_combined[key]) > 0:
fx_combined[key] = statistics.median(fx_combined[key])
else:
fx_combined[key] = None
all_fx_err_flag = True
return all_fx_err_flag, fx_combined
# get binance luna usdt price
def get_binance_luna_price():
err_flag = False
try:
client = binance_client
if client is None:
client = binance.client.Client(binance_key, binance_secret)
avg_price = client.get_avg_price(symbol='LUNAUSDT')
s1 = json.dumps(avg_price)
response_dict = json.loads(s1)
luna_price = response_dict["price"]
logger.exception(luna_price)
except:
logger.exception("Error in get_binance_luna_price")
err_flag = True
luna_price = None
return err_flag, luna_price
# get coinone luna krw price
@time_request('coinone')
def get_coinone_luna_price():
err_flag = False
try:
if vwma_period > 1:
url = "https://api.coinone.co.kr/trades/?currency=luna"
luna_result = session.get(url, timeout=http_timeout).json()["completeOrders"]
hist_price = []
sum_price_volume = 0
sum_volume = 0
now_time = float(time.time())
for row in luna_result:
if now_time - float(row['timestamp']) < vwma_period:
sum_price_volume += float(row["price"]) * float(row["qty"])
sum_volume += float(row["qty"])
else:
break
askprice = sum_price_volume / sum_volume
bidprice = sum_price_volume / sum_volume
else:
url = "https://api.coinone.co.kr/orderbook/?currency=luna&format=json"
luna_result = session.get(url, timeout=http_timeout).json()
askprice = float(luna_result["ask"][0]["price"])
bidprice = float(luna_result["bid"][0]["price"])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "coinone",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
METRIC_OUTBOUND_ERROR.labels('coinone').inc()
logger.exception("Error in get_coinone_luna_price")
err_flag = True
luna_price = None
luna_base = None
luna_midprice_krw = None
return err_flag, luna_price, luna_base, luna_midprice_krw
# get bithumb luna krw price
@time_request('bithumb')
def get_bithumb_luna_price():
err_flag = False
try:
# get luna/krw
url = "https://api.bithumb.com/public/orderbook/luna_krw"
luna_result = session.get(url, timeout=http_timeout).json()["data"]
askprice = float(luna_result["asks"][0]["price"])
bidprice = float(luna_result["bids"][0]["price"])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "bithumb",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
METRIC_OUTBOUND_ERROR.labels('bithumb').inc()
logger.exception("Error in get_bithumb_luna_price")
err_flag = True
luna_price = None
luna_base = None
luna_midprice_krw = None
return err_flag, luna_price, luna_base, luna_midprice_krw
# get gopax luna krw price
@time_request('gopax')
def get_gopax_luna_price():
err_flag = False
try:
# get luna/krw
url = "https://api.gopax.co.kr/trading-pairs/LUNA-KRW/book"
luna_result = session.get(url, timeout=http_timeout).json()
askprice = float(luna_result["ask"][0][1])
bidprice = float(luna_result["bid"][0][1])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "gopax",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
METRIC_OUTBOUND_ERROR.labels('gopax').inc()
logger.exception("Error in get_gopax_luna_price")
err_flag = True
# gopax_share is set to zero if an error occurs
luna_price = 0
luna_base = 0
luna_midprice_krw = 0
return err_flag, luna_price, luna_base, luna_midprice_krw
# get gdac luna krw price
@time_request('gdac')
def get_gdac_luna_price():
err_flag = False
try:
# get luna/krw
url = "https://partner.gdac.com/v0.4/public/orderbook?pair=LUNA%2FKRW"
luna_result = session.get(url, timeout=http_timeout).json()
askprice = float(luna_result["ask"][0]["price"])
bidprice = float(luna_result["bid"][0]["price"])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "gdac",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
METRIC_OUTBOUND_ERROR.labels('gdax').inc()
logger.exception("Error in get_gdac_luna_price")
err_flag = True
# gdac_share is set to zero if an error occurs
luna_price = 0
luna_base = 0
luna_midprice_krw = 0
return err_flag, luna_price, luna_base, luna_midprice_krw
# get band luna krw price
@time_request('band-luna')
def get_band_luna_price():
binance, coinone, bithumb, gdac, gopax = None, None, None, None, None
try:
oracle_script_id, multiplier, min_count, ask_count = [int(param, 10) for param in band_luna_price_params.split(",")]
bandcli = Client(band_endpoint)
schema = bandcli.get_oracle_script(oracle_script_id).schema
obi = PyObi(schema)
result = obi.decode_output(
bandcli.get_latest_request(
oracle_script_id,
obi.encode_input({
"multiplier": multiplier
}),
min_count,
ask_count
).result.response_packet_data.result
)
abms = []
exchanges = ["binance", "huobipro", "coinone", "bithumb", "gdac", "gopax"]
for (order_book,ex) in zip(result['prices'], exchanges):
abm = None
if order_book['ask'] > 0 and order_book['bid'] > 0 and order_book['mid'] > 0:
luna_price = {
"base_currency": "ukrw",
"exchange": f"band_{ex}",
"askprice": order_book['ask']/multiplier,
"bidprice": order_book['bid']/multiplier,
"midprice": order_book['mid']/multiplier
}
luna_base = "USDKRW"
luna_midprice_krw = order_book['mid']/multiplier
abm = (luna_price, luna_base, luna_midprice_krw)
abms.append(abm)
binance, _, coinone, bithumb, gdac, gopax = abms
except:
METRIC_OUTBOUND_ERROR.labels('band-luna').inc()
logger.exception("Error in get_band_luna_price")
return binance, coinone, bithumb, gdac, gopax
# get swap price
@time_request('lcd')
def get_swap_price():
err_flag = False
try:
result = session.get(
"{}/oracle/denoms/exchange_rates".format(lcd_address),
timeout=http_timeout).json()
except:
METRIC_OUTBOUND_ERROR.labels('lcd').inc()
logger.exception("Error in get_swap_price")
result = {"result":[]}
err_flag = True
return err_flag, result
def get_hash(salt, price, denom, validator):
m = hashlib.sha256()
m.update("{}:{}:{}:{}".format(salt, price, denom, validator).encode('utf-8'))
result = m.hexdigest()[:40]
return result
def get_salt(string):
b_string = str(string).encode('utf-8')
return str(hashlib.sha256(b_string).hexdigest())[:4]
def broadcast_messages(messages):
tx_json = {
"type": "core/StdTx",
"value": {
"msg": messages,
"fee": {
"amount": [
{
"denom": fee_denom,
"amount": fee_amount
}
],
"gas": fee_gas
},
"signatures": [],
"memo": ""
}
}
logger.info("Signing...")
json.dump(tx_json, open("tx_oracle_prevote.json", 'w'))
cmd_output = subprocess.check_output([
terracli,
"tx", "sign", "tx_oracle_prevote.json",
"--from", key_name,
"--chain-id", chain_id,
"--home", home_cli,
"--node", node
], input=key_password + b'\n' + key_password + b'\n').decode()
tx_json_signed = json.loads(cmd_output)
json.dump(tx_json_signed, open("tx_oracle_prevote_signed.json", 'w'))
logger.info("Broadcasting...")
cmd_output = subprocess.check_output([
terracli,
"tx", "broadcast", "tx_oracle_prevote_signed.json",
"--output", "json",
"--from", key_name,
"--chain-id", chain_id,
"--home", home_cli,
"--node", node,
], input=key_password + b'\n' + key_password + b'\n').decode()
return json.loads(cmd_output)
def broadcast_prevote(hash):
logger.info("Prevoting...")
return broadcast_messages([
{
"type": "oracle/MsgExchangeRatePrevote",
"value": {
"hash": str(hash[denom]),
"denom": str(denom),
"feeder": feeder,
"validator": validator
}
} for denom in active
])
def broadcast_all(vote_price, vote_salt, prevote_hash):
logger.info("Prevoting and voting...")
return broadcast_messages(
[
{
"type": "oracle/MsgExchangeRateVote",
"value": {
"exchange_rate": str(vote_price[denom]),
"salt": str(vote_salt[denom]),
"denom": denom,
"feeder": feeder,
"validator": validator
}
} for denom in active
] + [
{
"type": "oracle/MsgExchangeRatePrevote",
"value": {
"hash": str(prevote_hash[denom]),
"denom": str(denom),
"feeder": feeder,
"validator": validator
}
} for denom in active
])
main_err_flag = True
while main_err_flag:
latest_block_err_flag, latest_block_height, latest_block_time = get_latest_block()
if latest_block_err_flag == False:
height = latest_block_height
if height > last_height:
main_err_flag = False
last_height = height
time.sleep(1)
last_prevoted_round = 0
last_active = []
last_hash = []
while True:
main_err_flag = True
while main_err_flag:
latest_block_err_flag, latest_block_height, latest_block_time = get_latest_block()
if latest_block_err_flag == False:
height = latest_block_height
if height > last_height:
main_err_flag = False
last_height = height
time.sleep(1)
current_round = int(float(height - 1) / round_block_num)
next_height_round = int(float(height) / round_block_num)
num_blocks_till_next_round = (current_round + 1) * round_block_num - height
logger.debug("current_round: %d", current_round)
logger.debug("next_height_round: %d", next_height_round)
logger.debug("last_prevoted_round: %d", last_prevoted_round)
logger.debug("height: %d", height)
logger.debug("num_blocks_till_next_round: %d", num_blocks_till_next_round)
if next_height_round > last_prevoted_round and (
num_blocks_till_next_round == 0 or num_blocks_till_next_round > 3):
# Get external data
all_err_flag = False
ts = time.time()
fx_api_collection = {
"alphavantage": get_fx_rate,
"free_api": get_fx_rate_free,
"band": get_fx_rate_from_band
}
with concurrent.futures.ThreadPoolExecutor() as executor:
res_swap = executor.submit(get_swap_price)
res_fxs = []
for fx_key in fx_api_option.split(","):
res_fxs.append( executor.submit(fx_api_collection[fx_key]))
#res_sdr = executor.submit(get_sdr_rate) sdr receive Option
res_coinone = executor.submit(get_coinone_luna_price)
res_bithumb = executor.submit(get_bithumb_luna_price)
res_gopax = executor.submit(get_gopax_luna_price)
res_gdac = executor.submit(get_gdac_luna_price)
res_band = executor.submit(get_band_luna_price)
res_binance = executor.submit(get_binance_luna_price)
def metrics_for_result(exchange, result):
if result:
METRIC_EXCHANGE_ASK_PRICE.labels(exchange, result['base_currency']).set(result['askprice'])
METRIC_EXCHANGE_BID_PRICE.labels(exchange, result['base_currency']).set(result['bidprice'])
METRIC_EXCHANGE_MID_PRICE.labels(exchange, result['base_currency']).set(result['midprice'])
metrics_for_result('coinone', res_coinone.result()[1])
metrics_for_result('bithumb', res_bithumb.result()[1])
metrics_for_result('gopax', res_gopax.result()[1])
metrics_for_result('res_gdac', res_gdac.result()[1])
for rb in res_band.result():
if rb:
metrics_for_result(rb[0]['exchange'], rb[0])
# Get active set of denoms
swap_price_err_flag, swap_price = res_swap.result()
if swap_price["result"] is None:
swap_price["result"] = []
if len(hardfix_active_set) == 0:
active = []
for denom in swap_price["result"]:
active.append(denom["denom"])
else:
active = hardfix_active_set
logger.info("Active set: {}".format(active))
# combine fx from all sources
fx_err_flag, real_fx = combine_fx(res_fxs)
#sdr_err_flag, sdr_rate = res_sdr.result() sdr receive Option
coinone_err_flag, coinone_luna_price, coinone_luna_base, coinone_luna_midprice_krw = res_coinone.result()
bithumb_err_flag, bithumb_luna_price, bithumb_luna_base, bithumb_luna_midprice_krw = res_bithumb.result()
gopax_err_flag, gopax_luna_price, gopax_luna_base, gopax_luna_midprice_krw = res_gopax.result()
gdac_err_flag, gdac_luna_price, gdac_luna_base, gdac_luna_midprice_krw = res_gdac.result()
binance_err_flag, binance_luna_price = res_binance.result()
# extract backup luna price from band
binance_backup, coinone_backup, bithumb_backup, gdac_backup, gopax_backup = res_band.result()
coinone_share = coinone_share_default
bithumb_share = bithumb_share_default
gopax_share = gopax_share_default
gdac_share = gdac_share_default
'''sdr receive Option
if fx_err_flag or sdr_err_flag or coinone_err_flag or swap_price_err_flag:
all_err_flag = True
'''
if fx_err_flag:
all_err_flag = True
if coinone_err_flag or swap_price_err_flag:
if coinone_backup is None:
all_err_flag = True
else:
coinone_luna_price, coinone_luna_base, coinone_luna_midprice_krw = coinone_backup
if bithumb_err_flag:
if bithumb_backup is None:
bithumb_share = 0
else:
bithumb_luna_price, bithumb_luna_base, bithumb_luna_midprice_krw = bithumb_backup
if gopax_err_flag:
if gdac_backup is None:
gopax_share = 0
else:
gopax_luna_price, gopax_luna_base, gopax_luna_midprice_krw = gopax_backup
if gdac_err_flag:
if gopax_backup is None:
gdac_share = 0
else:
gdac_luna_price, gdac_luna_base, gdac_luna_midprice_krw = gdac_backup
if binance_err_flag:
if binance_backup is not None:
_, luna_base, band_luna_price = binance_backup
binance_luna_price = band_luna_price / real_fx[luna_base] # convert to USD
if not all_err_flag:
#real_fx["USDSDR"] = float(sdr_rate) sdr receive Option