In [1]:
import os
import sys
pwd = os.getcwd()
sys.path.append(os.path.join(pwd, '..', '..'))
from server.utils import load_config
from server import db
from sqlalchemy.orm import sessionmaker
import json
conf_dir = os.path.abspath(os.path.join(pwd, '..', '..', 'config', 'base.yaml'))
config = load_config(conf_dir)
engine = db.sync_engine(config['postgres'])
Session = sessionmaker(bind=engine)
session = Session()
In [2]:
start_date_filter = '2018-02-09 00:00'
end_date_filter = '2018-02-09 23:59'
from server.trade.MultiplePairs import MultiplePairs
In [3]:
from server.trade.player import run_script
import logging
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
run_script(
strategy_class = MultiplePairs,
start_date = start_date_filter,
end_date = end_date_filter,
conf = config,
constructor = {
'fee': 1
}
)
In [4]:
class PairInfo(object):
def __init__(self, pair):
print('Pair {}'.format(pair))
self.pair = pair
self.buy_dir, self.sell_dir = pair.split("_")
self.order_dict = {
'sell': [],
'buy': []
}
self.rate_dict = {
'date': [],
'sell_price': [],
'buy_price': []
}
def get_orders(self):
return self.order_dict['sell'] + self.order_dict['buy']
def as_dict(row):
item = row._asdict().copy()
return item
def get_fee(delta):
return (1 + (delta*(0.2 + 0)/100))
def calc_money(order):
if order['is_sell']:
buy_delta = -1
sell_delta = 1
fee_delta = -1
else:
buy_delta = 1
sell_delta = -1
fee_delta = 1
return {
sell_dir: sell_delta * order['amount'] * order['price'] * get_fee(fee_delta),
buy_dir: buy_delta * order['amount']
}
def calcOrders(self):
for order in self.orders:
self.order_dict['sell' if order.is_sell else 'buy'].append({
'date': order.pub_date,
'price': order.price,
'funds': order.api['funds']
})
print('Orders - {}'.format(len(self.order_dict['sell']) + len(self.order_dict['buy'])))
def calcRate(self):
for rate_info in self.rate:
resp = json.loads(rate_info.resp)
self.rate_dict['date'].append(rate_info.pub_date)
self.rate_dict['buy_price'].append(resp['asks'][0][0])
self.rate_dict['sell_price'].append(resp['bids'][0][0])
self.last_rate = resp
print('Prices - {}'.format(len(self.rate_dict['date'])))
In [5]:
from sqlalchemy.orm.exc import NoResultFound
import sqlalchemy as sa
from server.trade.VolumeStrategy import VolumeStrategy
table_name = 'order' # 'order', 'demo_order'
table = getattr(db, table_name)
info = []
for pair in MultiplePairs.PAIRS:
pairInfo = PairInfo(pair)
pairInfo.orders = session.query(table).filter(
(table.c.pair == pair)
& (table.c.pub_date > start_date_filter)
& (table.c.pub_date < end_date_filter)
).order_by(table.c.pub_date)
pairInfo.rate = session.query(db.history).filter(
(db.history.c.pub_date > start_date_filter)
& (db.history.c.pub_date < end_date_filter)
& (db.history.c.pair == pair)
& (sa.sql.func.random() < 0.003)
).order_by(db.history.c.pub_date)
info.append(pairInfo)
pairInfo.calcOrders()
pairInfo.calcRate()
In [6]:
import matplotlib.pyplot as plt
plt.cla()
plt.clf()
plt.close('all')
fig, axes = plt.subplots(nrows=len(info), figsize=(20,30))
for index, pairInfo in enumerate(info):
ay = axes[index]
ay.grid(True)
for name, vals in pairInfo.order_dict.items():
ay.set_title(pairInfo.pair)
ay.plot(
list(map(lambda i: i['date'], vals)),
list(map(lambda i: i['price'], vals)),
color = 'red' if name == 'sell' else 'blue',
marker= '.'
)
rate_dict = pairInfo.rate_dict
ay.plot(rate_dict['date'], rate_dict['buy_price'], alpha=0.2, color='blue')
ay.plot(rate_dict['date'], rate_dict['sell_price'], alpha=0.2, color='red')
fig
Out[6]:
In [7]:
plt.cla()
plt.clf()
plt.close('all')
all_orders = []
currencySet = set()
for pairInfo in info:
currencySet.add(pairInfo.sell_dir)
currencySet.add(pairInfo.buy_dir)
all_orders = all_orders + pairInfo.get_orders()
all_orders = sorted(all_orders, key=lambda order: order['date'])
fig, axes = plt.subplots(nrows=len(currencySet), figsize=(20,30))
for index, currency in enumerate(currencySet):
ay = axes[index]
ay.grid(True)
ay.set_title(currency)
ay.plot(
list(map(lambda i: i['date'], all_orders)),
list(map(lambda i: i['funds'][currency], all_orders))
)
fig
Out[7]:
In [8]:
plt.cla()
plt.clf()
plt.close('all')
usd_rate_dict = {
'usd': 1
}
for pairInfo in info:
if (pairInfo.sell_dir == 'usd'):
usd_rate_dict[pairInfo.buy_dir] = float(pairInfo.last_rate['asks'][0][0])
fig_balance = plt.figure(figsize=(20,10))
ay = fig_balance.add_subplot(1,1,1)
def summ_all_funds(funds):
out = 0
for currency in currencySet:
out += float(funds[currency]) * usd_rate_dict[currency]
return out
ay.grid(True)
ay.plot(
list(map(lambda i: i['date'], all_orders)),
list(map(lambda i: summ_all_funds(i['funds']), all_orders))
)
fig_balance
Out[8]:
In [ ]: