Skip to content

Instantly share code, notes, and snippets.

@h3lls
Last active January 6, 2018 09:42
Show Gist options
  • Save h3lls/5e097d3bab4e10803b859a63ac3270ba to your computer and use it in GitHub Desktop.
Save h3lls/5e097d3bab4e10803b859a63ac3270ba to your computer and use it in GitHub Desktop.
Make sure you also run: pip install python-binance and pip install flask for the web version
livecoin:
enabled: False
apikey: LIVECOINAPIKEY
sign: LIVECOINSIG
max_bid: 0.00011
poloniex:
enabled: False
apikey: POLONIEXAPIKEY
sign: POLONIEXSIG
binance:
enabled: False
apikey: BINANCEAPIKEY
secret: BINANCESECRET
discord:
token: DISCORD TOKEN (Get this from local storage "Ctrl"+"Shift"+"I")
listen_channels:
- LIST OF CHANNEL IDS
- EACH CHANNEL
<html>
<head>
<title>Show Me the Monay</title>
<style>
body {
margin: 0;
background-color: #555555;
}
table.steelBlueCols {
border: 4px solid #555555;
background-color: #555555;
width: 100%;
text-align: left;
border-collapse: collapse;
}
div.steelBlueCols {
font-family: opensans, sans-serif, btcglyph;
border: 4px solid #777777;
background-color: #555555;
width: 100%;
text-align: left;
border-collapse: collapse;
}
.divTable.steelBlueCols .divTableCell, .divTable.steelBlueCols .divTableHead {
border: 1px solid #777777;
padding: 5px 10px;
}
.divTable.steelBlueCols .divTableBody .divTableCell {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.divTable.steelBlueCols .divTableCell:nth-child(even) {
background: #333333;
}
.steelBlueCols .tableFootStyle {
font-size: 13px;
}
.steelBlueCols .tableFootStyle .links {
text-align: right;
}
.steelBlueCols .tableFootStyle .links a{
display: inline-block;
background: #FFFFFF;
color: #398AA4;
padding: 2px 8px;
border-radius: 5px;
}
.steelBlueCols.outerTableFooter {
border-top: none;
}
.steelBlueCols.outerTableFooter .tableFootStyle {
padding: 3px 5px;
}
h1 {
font-family: opensans, sans-serif, btcglyph;
font-size: 16px;
margin-top: 10px;
margin-left: 20px;
color: #555555;
text-shadow: 0 0 5px #111111;
}
/* DivTable.com */
.divTable{ display: table; }
.divTableRow { display: table-row; }
.divTableHeading { display: table-header-group;}
.divTableCell, .divTableHead { display: table-cell;}
.divTableHeading { display: table-header-group;}
.divTableFoot { display: table-footer-group;}
.divTableBody { display: table-row-group;}
.finance { font-family: opensans, sans-serif, btcglyph; }
.dataTable
{
font-family: opensans, sans-serif, btcglyph;
font-size: 12px;
font-weight: bold;
color: #888888;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function reloadLivecoin()
{
$("#livecoin_1").html("Loading, please wait...");
$.get( "/livecoin", function( data ) {
$( "#livecoin_1" ).html( data );
});
// $("#livecoin_1").load("/livecoin");
}
function reloadPoloniex()
{
$("#poloniex_1").html("Loading, please wait...");
$.get( "/poloniex", function( data ) {
$( "#poloniex_1" ).html( data );
});
// $("#poloniex_1").queue(function() {
// $("#poloniex_1").load("/poloniex");
// });
}
function reloadBinance()
{
$("#binance_1").html("Loading, please wait...");
$.get( "/binance", function( data ) {
$( "#binance_1" ).html( data );
});
// $("#binance_1").queue(function() {
// $("#binance_1").load("/binance");
// });
}
setInterval('reloadLivecoin()', 300000);
setInterval('reloadPoloniex()', 300000);
setInterval('reloadBinance()', 300000);
</script>
</head>
<body>
<h1>Open Orders and Balances</h1>
<div class="divTable steelBlueCols">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell">Livecoin</div>
<div id="livecoin_1" class="divTableCell">cell2_1</div>
</div>
<div class="divTableRow">
<div class="divTableCell">Poloniex</div>
<div id="poloniex_1" class="divTableCell">cell2_2</div>
</div>
<div class="divTableRow">
<div class="divTableCell">Binance</div>
<div id="binance_1" class="divTableCell">cell2_3</div>
</div>
</div>
</div>
<script>
reloadLivecoin();
reloadBinance();
reloadPoloniex();
</script>
</body>
</html>
import logging
import time
import requests
import hmac
import hashlib
import pprint
from collections import OrderedDict
# for compatibility with python 2 and 3
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
logger = logging.getLogger(__name__)
METHOD_MAPPING = {
'coinInfo': ['info', False, 'GET'],
'ticker': ['exchange', False, 'GET'],
'last_trades': ['exchange', False, 'GET'],
'order_book': ['exchange', False, 'GET'],
'all/order_book': ['exchange', False, 'GET'],
'maxbid_minask': ['exchange', False, 'GET'],
'restrictions': ['exchange', False, 'GET'],
'trades': ['exchange', True, 'GET'],
'client_orders': ['exchange', True, 'GET'],
'order': ['exchange', True, 'GET'],
'commission': ['exchange', True, 'GET'],
'commissionCommonInfo': ['exchange', True, 'GET'],
'buylimit': ['exchange', True, 'POST'],
'selllimit': ['exchange', True, 'POST'],
'buymarket': ['exchange', True, 'POST'],
'sellmarket': ['exchange', True, 'POST'],
'cancellimit': ['exchange', True, 'POST'],
'balances': ['payment', True, 'GET'],
'balance': ['payment', True, 'GET'],
'history/transactions': ['payment', True, 'GET'],
'history/size': ['payment', True, 'GET'],
'get/address': ['payment', True, 'GET'],
'out/coin': ['payment', True, 'GET'],
'out/payeer': ['payment', True, 'GET'],
'out/capitalist': ['payment', True, 'GET'],
'out/advcah': ['payment', True, 'GET'],
'out/card': ['payment', True, 'GET'],
'out/okpay': ['payment', True, 'GET'],
'out/perfectmoney': ['payment', True, 'GET'],
'voucher/make': ['payment', True, 'GET'],
'voucher/amount': ['payment', True, 'GET'],
'voucher/redeem': ['payment', True, 'GET'],
}
class Livecoin(object):
"""
Used for requesting Bittrex with API key and API secret
"""
def __init__(self, api_key, api_secret):
self.api_key = str(api_key) if api_key is not None else ''
self.api_secret = str(api_secret) if api_secret is not None else ''
self.method_mapping = set(METHOD_MAPPING)
def api_query(self, method, options=None):
"""
Queries Bittrex with given method and options
:param method: Query method for getting info
:type method: str
:param options: Extra options for query
:type options: dict
:return: JSON response from Bittrex
:rtype : dict
"""
if not options:
options = {}
nonce = str(int(time.time() * 1000))
base_url = 'https://api.livecoin.net'
request_url = ''
#print("Method: " + method)
namespace, needs_api_key, http_method = METHOD_MAPPING[method]
request_url = '/'.join([base_url, namespace, method])
if http_method == 'GET' and options:
request_url += '?' + urlencode(options)
signature = hmac.new(self.api_secret.encode(), urlencode(options).encode(), hashlib.sha256).hexdigest().upper()
if needs_api_key:
headers = {'Api-key': self.api_key, "Sign": signature, "Content-type": "application/x-www-form-urlencoded"}
else:
headers = {"Content-type": "application/x-www-form-urlencoded"}
#print(request_url)
if http_method == 'GET':
ret = requests.get(request_url, headers=headers)
elif http_method == 'POST':
ret = requests.post(request_url, data=options, headers=headers)
#print(ret)
#print("Result of {0} via {1} = {2}".format(
# method, request_url, pprint.pformat(ret.json())))
# logger.info("Result of {0}={1}".format(method, ret))
return ret.json()
def get_coininfo(self):
"""
Used to get all supported currencies at Bittrex
along with other meta data.
:return: Supported currencies info in JSON
:rtype : dict
"""
return self.api_query('coinInfo')
def get_ticker(self, market):
"""
Used to get the current tick values for a market.
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:return: Current values for given market in JSON
:rtype : dict
"""
return self.api_query('ticker', {
'currencyPair': market
}
)
return self.api_query('getticker', {'market': market})
def get_all_tickers(self):
"""
Summarize all markets.
:return: Current values for all markets in JSON
:rtype : list of dict
"""
return self.api_query('ticker')
def get_last_trades(self, currency_pair, in_minutes='false', type='false'):
"""
Retrieve information on the latest transactions for a currency pair.
:param str currency_pair: Which currency pair. E.g. LTC/BTC
:param bool in_minutes: if false (the default), then supply in hours.
:param str type: defaults to false. But can be BUY or SELL.
:return: Summaries of active exchanges in JSON
:rtype : list of dict
"""
return self.api_query('last_trades', {
'currencyPair': market,
'minutesOrHour': in_minutes,
'type': type
})
def get_orderbook(self, market, group_by_price=False, depth=20):
"""
Used to get retrieve the orderbook for a given market
:param market: String literal for the market (ex: LTC/BTC)
:type market: str
:param group_by_price: group by price.
:type depth_type: bool
:param depth: how deep of an order book to retrieve.
:type depth: int
:return: Orderbook of market in JSON
:rtype : dict
"""
return self.api_query('order_book', {
'currencyPair': market,
'groupByPrice': group_by_price,
'depth': depth})
def client_orders(self, currencyPair=None, openClosed="ALL", issuedFrom=None, issuedTo=None, startRow=0, endRow=2147483646):
"""
To retrieve full information on your trade-orders for the specified currency pair. You can optionally limit the response to orders of a certain type (open, closed, etc.)
:param str currency_pair: Which currency pair. E.g. LTC/BTC
:param openClosed str: Order type. Possible values: ALL - All orders OPEN - Open orders CLOSED - Executed or cancelled orders CANCELLED - Cancelled orders NOT_CANCELLED - All orders except cancelled ones PARTIALLY - partially closed orders Default value: ALL
:return: Orderbook of market in JSON
:rtype : list of dict
"""
options = {
'openClosed': openClosed
}
# if currencyPair is not None:
# options['currencyPair'] = currencyPair
# if issuedFrom is not None:
# options['issuedFrom'] = issuedFrom
# if issuedTo is not None:
# options['issuedTo'] = issuedTo
return self.api_query('client_orders', options)
def get_maxbid_minask(self, market=None):
"""
Returns maximum bid and minimum ask optionally
in a specific orderbook.
:param market: String literal for the market (ex: LTC/BTC)
:type market: str
:return: Market history in JSON
:rtype : dict
"""
if market:
options = dict(currencyPair=market)
return self.api_query('maxbid_minask', options)
return self.api_query('maxbid_minask')
def buy_market(self, currency_pair, quantity):
"""
Used to place a buy order in a specific market. Use buymarket to
place market orders. Make sure you have the proper permissions
set on your API keys for this call to work
/market/buymarket
:param currency_pair: String literal for the currency_pair (ex: BTC/LTC)
:type currency_pair: str
:param quantity: The amount to purchase
:type quantity: float
:return:
:rtype : dict
"""
return self.api_query('buymarket', {'currencyPair': currency_pair, 'quantity': quantity})
def buy_limit(self, currency_pair, quantity, price):
"""
Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
/market/buylimit
:param currency_pair: String literal for the currencyPair (ex: BTC/LTC)
:type currency_pair: str
:param quantity: The amount to purchase
:type quantity: float
:param price: The price at which to place the order.
This is not needed for market orders
:type price: float
:return:
:rtype : dict
"""
return self.api_query('buylimit', {'currencyPair': currency_pair, 'quantity': quantity, 'price': price})
def sell_market(self, currency_pair, quantity, price):
"""
Used to place a sell order in a specific market. Use sellmarket to place
market orders. Make sure you have the proper permissions set on your
API keys for this call to work
/exchange/sellmarket
:param currency_pair: String literal for the currencyPair (ex: BTC/LTC)
:type currency_pair: str
:param quantity: The amount to purchase
:type quantity: float
:param price: The price at which to place the order.
This is not needed for market orders
:type price: float
:return:
:rtype : dict
"""
return self.api_query('sellmarket', {'currencyPair': currency_pair, 'quantity': quantity, 'price': price})
def sell_limit(self, currency_pair, quantity, price):
"""
Used to place a sell order in a specific market. Use selllimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
/market/selllimit
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param price: The price at which to place the order.
This is not needed for market orders
:type price: float
:return:
:rtype : dict
"""
data = OrderedDict(sorted([('currencyPair', currency_pair),('price', price),('quantity', quantity)]))
return self.api_query('selllimit', data)
def cancel(self, uuid):
"""
Used to cancel a buy or sell order
/market/cancel
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict
"""
return self.api_query('cancel', {'uuid': uuid})
def get_open_orders(self, market):
"""
Get all orders that you currently have opened. A specific market can be requested
/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
:rtype : dict
"""
return self.api_query('getopenorders', {'market': market})
def get_balances(self):
"""
Used to retrieve all balances from your account
/account/getbalances
:return: Balances info in JSON
:rtype : dict
"""
return self.api_query('balances', {})
def get_balance(self, currency):
"""
Used to retrieve the balance from your account for a specific currency
/account/getbalance
:param currency: String literal for the currency (ex: LTC)
:type currency: str
:return: Balance info in JSON
:rtype : dict
"""
return self.api_query('balance', {'currency': currency})
def get_deposit_address(self, currency):
"""
Used to generate or retrieve an address for a specific currency
/account/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict
"""
return self.api_query('getdepositaddress', {'currency': currency})
def withdraw(self, currency, quantity, address):
"""
Used to withdraw funds from your account
/account/withdraw
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
:param address: The address where to send the funds.
:type address: str
:return:
:rtype : dict
"""
return self.api_query('withdraw', {'currency': currency, 'quantity': quantity, 'address': address})
def get_order(self, uuid):
"""
Used to get an order from your account
/account/getorder
:param uuid: The order UUID to look for
:type uuid: str
:return:
:rtype : dict
"""
return self.api_query('getorder', {'uuid': uuid})
def get_order_history(self, market = ""):
"""
Used to retrieve your order history
/account/getorderhistory
:param market: Bittrex market identifier (i.e BTC-DOGE)
:type market: str
:return:
:rtype : dict
"""
return self.api_query('getorderhistory', {"market": market})
def get_withdrawal_history(self, currency = ""):
"""
Used to retrieve your withdrawal history
/account/getwithdrawalhistory
:param currency: String literal for the currency (ie. BTC) (defaults to all)
:type currency: str
:return:
:rtype : dict
"""
return self.api_query('getwithdrawalhistory', {"currency": currency})
def get_deposit_history(self, currency = ""):
"""
Used to retrieve your deposit history
/account/getdeposithistory
:param currency: String literal for the currency (ie. BTC) (defaults to all)
:type currency: str
:return:
:rtype : dict
"""
return self.api_query('getdeposithistory', {"currency": currency})
from urllib.parse import urlencode
from urllib.request import urlopen, Request
import json
import time
import hmac,hashlib
def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
return time.mktime(time.strptime(datestr, format))
class Poloniex:
def __init__(self, APIKey, Secret):
self.APIKey = APIKey
self.Secret = Secret
def post_process(self, before):
after = before
# Add timestamps if there isnt one but is a datetime
if('return' in after):
if(isinstance(after['return'], list)):
for x in xrange(0, len(after['return'])):
if(isinstance(after['return'][x], dict)):
if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
return after
def api_query(self, command, req={}):
if(command == "returnTicker" or command == "return24Volume"):
ret = urlopen(Request('https://poloniex.com/public?command=' + command))
return json.loads(ret.read())
elif(command == "returnOrderBook"):
ret = urlopen(Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif(command == "returnMarketTradeHistory"):
ret = urlopen(Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
else:
req['command'] = command
req['nonce'] = int(time.time()*1000)
post_data = urlencode(req).encode()
sign = hmac.new(self.Secret.encode(), post_data, hashlib.sha512).hexdigest().upper()
headers = {
'Sign': sign,
'Key': self.APIKey
}
ret = urlopen(Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def returnTicker(self):
return self.api_query("returnTicker")
def return24Volume(self):
return self.api_query("return24Volume")
def returnOrderBook (self, currencyPair):
return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
def returnMarketTradeHistory (self, currencyPair):
return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
# Returns all of your balances.
# Outputs:
# {"BTC":"0.59098578","LTC":"3.31117268", ... }
def returnBalances(self):
return self.api_query('returnBalances')
def returnCompleteBalances(self):
return self.api_query('returnCompleteBalances')
# Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
# Inputs:
# currencyPair The currency pair e.g. "BTC_XCP"
# Outputs:
# orderNumber The order number
# type sell or buy
# rate Price the order is selling or buying at
# Amount Quantity of order
# total Total value of order (price * quantity)
def returnOpenOrders(self,currencyPair):
return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
# Returns your trade history for a given market, specified by the "currencyPair" POST parameter
# Inputs:
# currencyPair The currency pair e.g. "BTC_XCP"
# Outputs:
# date Date in the form: "2014-02-19 03:44:59"
# rate Price the order is selling or buying at
# amount Quantity of order
# total Total value of order (price * quantity)
# type sell or buy
def returnTradeHistory(self,currencyPair):
return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
# Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
# Inputs:
# currencyPair The curreny pair
# rate price the order is buying at
# amount Amount of coins to buy
# Outputs:
# orderNumber The order number
def buy(self,currencyPair,rate,amount):
return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
# Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
# Inputs:
# currencyPair The curreny pair
# rate price the order is selling at
# amount Amount of coins to sell
# Outputs:
# orderNumber The order number
def sell(self,currencyPair,rate,amount):
return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
# Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber".
# Inputs:
# currencyPair The curreny pair
# orderNumber The order number to cancel
# Outputs:
# succes 1 or 0
def cancel(self,currencyPair,orderNumber):
return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
# Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."}
# Inputs:
# currency The currency to withdraw
# amount The amount of this coin to withdraw
# address The withdrawal address
# Outputs:
# response Text containing message about the withdrawal
def withdraw(self, currency, amount, address):
return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
import argparse
from flask import Flask
from livecoin.livecoin import Livecoin
from poloniex import Poloniex
from binance.client import Client
from binance.enums import *
import yaml
app = Flask(__name__)
apikey = None
sign = None
token = None
listen_channels = []
# Use the minimum until this thing is tested.
MAX_BID = 0.00011
parser = argparse.ArgumentParser(description='Show Exchange Orders and Balances')
parser.add_argument('--balances', '-b', action='store_true', help='Show balances in addition to open orders')
parser.add_argument('--nolivecoin', '-l', action='store_true', help='Disable Livecoin exchange')
parser.add_argument('--nopoloniex', '-p', action='store_true', help='Disable Poloniex exchange')
parser.add_argument('--nobinance', '-i', action='store_true', help='Disable Binance exchange')
args = parser.parse_args()
with open('config.yml', 'r') as f:
doc = yaml.load(f)
apikey = doc['livecoin']['apikey']
sign = doc['livecoin']['sign']
livecoin_enabled = doc['livecoin']['enabled']
p_apikey = doc['poloniex']['apikey']
p_sign = doc['poloniex']['sign']
poloniex_enabled = doc['poloniex']['enabled']
b_api_key = doc['binance']['apikey']
b_api_secret = doc['binance']['secret']
binance_enabled = doc['binance']['enabled']
MAX_BID = doc['livecoin']['max_bid']
token = doc['discord']['token']
listen_channels = doc['discord']['listen_channels']
if args.nolivecoin:
livecoin_enabled = False
if args.nopoloniex:
poloniex_enabled = False
if args.nobinance:
binance_enabled = False
def format_order(order_type, symbol, quantity, balance, price, last, high, low):
green = "#227722"
red = "#884444"
order = "<tr><td>{:s}:</td><td>{:s}</td><td>Quantity:</td><td>{:.8f}<td>Balance:</td><td>{:s}</td></tr>".format(order_type, symbol, float(quantity), balance)
order += "<tr><td></td><td>price:</td><td style='color: {:s};'>{:.8f}</td><td style='padding-left: 10px;'>high:</td><td>{:.8f}</td></tr><tr><td></td><td>last:</td><td style='color: {:s};'>{:.8f}</td><td style='padding-left: 10px;'>low:</td><td>{:.8f}</td></tr>".format(green, float(price), float(high), red, float(last), float(low))
return order
def get_binance_output(binance):
output = "<table class='dataTable'>"
prices = binance.get_all_tickers()
for price in prices:
if price['symbol'].endswith('BTC'):
orders = binance.get_open_orders(symbol=price['symbol'])
for order in orders:
order_type = order['type']
currency = order['symbol']
output += format_order(order['side'], order['symbol'], order['origQty'], '', order['price'], price['price'], 0, 0)
if args.balances == False:
output += "<tr><td></br></td></tr>"
# This isn't included in the prices so we have to add it so it fetches the balance
prices.append({'symbol': 'BTCBTC'})
for price in prices:
if price['symbol'].endswith('BTC'):
symbol = price['symbol'][:-3]
balance = binance.get_asset_balance(asset=symbol)
if float(balance['free']) + float(balance['locked']) > 0:
output += "<tr><td>Balance for</td><td>{:s}</td><td>Free:</td><td>{:s}</td><td>Locked:</td><td>{:s}</td></tr>".format(symbol.rjust(5, ' '), balance['free'].rjust(13, ' '), balance['locked'].rjust(13, ' '))
output += "</table>"
return output
def get_livecoin_output(livecoin):
output = "<table class='dataTable'>"
balances = livecoin.get_balances()
orders = livecoin.client_orders(openClosed="OPEN")
printed_balances = []
for order in orders['data']:
currency = order['currencyPair']
order_type = order['type']
price = order['price']
available_balance = 0
for balance in balances:
if balance['currency'] == currency.split('/')[0] and balance['type'] == 'total':
printed_balances.append(currency.split('/')[0])
available_balance = balance['value']
ticker = livecoin.get_ticker(currency)
output += format_order(order_type, currency, available_balance, '', price, ticker['last'], ticker['high'], ticker['low'])
# Opposite day, please forgive me
if args.balances == False:
output += "<tr><td></br></td></tr>"
for balance in balances:
if balance['currency'] not in printed_balances and balance['value'] > 0.0 and balance['type'] == 'total':
if balance['currency'] not in ['USD', 'BTC']:
ticker = livecoin.get_ticker(balance['currency'] + "/BTC")
output += "<tr><td>Balance for</td><td>{:s}:</td><td>{:.8f}</td><td>Last:</td><td>{:.8f}</td><td>Value in BTC:</td><td>{:.8f}</td></tr>".format(balance['currency'], balance['value'], ticker['last'], ticker['last'] * balance['value'])
else:
output += "<tr><td>Balance for</td><td>{:s}:</td><td>{:.8f}</td></tr>".format(balance['currency'], balance['value'])
output += "</table>"
return output
def get_poloniex_data(poloniex):
output = "<table class='dataTable'>"
available_balances = poloniex.returnCompleteBalances()
tickers = poloniex.returnTicker()
orders = poloniex.returnOpenOrders('all')
printed_balances = []
for currencyPair, order_val in orders.items():
for order in order_val:
order_type = order['type']
price = order['rate']
balance = available_balances[currencyPair.split('_')[1]]
printed_balances.append(currencyPair.split('_')[1])
for ticker_currency, ticker in tickers.items():
if ticker_currency == currencyPair:
output += format_order(order_type, currencyPair, balance['onOrders'], balance['available'], price, ticker['last'], ticker['high24hr'], ticker['low24hr'])
if args.balances == False:
output += "<tr><td></br></td></tr>"
for currency, balance in available_balances.items():
if currency not in printed_balances and float(balance['btcValue']) > 0:
if currency in ['BTC', 'USD']:
output += "<tr><td>Balance for</td><td>{:s}</td><td>Avail:</td><td>{:s}</td><td>OnOrder:</td><td>{:s}</td><td>Value in BTC:</td><td>{:s}</td></tr>".format(currency, balance['available'], balance['onOrders'], balance['btcValue'])
else:
output += "<tr><td>Balance for</td><td>{:s}</td><td>Avail:</td><td>{:s}</td><td>OnOrder:</td><td>{:s}</td><td>Last:</td><td>{}</td><td>Value in BTC:</td><td>{:s}</td></tr>".format(currency, balance['available'], balance['onOrders'], tickers["BTC_" + currency]['last'], balance['btcValue'])
output += "</table>"
return output
@app.route('/')
def index():
with open("index.html", 'r') as f:
return f.read()
@app.route('/livecoin')
def get_livecoin():
if livecoin_enabled:
livecoin = Livecoin(apikey, sign)
return get_livecoin_output(livecoin)
else:
return "Livecoin Disabled"
@app.route('/poloniex')
def get_poloniex():
if poloniex_enabled:
poloniex = Poloniex(p_apikey, p_sign)
return get_poloniex_data(poloniex)
else:
return "Poloniex Disabled"
@app.route('/binance')
def get_binance():
if binance_enabled:
binance = Client(b_api_key, b_api_secret)
return get_binance_output(binance)
else:
return "Binance Disabled"
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', threaded=True)
quit()
import argparse
from livecoin.livecoin import Livecoin
from poloniex import Poloniex
from binance.client import Client
import yaml
apikey = None
sign = None
token = None
listen_channels = []
# Use the minimum until this thing is tested.
MAX_BID = 0.00011
parser = argparse.ArgumentParser(description='Show Exchange Orders and Balances')
parser.add_argument('--balances', '-b', action='store_true', help='Show balances in addition to open orders')
parser.add_argument('--nolivecoin', '-l', action='store_true', help='Disable Livecoin exchange')
parser.add_argument('--nopoloniex', '-p', action='store_true', help='Disable Poloniex exchange')
parser.add_argument('--nobinance', '-i', action='store_true', help='Disable Binance exchange')
args = parser.parse_args()
with open('config.yml', 'r') as f:
doc = yaml.load(f)
apikey = doc['livecoin']['apikey']
sign = doc['livecoin']['sign']
livecoin_enabled = doc['livecoin']['enabled']
p_apikey = doc['poloniex']['apikey']
p_sign = doc['poloniex']['sign']
poloniex_enabled = doc['poloniex']['enabled']
b_api_key = doc['binance']['apikey']
b_api_secret = doc['binance']['secret']
binance_enabled = doc['binance']['enabled']
MAX_BID = doc['livecoin']['max_bid']
token = doc['discord']['token']
listen_channels = doc['discord']['listen_channels']
if args.nolivecoin:
livecoin_enabled = False
if args.nopoloniex:
poloniex_enabled = False
if args.nobinance:
binance_enabled = False
def show_binance(binance):
print ("\n-----==== BINANCE ====-----")
prices = binance.get_all_tickers()
for price in prices:
if price['symbol'].endswith('BTC'):
orders = binance.get_open_orders(symbol=price['symbol'])
for order in orders:
order_type = order['type']
currency = order['symbol']
print("{:s} of {:s} Balance: {:s}\n price: {:s}\n last: {:s}".format(
order['side'], order['symbol'], order['origQty'], order['price'], price['price']))
if args.balances:
return
# This isn't included in the prices so we have to add it so it fetches the balance
prices.append({'symbol': 'BTCBTC'})
for price in prices:
if price['symbol'].endswith('BTC'):
symbol = price['symbol'][:-3]
balance = binance.get_asset_balance(asset=symbol)
if float(balance['free']) + float(balance['locked']) > 0:
print("Balance for {:s} Free: {:s} Locked: {:s}".format(symbol.rjust(5, ' '), balance['free'].rjust(13, ' '), balance['locked'].rjust(13, ' ')))
def show_livecoin(livecoin):
print ("\n-----==== LIVECOIN ====-----")
balances = livecoin.get_balances()
orders = livecoin.client_orders(openClosed="OPEN")
printed_balances = []
for order in orders['data']:
currency = order['currencyPair']
order_type = order['type']
price = order['price']
available_balance = 0
for balance in balances:
if balance['currency'] == currency.split('/')[0] and balance['type'] == 'total':
printed_balances.append(currency.split('/')[0])
available_balance = balance['value']
ticker = livecoin.get_ticker(currency)
print("{:s} of {:s} Balance: {:.8f}\thigh: {:.8f}\tlow: {:.8f}\n price: {:.8f}\n last: {:.8f}".format(order_type, currency, available_balance, ticker['high'], ticker['low'], price, ticker['last']))
if args.balances:
return
for balance in balances:
if balance['currency'] not in printed_balances and balance['value'] > 0.0 and balance['type'] == 'total':
if balance['currency'] not in ['USD', 'BTC']:
ticker = livecoin.get_ticker(balance['currency'] + "/BTC")
print("Balance for {:s}: {:.8f} Last: {:.8f} Value in BTC: {:.8f}".format(balance['currency'], balance['value'], ticker['last'], ticker['last'] * balance['value']))
else:
print("Balance for {:s}: {:.8f}".format(balance['currency'], balance['value']))
def show_poloniex(poloniex):
print ("\n-----==== POLONIEX ====-----")
available_balances = poloniex.returnCompleteBalances()
tickers = poloniex.returnTicker()
orders = poloniex.returnOpenOrders('all')
printed_balances = []
for currencyPair, order_val in orders.items():
for order in order_val:
order_type = order['type']
price = order['rate']
balance = available_balances[currencyPair.split('_')[1]]
printed_balances.append(currencyPair.split('_')[1])
for ticker_currency, ticker in tickers.items():
if ticker_currency == currencyPair:
print("{:s} of {:s} Avail: {:s} OnOrder: {:s}\thigh: {:s}\tlow: {:s}\n price: {:s}\n last: {:s}".format(order_type, currencyPair, balance['available'], balance['onOrders'], ticker['high24hr'], ticker['low24hr'], price, ticker['last']))
if args.balances:
return
for currency, balance in available_balances.items():
if currency not in printed_balances and float(balance['btcValue']) > 0:
if currency in ['BTC', 'USD']:
print("Balance for {:s} Avail: {:s} OnOrder: {:s} Value in BTC: {:s}".format(currency, balance['available'], balance['onOrders'], balance['btcValue']))
else:
print("Balance for {:s} Avail: {:s} OnOrder: {:s} Last: {} Value in BTC: {:s}".format(currency, balance['available'], balance['onOrders'], tickers["BTC_" + currency]['last'], balance['btcValue']))
if livecoin_enabled:
livecoin = Livecoin(apikey, sign)
show_livecoin(livecoin)
if poloniex_enabled:
poloniex = Poloniex(p_apikey, p_sign)
show_poloniex(poloniex)
if binance_enabled:
binance = Client(b_api_key, b_api_secret)
show_binance(binance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment