From 2e863dd56c9af5190f30ff9aefffe73082f6d498 Mon Sep 17 00:00:00 2001
From: Holger Nahrstaedt <holger@nahrstaedt.de>
Date: Tue, 24 Apr 2018 16:38:47 +0200
Subject: [PATCH] Dokumentation and market improved

Account
* Example for history and history_reverse added
Market
* base and quote added to init to define what buy and what sell means
Doc
* tutorials improved
Unit tests
* test_market improved
---
 beem/account.py           | 45 +++++++++++++++++++++++++++++
 beem/market.py            | 52 +++++++++++++++++++++++++--------
 docs/index.rst            |  2 +-
 docs/tutorials.rst        | 60 +++++++++++++++++++++++----------------
 tests/beem/test_market.py | 33 ++++++++++++++-------
 5 files changed, 143 insertions(+), 49 deletions(-)

diff --git a/beem/account.py b/beem/account.py
index 58deae42..a80c9057 100644
--- a/beem/account.py
+++ b/beem/account.py
@@ -858,6 +858,28 @@ class Account(BlockchainObject):
                 The full list of operation ID's can be found in
                 beembase.operationids.ops.
                 Example: ['transfer', 'vote']
+
+            Example::
+                from beem.account import Account
+                from beem.blockchain import Blockchain
+                from datetime import datetime
+                acc = Account("test")
+                max_op_count = acc.virtual_op_count()
+                # Returns the 100 latest operations
+                for h in acc.history(start=max_op_count-100, stop=max_op_count, use_block_num=False):
+                    print(h)
+
+                b = Blockchain()
+                max_block = b.get_current_block_num()
+                # Returns the account operation inside the last 100 block. This can be empty.
+                for h in acc.history(start=max_block-100, stop=max_block, use_block_num=True):
+                    print(h)
+
+                start_time = datetime(2018, 3, 1, 0, 0, 0)
+                stop_time = datetime(2018, 4, 1, 0, 0, 0)
+                # Returns the account operation from 1.4.2018 back to 1.3.2018
+                for h in acc.history(start=start_time, stop=stop_time):
+                    print(h)
         """
         _limit = batch_size
         max_index = self.virtual_op_count()
@@ -947,6 +969,29 @@ class Account(BlockchainObject):
                 The full list of operation ID's can be found in
                 beembase.operationids.ops.
                 Example: ['transfer', 'vote']
+
+            Example::
+                from beem.account import Account
+                from beem.blockchain import Blockchain
+                from datetime import datetime
+                acc = Account("test")
+                max_op_count = acc.virtual_op_count()
+                # Returns the 100 latest operations
+                for h in acc.history_reverse(start=max_op_count, stop=max_op_count-100, use_block_num=False):
+                    print(h)
+
+                b = Blockchain()
+                max_block = b.get_current_block_num()
+                # Returns the account operation inside the last 100 block. This can be empty.
+                for h in acc.history_reverse(start=max_block, stop=max_block-100, use_block_num=True):
+                    print(h)
+
+                start_time = datetime(2018, 4, 1, 0, 0, 0)
+                stop_time = datetime(2018, 3, 1, 0, 0, 0)
+                # Returns the account operation from 1.4.2018 back to 1.3.2018
+                for h in acc.history_reverse(start=start_time, stop=stop_time):
+                    print(h)
+
         """
         _limit = batch_size
         first = self.virtual_op_count()
diff --git a/beem/market.py b/beem/market.py
index eca56796..267f2d7a 100644
--- a/beem/market.py
+++ b/beem/market.py
@@ -4,8 +4,9 @@ from __future__ import division
 from __future__ import print_function
 from __future__ import unicode_literals
 from builtins import str
-from beem.instance import shared_steem_instance
+import random
 from datetime import datetime, timedelta
+from beem.instance import shared_steem_instance
 from .utils import (
     formatTimeFromNow, formatTime, formatTimeString, assets_from_string, parse_time)
 from .asset import Asset
@@ -13,7 +14,6 @@ from .amount import Amount
 from .price import Price, Order, FilledOrder
 from .account import Account
 from beembase import operations
-import random
 
 
 class Market(dict):
@@ -32,26 +32,26 @@ class Market(dict):
         This class tries to identify **two** assets as provided in the
         parameters in one of the following forms:
 
-        * ``base`` and ``quote`` are valid assets (according to :class:`steem.asset.Asset`)
+        * ``base`` and ``quote`` are valid assets (according to :class:`beem.asset.Asset`)
         * ``base:quote`` separated with ``:``
         * ``base/quote`` separated with ``/``
         * ``base-quote`` separated with ``-``
 
         .. note:: Throughout this library, the ``quote`` symbol will be
-                  presented first (e.g. ``USD:BTS`` with ``USD`` being the
+                  presented first (e.g. ``STEEM:SBD`` with ``STEEM`` being the
                   quote), while the ``base`` only refers to a secondary asset
                   for a trade. This means, if you call
-                  :func:`steem.market.Market.sell` or
-                  :func:`steem.market.Market.buy`, you will sell/buy **only
+                  :func:`beem.market.Market.sell` or
+                  :func:`beem.market.Market.buy`, you will sell/buy **only
                   quote** and obtain/pay **only base**.
 
     """
 
     def __init__(
         self,
+        base=None,
+        quote=None,
         steem_instance=None,
-        *args,
-        **kwargs
     ):
         """
         Init Market
@@ -61,18 +61,46 @@ class Market(dict):
             :param beem.asset.Asset quote: Quote asset
         """
         self.steem = steem_instance or shared_steem_instance()
-        base = kwargs.get("base", Asset("SBD", steem_instance=self.steem))
-        quote = kwargs.get("quote", Asset("STEEM", steem_instance=self.steem))
 
-        super(Market, self).__init__({"base": base, "quote": quote})
+        if quote is None and isinstance(base, str):
+            quote_symbol, base_symbol = assets_from_string(base)
+            quote = Asset(quote_symbol, steem_instance=self.steem)
+            base = Asset(base_symbol, steem_instance=self.steem)
+            super(Market, self).__init__({"base": base, "quote": quote})
+        elif base and quote:
+            quote = Asset(quote, steem_instance=self.steem)
+            base = Asset(base, steem_instance=self.steem)
+            super(Market, self).__init__({"base": base, "quote": quote})
+        elif base is None and quote is None:
+            quote = Asset("SBD", steem_instance=self.steem)
+            base = Asset("STEEM", steem_instance=self.steem)
+            super(Market, self).__init__({"base": base, "quote": quote})
+        else:
+            raise ValueError("Unknown Market config")
 
     def get_string(self, separator=":"):
-        """ Return a formated string that identifies the market, e.g. ``USD:BTS``
+        """ Return a formated string that identifies the market, e.g. ``STEEM:SBD``
 
             :param str separator: The separator of the assets (defaults to ``:``)
         """
         return "%s%s%s" % (self["quote"]["symbol"], separator, self["base"]["symbol"])
 
+    def __eq__(self, other):
+        if isinstance(other, str):
+            quote_symbol, base_symbol = assets_from_string(other)
+            return (
+                self["quote"]["symbol"] == quote_symbol and
+                self["base"]["symbol"] == base_symbol
+            ) or (
+                self["quote"]["symbol"] == base_symbol and
+                self["base"]["symbol"] == quote_symbol
+            )
+        elif isinstance(other, Market):
+            return (
+                self["quote"]["symbol"] == other["quote"]["symbol"] and
+                self["base"]["symbol"] == other["base"]["symbol"]
+            )
+
     def ticker(self, raw_data=False):
         """ Returns the ticker for all markets.
 
diff --git a/docs/index.rst b/docs/index.rst
index 86df70c7..7dcb9eaa 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -102,7 +102,7 @@ Quickstart
 .. code-block:: python
 
    from beem.market import Market
-   market = Market()
+   market = Market("SBD:STEEM")
    print(market.ticker())
    market.steem.wallet.unlock("wallet-passphrase")
    print(market.sell(300, 100)  # sell 100 STEEM for 300 STEEM/SBD
diff --git a/docs/tutorials.rst b/docs/tutorials.rst
index c9a52e09..45ed1589 100644
--- a/docs/tutorials.rst
+++ b/docs/tutorials.rst
@@ -16,19 +16,32 @@ executed in the same order as they are added to the transaction.
   from pprint import pprint
   from beem import Steem
   from beem.account import Account
+  from beem.comment import Comment
+  from beem.instance import set_shared_steem_instance
 
+  # Only for testing not a real working key
+  wif = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"
+
+  # set nobroadcast always to True, when testing
   testnet = Steem(
       nobroadcast=True,
       bundle=True,
+      keys=[wif],
   )
-  
-  account = Account("test", steem_instance=testnet)
-  account.steem.wallet.unlock("supersecret")
+  # Set testnet as shared instance
+  set_shared_steem_instance(testnet)
+
+  # Account and Comment will use now testnet
+  account = Account("test")
 
-  account.transfer("test1", 1, "STEEM", account="test")
-  account.transfer("test1", 1, "STEEM", account="test")
-  account.transfer("test1", 1, "STEEM", account="test")
-  account.transfer("test1", 1, "STEEM", account="test")
+  # Post 
+  c = Comment("@gtg/witness-gtg-log")
+
+  account.transfer("test1", 1, "STEEM")
+  account.transfer("test2", 1, "STEEM")
+  account.transfer("test3", 1, "SBD")
+  # Upvote post with 25%
+  c.upvote(25, voter=account)
 
   pprint(testnet.broadcast())
 
@@ -42,25 +55,24 @@ Simple Sell Script
     from beem.market import Market
     from beem.price import Price
     from beem.amount import Amount
-
+    
+    # Only for testing not a real working key
+    wif = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"
+  
     #
     # Instanciate Steem (pick network via API node)
     #
     steem = Steem(
-        nobroadcast=True   # <<--- set this to False when you want to fire!
+        nobroadcast=True,   # <<--- set this to False when you want to fire!
+        keys=[wif]          # <<--- use your real keys, when going live!
     )
 
-    #
-    # Unlock the Wallet
-    #
-    steem.wallet.unlock("<supersecret>")
-
     #
     # This defines the market we are looking at.
     # The first asset in the first argument is the *quote*
     # Sell and buy calls always refer to the *quote*
     #
-    market = Market(
+    market = Market("SBD:STEEM",
         steem_instance=steem
     )
 
@@ -69,7 +81,7 @@ Simple Sell Script
     #
     print(market.sell(
         Price(100.0, "STEEM/SBD"),
-        Amount("0.01 STEEM")
+        Amount("0.01 SBD")
     ))
 
 
@@ -84,13 +96,15 @@ Sell at a timely rate
     from beem.price import Price
     from beem.amount import Amount
 
+    # Only for testing not a real working key
+    wif = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"
 
     def sell():
         """ Sell an asset for a price with amount (quote)
         """
         print(market.sell(
-            Price(100.0, "USD/GOLD"),
-            Amount("0.01 GOLD")
+            Price(100.0, "SBD/STEEM"),
+            Amount("0.01 STEEM")
         ))
 
         threading.Timer(60, sell).start()
@@ -101,20 +115,16 @@ Sell at a timely rate
         # Instanciate Steem (pick network via API node)
         #
         steem = Steem(
-            nobroadcast=True   # <<--- set this to False when you want to fire!
+            nobroadcast=True,   # <<--- set this to False when you want to fire!
+            keys=[wif]          # <<--- use your real keys, when going live!
         )
 
-        #
-        # Unlock the Wallet
-        #
-        steem.wallet.unlock("<supersecret>")
-
         #
         # This defines the market we are looking at.
         # The first asset in the first argument is the *quote*
         # Sell and buy calls always refer to the *quote*
         #
-        market = Market(
+        market = Market("STEEM:SBD",
             steem_instance=steem
         )
 
diff --git a/tests/beem/test_market.py b/tests/beem/test_market.py
index 4c58389d..35ebd79e 100644
--- a/tests/beem/test_market.py
+++ b/tests/beem/test_market.py
@@ -9,6 +9,7 @@ from pprint import pprint
 from beem import Steem
 from beem.market import Market
 from beem.price import Price
+from beem.asset import Asset
 from beem.amount import Amount
 from beem.instance import set_shared_steem_instance
 from beem.utils import get_node_list
@@ -46,7 +47,17 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m1 = Market(u'STEEM', u'SBD', steem_instance=bts)
+        self.assertEqual(m1.get_string(), u'SBD:STEEM')
+        m2 = Market(steem_instance=bts)
+        self.assertEqual(m2.get_string(), u'SBD:STEEM')
+        m3 = Market(u'STEEM:SBD', steem_instance=bts)
+        self.assertEqual(m3.get_string(), u'STEEM:SBD')
+        self.assertTrue(m1 == m2)
+
+        base = Asset("SBD", steem_instance=bts)
+        quote = Asset("STEEM", steem_instance=bts)
+        m = Market(base, quote, steem_instance=bts)
         self.assertEqual(m.get_string(), u'STEEM:SBD')
 
     @parameterized.expand([
@@ -58,7 +69,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         ticker = m.ticker()
         self.assertEqual(len(ticker), 6)
         self.assertEqual(ticker['steemVolume']["symbol"], u'STEEM')
@@ -73,7 +84,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         volume = m.volume24h()
         self.assertEqual(volume['STEEM']["symbol"], u'STEEM')
         self.assertEqual(volume['SBD']["symbol"], u'SBD')
@@ -87,7 +98,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         orderbook = m.orderbook(limit=10)
         self.assertEqual(len(orderbook['asks_date']), 10)
         self.assertEqual(len(orderbook['asks']), 10)
@@ -103,7 +114,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         recenttrades = m.recent_trades(limit=10)
         recenttrades_raw = m.recent_trades(limit=10, raw_data=True)
         self.assertEqual(len(recenttrades), 10)
@@ -118,7 +129,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         trades = m.trades(limit=10)
         trades_raw = m.trades(limit=10, raw_data=True)
         self.assertEqual(len(trades), 10)
@@ -133,7 +144,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         buckets = m.market_history_buckets()
         history = m.market_history(buckets[2])
         self.assertTrue(len(history) > 0)
@@ -147,7 +158,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         openOrder = m.accountopenorders("test")
         self.assertTrue(isinstance(openOrder, list))
 
@@ -160,7 +171,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         tx = m.buy(5, 0.1, account="test")
         self.assertEqual(
             (tx["operations"][0][0]),
@@ -193,7 +204,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         tx = m.sell(5, 0.1, account="test")
         self.assertEqual(
             (tx["operations"][0][0]),
@@ -226,7 +237,7 @@ class Testcases(unittest.TestCase):
             bts = self.bts
         else:
             bts = self.appbase
-        m = Market(steem_instance=bts)
+        m = Market(u'STEEM:SBD', steem_instance=bts)
         tx = m.cancel(5, account="test")
         self.assertEqual(
             (tx["operations"][0][0]),
-- 
GitLab