In [ ]:
df = read_data('/Users/felipe/bitme/data/bitmex_1day.csv')
df.reset_index('time', inplace=True)
df.head()

In [ ]:
fills = read_data('/Users/felipe/bitme/output/fills.csv')
pnls = read_data('/Users/felipe/bitme/output/pnl.csv')
buys = fills.loc[fills['side'] == 'buy'][['price']]
sells = fills.loc[fills['side'] == 'sell'][['price']]
liqs = fills.loc[fills['order_type'] == 'market'][['price']]
pnls[['cum_pnl']]

In [ ]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.offline as offline

offline.init_notebook_mode(connected=True)
from datetime import datetime
import pandas as pd

def parse(s):
    #return datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
    return pd.Timestamp(s)

trace = go.Candlestick(x=df.time,
                open=df.open,
                high=df.high,
                low=df.low,
                close=df.close,
                      name='ohlc')

trace2 = go.Scatter(
    x = buys.index,
    y = buys['price'],
    name = 'Buy',
    mode = 'markers',
    marker = dict(
        size = 10,
        color = 'rgba(182, 255, 193, .9)',
        line = dict(
            width = 2,
        )
    )
)

trace3 = go.Scatter(
    x = sells.index,
    y = sells['price'],
    name = 'Sell',
    mode = 'markers',
    marker = dict(
        size = 7,
        color = 'rgba(255, 182, 193, .9)',
        line = dict(
            width = 1,
        )
    )
)

trace4 = go.Scatter(
    x = pnls.index,
    y = pnls['cum_pnl'],
    name = 'P&L',
    mode = 'lines+markers',
    marker = dict(
        size = 5,
        color = 'rgba(193, 182, 255, .9)',
        line = dict(
            width = 1,
        )
    ),
    yaxis='y2'
)

data = [trace, trace2, trace3, trace4]

layout = go.Layout(
    title='Double Y Axis Example',
    yaxis=dict(
        title='Price'
    ),
    yaxis2=dict(
        title='BTC',
        titlefont=dict(
            color='rgb(148, 103, 189)'
        ),
        tickfont=dict(
            color='rgb(148, 103, 189)'
        ),
        overlaying='y',
        side='right'
    ),
    xaxis = dict(
        rangeslider = dict(
            visible = False
        )
    ),
    xaxis2 = dict()
)


fig = go.Figure(data=data,layout=layout)
offline.iplot(fig, filename='/Users/felipe/bitme/simple_ohlc')
#offline.iplot(fig)#

In [ ]:
offline.plot(fig, filename='/Users/felipe/bitme/simple_ohlc.html')

In [ ]:
fills.head()

In [ ]:
s = [{'close': 6833,
  'foreignNotional': 641097,
  'high': 6835.5,
  'homeNotional': 93.81274770000002,
  'lastSize': 500,
  'low': 6833,
  'open': 6835,
  'symbol': 'XBTUSD',
  'timestamp': '2018-06-12T11:35:00.000Z',
  'trades': 230,
  'turnover': 9381274770,
  'volume': 641097,
  'vwap': 6833.8687},
 {'close': 6831.5,
  'foreignNotional': 879729,
  'high': 6833.5,
  'homeNotional': 128.77249317999997,
  'lastSize': 20,
  'low': 6831,
  'open': 6833,
  'symbol': 'XBTUSD',
  'timestamp': '2018-06-12T11:36:00.000Z',
  'trades': 158,
  'turnover': 12877249318,
  'volume': 879729,
  'vwap': 6832.0011}]

In [ ]:
a = pd.DataFrame(data=s); a = a.set_index('timestamp'); a.index 
a

In [ ]:
from typing import Union
def to_ohlcv(data: Union[pd.DataFrame, list] = None, filename=None) -> pd.DataFrame:

    if filename is not None:
        if data is not None:
            raise ValueError("XOR(filename==None, data==None) should be True")
        data = pd.read_csv(filename)

    if isinstance(data, list):
        df = pd.DataFrame(data=data, dtype='float64')
    else:
        df = data
    if 'timestamp' in df.columns:
        df.set_index('timestamp', inplace=True)
    elif 'time' in df.columns:
        df.set_index('time', inplace=True)
    df = df[['open', 'high', 'low', 'close', 'volume']]
    df.index = pd.to_datetime(df.index)

    return df

In [ ]:
z = to_ohlcv(filename='/Users/felipe/bitme/data/sample2.csv')

In [ ]:
z['open'][3] = 15000.0

In [ ]:
z

In [ ]:
df = z.copy()
idx = df['low'] > df['open']
c = df.copy()
c['low'][idx] = df['open']
df = c
df

In [ ]:
df - z

In [ ]:
c['low'][idx]
#df['open']

In [ ]:
from abc import ABCMeta, abstractmethod, abstractproperty
class B(metaclass=ABCMeta):
    @property
    @abstractmethod
    def x(self):
        pass

class A:
    def __init__(self, z=666):
        self.x=z
        pass
    def ha(self):
        self = A(123)
    x = 1

In [ ]:
a = A()
#a.x = 3
a.__dict__['x']  = 666
a.x

In [ ]:
a = A()
a.ha()
a.x

In [ ]:
a.print()

In [ ]:
import sys
import contextlib
@contextlib.contextmanager
def smart_open(filename=None):
    if filename and filename != '-':
        fh = open(filename, 'w')
    else:
        fh = sys.stdout

    try:
        yield fh
    finally:
        if fh is not sys.stdout:
            fh.close()

In [ ]:
with smart_open('/Users/felipe/KICKME') as f:
    print('hahaha', file='-')

In [ ]:
import argparse

In [ ]:
a = argparse.ArgumentParser()

In [1]:
def f():
    for i in range(3):
        yield i

In [2]:
for i in f():
    print(i)


0
1
2

In [24]:
initial = 7.3  # btc
p1 = 6000
p2l = 6123
p2s = 6000 - 123

In [25]:
N = initial * p1

In [26]:
long = N*(1./ p1 - 1./p2l)
long


Out[26]:
0.1466438020578147

In [27]:
short_ = -N*(1./ p1 - 1./p2s)
short_


Out[27]:
0.15278203164880094

In [28]:
(initial + long) * p2l, (initial + short_) * p2s,


Out[28]:
(45595.8, 43800.0)

In [29]:
long * p2l, short_ * p2s,


Out[29]:
(897.8999999999993, 897.9000000000032)

In [30]:
# N*(1./ p1 - 1./p2l) * p2l = N*(p2l/p1 - 1)  Long
# N*(1./ p2s - 1./p1) * p2s = N*(1 - p2s/p1)  short

In [ ]:
# N*((p1 + e)/p1 - 1) = N*e/p1  Long
# N*(1 - ((p1 - e))/p1) =   short

In [ ]: