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.ThreadStrategy import ThreadStrategy
from server.trade.player import START_TIME, END_TIME
rate = 1
table_name = 'demo_order'
table = getattr(db, table_name)
all_orders_flag = 1
start_date_filter = START_TIME
end_date_filter = END_TIME
pair = ThreadStrategy.PAIR
cursor = session.query(table).filter(
(table.c.extra[ThreadStrategy.ORDER_CLASS.FLAG_NAME].astext == '0')
& (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)
print(all_orders)
print(pair, start_date_filter, end_date_filter)
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()
item['api'] = item['api']
return item
def get_fee(delta):
return (1 + (delta*(0.2 + 0)/100))
def calc_money(order):
if order['is_sell']:
btc_delta = -1
usd_delta = 1
fee_delta = -1
else:
btc_delta = 1
usd_delta = -1
fee_delta = 1
return {
'usd': usd_delta * order['amount'] * order['price'] * get_fee(fee_delta),
'btc': btc_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
})
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(len(rate_dict['date']))
print(len(order_dict['sell']))
In [ ]:
plt.cla()
plt.clf()
fig = plt.figure(figsize=(20,10))
ay = fig.add_subplot(1,1,1)
ay.grid(True)
for name, vals in order_dict.items():
print(len(vals))
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')
print(all_orders_flag)
fig
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({
'btc': money_change['btc'],
'usd': money_change['usd'],
'price': order['price'],
'date': order['pub_date']
})
else:
last = change_info[index-1]
change_info.append({
'btc': last['btc'] + money_change['btc'],
'usd': last['usd'] + money_change['usd'],
'price': order['price'],
'date': order['pub_date']
})
last = change_info[len(change_info)-1]
print('Total: {} usd {} btc'.format(last['usd'], last['btc']))
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['usd']+(i['btc']*i['price']), change_info)),
'r-', linewidth=1
)
fig
In [ ]: