In [ ]:
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
import matplotlib.pyplot as plt
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 [ ]:
from sqlalchemy.orm.exc import NoResultFound
import sqlalchemy as sa
from server.trade.VolumeStrategy import VolumeStrategy
from server.trade.player import START_TIME, END_TIME
rate = 1
table_name = 'demo_order' # 'order', 'demo_order'
table = getattr(db, table_name)
all_orders_flag = 1
start_date_filter = START_TIME #START_TIME - 2017-06-16 00:00
end_date_filter = END_TIME #END_TIME - 2017-06-18 23:59
pair = 'eth_usd' #VolumeStrategy.PAIR
buy_dir, sell_dir = pair.split("_")
cursor = session.query(table).filter(
(table.c.extra[VolumeStrategy.ORDER_CLASS.FLAG_NAME].astext == '1')
& (table.c.pair == pair)
& (table.c.pub_date > start_date_filter)
& (table.c.pub_date < end_date_filter)
).order_by(table.c.pub_date)
if all_orders_flag:
all_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)
if rate:
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.007)
).order_by(db.history.c.pub_date)
In [ ]:
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']
}
In [ ]:
order_dict = {
'sell': [],
'buy': []
}
if all_orders_flag:
for order in all_orders:
order_dict['sell' if order.is_sell else 'buy'].append({
'date': order.pub_date,
'price': order.price
})
print('Orders - {}'.format(len(order_dict['sell']) + len(order_dict['buy'])))
if rate:
rate_dict = {
'date': [],
'sell_price': [],
'buy_price': []
}
for rate_info in rate:
resp = json.loads(rate_info.resp)
rate_dict['date'].append(rate_info.pub_date)
rate_dict['buy_price'].append(resp['asks'][0][0])
rate_dict['sell_price'].append(resp['bids'][0][0])
print('Prices - {}'.format(len(rate_dict['date'])))
In [ ]:
plt.cla()
plt.clf()
plt.close('all')
fig_price = plt.figure(figsize=(20,10))
ay = fig_price.add_subplot(1,1,1)
ay.grid(True)
for name, vals in order_dict.items():
ay.plot(
list(map(lambda i: i['date'], vals)),
list(map(lambda i: i['price'], vals)),
color = 'red' if name == 'sell' else 'blue',
marker= '.'
)
if rate:
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_price
In [ ]:
change_info = []
for index, order in enumerate(all_orders):
order = as_dict(order)
money_change = calc_money(order)
if not index:
change_info.append({
buy_dir: money_change[buy_dir],
sell_dir: money_change[sell_dir],
'price': order['price'],
'date': order['pub_date'],
'sum': money_change[sell_dir] + (money_change[buy_dir] * order['price'])
})
last = change_info[index]
else:
last = change_info[index-1]
change_info.append({
buy_dir: last[buy_dir] + money_change[buy_dir],
sell_dir: last[sell_dir] + money_change[sell_dir],
'price': order['price'],
'date': order['pub_date'],
'sum': money_change[sell_dir] + (money_change[buy_dir] * order['price'])
})
'''
print('{}, id {}, parent {} sum {}'.format(
money_change,
order['id'],
order['extra'].get('parent'),
last['']
))
'''
last = change_info[len(change_info)-1]
print('Total: {} {} {} {} sum {}'.format(
last[sell_dir], sell_dir, last[buy_dir], buy_dir, last[sell_dir]+(last[buy_dir]*last['price']))
)
index
In [ ]:
plt.cla()
plt.clf()
fig = plt.figure(figsize=(20,10))
ay = fig.add_subplot(1,1,1)
ay.grid(True)
ay.plot(
list(map(lambda i: i['date'], change_info)),
list(map(lambda i: i[sell_dir]+(i[buy_dir]*i['price']), change_info)),
'r-', linewidth=1
)
fig
In [ ]:
level = set()
def get_parent(item):
parent = session.query(table).filter(
(table.c.id == str(item['extra']['parent'])
#| (table.c.extra['merged'].astext == str(item.id))
)
& (table.c.pub_date > start_date_filter)
& (table.c.pub_date < end_date_filter)).one()
return as_dict(parent)
def iter_order(item, tail):
if item['extra'].get('parent'):
parent = get_parent(item)
iter_order(parent, tail)
tail.append([parent, item])
else:
tail.append([None, item])
pairs_list = []
for index, order in enumerate(cursor):
order = as_dict(order)
iter_order(order, pairs_list)
len(pairs_list)
In [ ]:
new_sum = 0
for parent, child in pairs_list:
if not parent:
continue
parent_dir = 'Sell' if parent['is_sell'] else 'Buy'
child_dir = 'Sell' if child['is_sell'] else 'Buy'
print('{} before price {} amount {} now {} price {} amount {}'.format(
parent_dir,
parent['price'],
parent['amount'],
child_dir,
child['price'],
child['amount']
))
if parent['is_sell']:
price_diff = parent['price'] - child['price']
else:
price_diff = child['price'] - parent['price']
new_sum += price_diff * child['amount']
new_sum
In [ ]: