Skip to content

Commit

Permalink
more work
Browse files Browse the repository at this point in the history
  • Loading branch information
xeroc committed Jun 25, 2017
1 parent f8c321d commit e7f0dc5
Show file tree
Hide file tree
Showing 9 changed files with 108 additions and 312 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,9 @@ target/
# script data
data_*.json
.env

bitshares
bitsharesapi
uptick
deprecated
*.sqlite
5 changes: 5 additions & 0 deletions cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env python3

from stakemachine import cli

cli.main()
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bitshares
sqlalchemy
88 changes: 57 additions & 31 deletions stakemachine/basestrategy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import logging
from events import Events
from bitshares.market import Market
from bitshares.account import Account
from bitshares.price import FilledOrder, Order
from bitshares.instance import shared_bitshares_instance
from .storage import Storage
from .statemachine import StateMachine
log = logging.getLogger(__name__)
Expand All @@ -23,9 +26,35 @@ def __init__(
onOrderPlaced=None,
onMarketUpdate=None,
ontick=None,
bitshares_instance=None,
*args,
**kwargs
):
""" Base Strategy and methods available in all Sub Classes that
inherit this BaseStrategy.
Available attributes:
* ``basestrategy.bitshares``: instance of ´`bitshares.BitShares()``
* ``basestrategy.add_state``: Add a specific state
* ``basestrategy.set_state``: Set finite state machine
* ``basestrategy.get_state``: Change state of state machine
* ``basestrategy.account``: The Account object of this bot
* ``basestrategy.market``: The market used by this bot
* ``basestrategy.orders``: List of open orders of the bot's account in the bot's market
* ``basestrategy.balanc``: List of assets and amounts available in the bot's account
Also, Base Strategy inherits :class:`stakemachine.storage.Storage`
which allows to permanently store data in a sqlite database
using:
``basestrategy["key"] = "value"``
... note:: This applies a ``json.loads(json.dumps(value))``!
"""
# BitShares instance
self.bitshares = bitshares_instance or shared_bitshares_instance()

# Storage
Storage.__init__(self, name)

Expand All @@ -43,41 +72,38 @@ def __init__(
self.ontick += ontick

# Redirect this event to also call order placed and order matched
self.onMarketUpdate += self.callbackPlaceFillOrders
self.onMarketUpdate += self._callbackPlaceFillOrders

def callbackPlaceFillOrders(self, d):
self.config = config
self.bot = config["bots"][name]
self.account = Account(
self.bot["account"],
bitshares_instance=self.bitshares
)

@property
def market(self):
return Market(
self.bot["market"],
bitshares_instance=self.bitshares
)

@property
def orders(self):
return [o for o in self.account.openorders if self.bot["market"] == o.market]

@property
def balance(self):
return self.account.balances

@property
def balances(self):
return self.balance

def _callbackPlaceFillOrders(self, d):
if isinstance(d, FilledOrder):
self.onOrderMatched(d)
elif isinstance(d, Order):
self.onOrderPlaced(d)
else:
pass

def update(self):
""" Tick every block
"""
log.debug("Market update. Please define `%s.update()`" % self.name)

# Extra calls
def buy(self, market, price, amount, expiration=60 * 60 * 24, **kwargs):
pass

def sell(self, market, price, amount, expiration=60 * 60 * 24, **kwargs):
pass

def cancel(self, orderid):
""" Cancel the order with id ``orderid``
"""
log.info("Canceling %s" % orderid)
try:
cancel = self.dex.cancel(orderid)
except Exception as e:
log.critical("An error occured while trying to sell: %s" % str(e))
return cancel

def get_balances(self):
pass

@property
def balance(self):
pass
15 changes: 7 additions & 8 deletions stakemachine/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ def __init__(
for botname, bot in config["bots"].items():
if "account" not in bot:
raise ValueError("Bot %s has no account" % botname)
if "markets" not in bot:
raise ValueError("Bot %s has no markets" % botname)
if "market" not in bot:
raise ValueError("Bot %s has no market" % botname)

accounts.add(bot["account"])
markets.update(set(bot["markets"]))
markets.add(bot["market"])

# Create notification instance
# Technically, this will multiplex markets and accounts and
Expand Down Expand Up @@ -58,14 +59,12 @@ def __init__(
# Events
def on_block(self, data):
for botname, bot in self.config["bots"].items():
for market in bot["markets"]:
self.bots[botname].ontick(data)
self.bots[botname].ontick(data)

def on_market(self, data):
for botname, bot in self.config["bots"].items():
for market in bot["markets"]:
if market == data.market:
self.bots[botname].onMarketUpdate(data)
if bot["market"] == data.market:
self.bots[botname].onMarketUpdate(data)

def on_account(self, data):
pass
Expand Down
4 changes: 3 additions & 1 deletion stakemachine/storage.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import sqlalchemy
from sqlalchemy import create_engine, Table, Column, String, Integer, MetaData
from sqlalchemy.ext.declarative import declarative_base
Expand Down Expand Up @@ -29,6 +30,7 @@ def __init__(self, category):
self.category = category

def __setitem__(self, key, value):
value = json.dumps(value)
e = session.query(Config).filter_by(
category=self.category,
key=key
Expand All @@ -48,7 +50,7 @@ def __getitem__(self, key):
if not e:
return None
else:
return e.value
return json.loads(e.value)

def __delitem__(self, key):
e = session.query(Config).filter_by(
Expand Down
14 changes: 9 additions & 5 deletions stakemachine/strategies/echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,20 @@


def print1(i):
print("1: %s" % i)
print("order matched: %s" % i)


def print2(i):
print("2: %s" % i)
print("order placed: %s" % i)


def print3(i):
print("3: %s" % i)
print("marketupdate: %s" % i)


def print4(i):
print("4: %s" % i)
print("new block: %s" % i)


class Echo(BaseStrategy):
def __init__(self, *args, **kwargs):
Expand All @@ -23,5 +27,5 @@ def __init__(self, *args, **kwargs):
"""
self.onOrderMatched += print1
self.onOrderPlaced += print2
#self.onMarketUpdate += print3
self.onMarketUpdate += print3
self.ontick += print4
Loading

0 comments on commit e7f0dc5

Please sign in to comment.