def fetch_hut(hut_id):
assert hut_id
headers = {'x-api-key': settings.API_KEY}
huts_index = HutIndexPage.objects.first()
try:
rh = requests.get('%s/%s/detail' % (settings.API_HUTS_BASE_URL, hut_id), headers=headers, timeout=settings.API_TIMEOUT)
except requests.exceptions.RequestException as e:
logger.exception(str(e))
else:
if rh.status_code == 200:
rh_json = rh.json()
try:
hut = HutPage.objects.get(asset_id=rh_json['assetId'])
except HutPage.DoesNotExist:
hut = HutPage(title=rh_json['name'], seo_title=rh_json['name'], asset_id=rh_json['assetId'])
for key, value in HutPage.API_FIELDS_MAPPING.items():
setattr(hut, value, rh_json[key])
if hut.pk is None:
huts_index.add_child(instance=hut)
else:
hut.save()
else:
logger.error("Failed hut details request with status %s, %s", str(rh.status_code), rh.json()['message'])
python类API_KEY的实例源码
def handle(self, *args, **options):
from history.poloniex import poloniex
from history.models import Price
import time
poo = poloniex(settings.API_KEY, settings.API_SECRET)
price = poo.returnTicker()
for ticker in price.keys():
this_price = price[ticker]['last']
this_volume = price[ticker]['quoteVolume']
the_str = ticker + ',' + str(time.time()) + ',' + this_price + ", " + this_volume
print("(pp)"+the_str)
p = Price()
p.price = this_price
p.volume = this_volume
p.lowestask = price[ticker]['lowestAsk']
p.highestbid = price[ticker]['highestBid']
p.symbol = ticker
p.created_on_str = str(p.created_on)
p.save()
def handle(self, *args, **options):
from history.poloniex import poloniex
from history.models import Price
import time
poo = poloniex(settings.API_KEY, settings.API_SECRET)
price = poo.returnTicker()
for ticker in price.keys():
this_price = price[ticker]['last']
this_volume = price[ticker]['quoteVolume']
the_str = ticker + ',' + str(time.time()) + ',' + this_price + ", " + this_volume
print("(pp)"+the_str)
p = Price()
p.price = this_price
p.volume = this_volume
p.lowestask = price[ticker]['lowestAsk']
p.highestbid = price[ticker]['highestBid']
p.symbol = ticker
p.created_on_str = str(p.created_on)
p.save()
def __init__(self):
self.client_id = settings.API_CLIENT
self.key = settings.API_KEY
self.api_version = "1"
self.msg_type = "sms"
self.api_url = "http://api.openapi.io/ppurio/" + \
"{api_version}/message/{msg_type}/{client_id}/".format(
api_version=self.api_version,
msg_type=self.msg_type,
client_id=self.client_id,
)
self.header = {
"x-waple-authorization": self.key,
}
def fetch_all_huts():
headers = {'x-api-key': settings.API_KEY}
subtasks = []
try:
r = requests.get(settings.API_HUTS_BASE_URL, headers=headers, timeout=settings.API_TIMEOUT)
except requests.exceptions.RequestException as e:
logger.exception(str(e))
if r.status_code == 200:
for h in r.json():
subtasks.append(fetch_hut.s(h['assetId']))
else:
logger.error("Failed huts request with status %s, %s", str(r.status_code), r.json()['message'])
results = group(subtasks)() # in parallel
results.get()
def handle(self, *args, **options):
from history.poloniex import poloniex
poo = poloniex(settings.API_KEY, settings.API_SECRET)
now = get_utc_unixtime()
r = poo.returnDepositHistory(0, now)
deposits = r['deposits'] + r['withdrawals']
for d in deposits:
print(d)
currency = d['currency']
amount = float(d['amount']) * (-1 if 'withdrawalNumber' in d.keys() else 1)
timestamp = d['timestamp']
txid = d['withdrawalNumber'] if 'withdrawalNumber' in d.keys() else d['txid']
status = d['status']
created_on = datetime.datetime.fromtimestamp(timestamp)
try:
d = Deposit.objects.get(txid=txid)
except:
d = Deposit()
d.symbol = currency
d.amount = amount
d.txid = txid
d.type = 'deposit' if amount > 0 else 'withdrawal'
d.status = status
d.created_on = created_on
d.modified_on = created_on
d.created_on_str = datetime.datetime.strftime(
created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M')
d.save()
def handle(self, *args, **options):
from history.poloniex import poloniex
# hit API
poo = poloniex(settings.API_KEY, settings.API_SECRET)
balances = poo.returnBalances()
# record balances
deposited_amount_btc, deposited_amount_usd = get_deposit_balance()
with transaction.atomic():
for ticker in balances:
val = float(balances[ticker]['available']) + float(balances[ticker]['onOrders'])
if val > 0.0001:
exchange_rate_coin_to_btc = get_exchange_rate_to_btc(ticker)
exchange_rate_btc_to_usd = get_exchange_rate_btc_to_usd()
btc_val = exchange_rate_coin_to_btc * val
usd_val = exchange_rate_btc_to_usd * btc_val
b = Balance(symbol=ticker, coin_balance=val, btc_balance=btc_val,
exchange_to_btc_rate=exchange_rate_coin_to_btc, usd_balance=usd_val,
exchange_to_usd_rate=exchange_rate_coin_to_btc,
deposited_amount_btc=deposited_amount_btc if ticker == 'BTC' else 0.00,
deposited_amount_usd=deposited_amount_usd if ticker == 'BTC' else 0.00)
b.save()
for b in Balance.objects.filter(date_str='0'):
# django timezone stuff , FML
b.date_str = datetime.datetime.strftime(b.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M')
b.save()
# normalize trade recommendations too. merp
for tr in Trade.objects.filter(created_on_str=''):
# django timezone stuff , FML
tr.created_on_str = datetime.datetime.strftime(
tr.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M')
tr.save()
def clean_api_key(self):
if self.cleaned_data['api_key'] != settings.API_KEY:
raise forms.ValidationError("Wrong api key")
def handle(self, *args, **options):
from history.poloniex import poloniex
poo = poloniex(settings.API_KEY, settings.API_SECRET)
now = get_utc_unixtime()
r = poo.returnDepositHistory(0, now)
deposits = r['deposits'] + r['withdrawals']
for d in deposits:
print(d)
currency = d['currency']
amount = float(d['amount']) * (-1 if 'withdrawalNumber' in d.keys() else 1)
timestamp = d['timestamp']
txid = d['withdrawalNumber'] if 'withdrawalNumber' in d.keys() else d['txid']
status = d['status']
created_on = datetime.datetime.fromtimestamp(timestamp)
try:
d = Deposit.objects.get(txid=txid)
except:
d = Deposit()
d.symbol = currency
d.amount = amount
d.txid = txid
d.type = 'deposit' if amount > 0 else 'withdrawal'
d.status = status
d.created_on = created_on
d.modified_on = created_on
d.created_on_str = datetime.datetime.strftime(
created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M')
d.save()
def handle(self, *args, **options):
from history.poloniex import poloniex
# hit API
poo = poloniex(settings.API_KEY, settings.API_SECRET)
balances = poo.returnBalances()
# record balances
deposited_amount_btc, deposited_amount_usd = get_deposit_balance()
with transaction.atomic():
for ticker in balances:
val = float(balances[ticker]['available']) + float(balances[ticker]['onOrders'])
if val > 0.0001:
exchange_rate_coin_to_btc = get_exchange_rate_to_btc(ticker)
exchange_rate_btc_to_usd = get_exchange_rate_btc_to_usd()
btc_val = exchange_rate_coin_to_btc * val
usd_val = exchange_rate_btc_to_usd * btc_val
b = Balance(symbol=ticker, coin_balance=val, btc_balance=btc_val,
exchange_to_btc_rate=exchange_rate_coin_to_btc, usd_balance=usd_val,
exchange_to_usd_rate=exchange_rate_coin_to_btc,
deposited_amount_btc=deposited_amount_btc if ticker == 'BTC' else 0.00,
deposited_amount_usd=deposited_amount_usd if ticker == 'BTC' else 0.00)
b.save()
for b in Balance.objects.filter(date_str='0'):
# django timezone stuff , FML
b.date_str = datetime.datetime.strftime(b.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M')
b.save()
# normalize trade recommendations too. merp
for tr in Trade.objects.filter(created_on_str=''):
# django timezone stuff , FML
tr.created_on_str = datetime.datetime.strftime(
tr.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M')
tr.save()
def handle(self, *args, **options):
from history.poloniex import poloniex
from history.models import Price
import time
poo = poloniex(settings.API_KEY, settings.API_SECRET)
if settings.MAKE_TRADES:
time.sleep(40)
for t in Trade.objects.filter(created_on__lt=datetime.datetime.now(), status='scheduled'):
# bid right below the lowest ask, or right above the highest bid so that our orders get filled
action = t.type
price = Price.objects.filter(symbol=t.symbol).order_by('-created_on').first()
if action == 'sell':
rate = price.lowestask * 0.999
else:
rate = price.highestbid * 1.001
t.price = rate
if action == 'buy':
try:
response = {} if not settings.MAKE_TRADES else poo.buy(t.symbol, rate, t.amount)
except Exception as e:
print_and_log('(st)act_upon_recommendation:buy: ' + str(e))
elif action == 'sell':
try:
response = {} if not settings.MAKE_TRADES else poo.sell(t.symbol, rate, t.amount)
except Exception as e:
print_and_log('(st)act_upon_recommendation:sell: ' + str(e))
t.response = response
t.orderNumber = response.get('orderNumber', '')
t.status = 'error' if response.get('error', False) else 'open'
t.calculatefees()
t.calculate_exchange_rates()
t.save()
ot = t.opposite_trade
ot.opposite_price = rate
ot.net_profit = ((rate * t.amount) - (ot.price * ot.amount) if action == 'sell' else
(ot.price * ot.amount) - (rate * t.amount)) - ot.fee_amount - t.fee_amount
ot.calculate_profitability_exchange_rates()
ot.save()
def handle(self, *args, **options):
# setup
self.poo = poloniex(settings.API_KEY, settings.API_SECRET)
self.setup()
print_and_log("(t){} ---- ****** STARTING TRAINERS ******* ".format(str(datetime.datetime.now())))
self.get_traders()
print_and_log("(t){} ---- ****** DONE TRAINING ALL TRAINERS ******* ".format(str(datetime.datetime.now())))
while True:
# TLDR -- which NNs should run at this granularity?
should_run = []
recommendations = dict.fromkeys(range(0, len(self.predictors)))
for i in range(0, len(self.predictor_configs)):
config = self.predictor_configs[i]
if (int(get_utc_unixtime() / 60) % config['granularity'] == 0 and datetime.datetime.now().second < 1):
should_run.append(i)
# TLDR -- update open orders bfore placing new ones
if len(should_run) > 0:
self.handle_open_orders()
# TLDR -- run the NNs specified at this granularity
for i in should_run:
config = self.predictor_configs[i]
recommend = self.run_predictor(i)
recommendations[i] = recommend
time.sleep(1)
# TLDR - act upon recommendations
for i in range(0, len(recommendations)):
recommendation = recommendations[i]
config = self.predictor_configs[i]
if recommendation is not None:
print_and_log("(t)recommendation {} - {} : {}".format(i, str(config['name']), recommendation))
self.act_upon_recommendation(i, recommendation)
# TLDR - cleanup and stats
if len(should_run) > 0:
pct_buy = round(100.0 * sum(recommendations[i] == 'BUY' for
i in recommendations) / len(recommendations))
pct_sell = round(100.0 * sum(recommendations[i] == 'SELL' for
i in recommendations) / len(recommendations))
print_and_log("(t)TLDR - {}% buy & {}% sell: {}".format(pct_buy, pct_sell, recommendations))
print_and_log("(t) ******************************************************************************* ")
print_and_log("(t) portfolio is {}".format(self.get_portfolio_breakdown_pct()))
print_and_log("(t) ******************************************************************************* ")
print_and_log("(t) {} ..... waiting again ..... ".format(str(datetime.datetime.now())))
print_and_log("(t) ******************************************************************************* ")
time.sleep(1)
def on_message(self, message):
data = json.loads(message)
if data['type'] == 'open_dialog':
if not Thread.objects.filter(
id=data['thread_id'],
participants__id=self.user_id
).exists():
self.close()
return
self.thread_id = data['thread_id']
return
elif data['type'] == 'message':
url = settings.SEND_MESSAGE_API_URL
body = urlencode({
"message_text": data['text'].encode("utf-8"),
"api_key": settings.API_KEY,
"sender_id": self.user_id,
"thread_id": self.thread_id,
})
elif data['type'] == 'message_status':
url = settings.UPDATE_MESSAGE_STATUS_API_URL
body = urlencode({
"api_key": settings.API_KEY,
"sender_id": self.user_id,
"thread_id": self.thread_id,
})
elif data['type'] == 'person_status':
pub_client.publish("thread_{}_messages".format(self.thread_id), json.dumps({
"type": "person_status",
"thread_id": self.thread_id,
"user_id": self.user_id,
"username": self.username,
"typing": data['typing'],
}))
return
else:
return
http_client = tornado.httpclient.AsyncHTTPClient()
request = tornado.httpclient.HTTPRequest(
url,
method="POST",
body=body
)
http_client.fetch(request, self.handle_request)
def handle(self, *args, **options):
from history.poloniex import poloniex
from history.models import Price
import time
poo = poloniex(settings.API_KEY, settings.API_SECRET)
if settings.MAKE_TRADES:
time.sleep(40)
for t in Trade.objects.filter(created_on__lt=datetime.datetime.now(), status='scheduled'):
# bid right below the lowest ask, or right above the highest bid so that our orders get filled
action = t.type
price = Price.objects.filter(symbol=t.symbol).order_by('-created_on').first()
if action == 'sell':
rate = price.lowestask * 0.999
else:
rate = price.highestbid * 1.001
t.price = rate
if action == 'buy':
try:
response = {} if not settings.MAKE_TRADES else poo.buy(t.symbol, rate, t.amount)
except Exception as e:
print_and_log('(st)act_upon_recommendation:buy: ' + str(e))
elif action == 'sell':
try:
response = {} if not settings.MAKE_TRADES else poo.sell(t.symbol, rate, t.amount)
except Exception as e:
print_and_log('(st)act_upon_recommendation:sell: ' + str(e))
t.response = response
t.orderNumber = response.get('orderNumber', '')
t.status = 'error' if response.get('error', False) else 'open'
t.calculatefees()
t.calculate_exchange_rates()
t.save()
ot = t.opposite_trade
ot.opposite_price = rate
ot.net_profit = ((rate * t.amount) - (ot.price * ot.amount) if action == 'sell' else
(ot.price * ot.amount) - (rate * t.amount)) - ot.fee_amount - t.fee_amount
ot.calculate_profitability_exchange_rates()
ot.save()
def handle(self, *args, **options):
# setup
self.poo = poloniex(settings.API_KEY, settings.API_SECRET)
self.setup()
print_and_log("(t){} ---- ****** STARTING TRAINERS ******* ".format(str(datetime.datetime.now())))
self.get_traders()
print_and_log("(t){} ---- ****** DONE TRAINING ALL TRAINERS ******* ".format(str(datetime.datetime.now())))
while True:
# TLDR -- which NNs should run at this granularity?
should_run = []
recommendations = dict.fromkeys(range(0, len(self.predictors)))
for i in range(0, len(self.predictor_configs)):
config = self.predictor_configs[i]
if (int(get_utc_unixtime() / 60) % config['granularity'] == 0 and datetime.datetime.now().second < 1):
should_run.append(i)
# TLDR -- update open orders bfore placing new ones
if len(should_run) > 0:
self.handle_open_orders()
# TLDR -- run the NNs specified at this granularity
for i in should_run:
config = self.predictor_configs[i]
recommend = self.run_predictor(i)
recommendations[i] = recommend
time.sleep(1)
# TLDR - act upon recommendations
for i in range(0, len(recommendations)):
recommendation = recommendations[i]
config = self.predictor_configs[i]
if recommendation is not None:
print_and_log("(t)recommendation {} - {} : {}".format(i, str(config['name']), recommendation))
self.act_upon_recommendation(i, recommendation)
# TLDR - cleanup and stats
if len(should_run) > 0:
pct_buy = round(100.0 * sum(recommendations[i] == 'BUY' for
i in recommendations) / len(recommendations))
pct_sell = round(100.0 * sum(recommendations[i] == 'SELL' for
i in recommendations) / len(recommendations))
print_and_log("(t)TLDR - {}% buy & {}% sell: {}".format(pct_buy, pct_sell, recommendations))
print_and_log("(t) ******************************************************************************* ")
print_and_log("(t) portfolio is {}".format(self.get_portfolio_breakdown_pct()))
print_and_log("(t) ******************************************************************************* ")
print_and_log("(t) {} ..... waiting again ..... ".format(str(datetime.datetime.now())))
print_and_log("(t) ******************************************************************************* ")
time.sleep(1)