def __init__(self):
        """
        Initialization method. Here is where we poll the database and the BitStamp API to collect relevant data.
        """
        # The first step is to fetch and store transactions from the backend to ensure that our knowledge of transactional data is up to Date
        push_transactions.push(log=False)

        # The next step is to fetch current price data from the sqlite3 database

        conn = sqlite3.connect( bitcoin.get_db() )
        cursor = conn.cursor()

        values = cursor.execute('''SELECT "time", "buy", "sell", "wa_buy", "wa_sell" FROM "prices" ORDER BY "time" DESC LIMIT 1''').fetchone()

        self.time = values[0]
        self.buy = values[1]
        self.sell = values[2]
        self.avg_buy = values[3]
        self.avg_sell = values[4]

        # Use BitStamp API client to fetch the USD and BTC balance
        bal = client.balance()

        self.usd_balance = float(bal['usd_balance'])
        self.btc_balance = float(bal['btc_balance'])

        # Query "transactions" table to database to get the latest buy and sell prices and the times they occurred (needed for orienting/analysis)
        values = cursor.execute('''SELECT "time", "rate" FROM "transactions" WHERE "usd" > 0 ORDER BY "time" DESC LIMIT 1''').fetchone()
        self.last_sell_time = values[0]
        self.last_sell_price = values[1]

        values = cursor.execute('''SELECT "time", "rate" FROM "transactions" WHERE "usd" < 0 ORDER BY "time" DESC LIMIT 1''').fetchone()
        self.last_buy_time = values[0]
        self.last_buy_price = values[1]

        # Fetch all buy prices since the last time BTC was sold
        self.buy_prices = []
        for values in cursor.execute('''SELECT "buy" FROM "prices" WHERE "time" > ?''', (self.last_sell_time,)):

            self.buy_prices.append(values[0])

        # Fetch all sell prices since the last time BTC was bought
        self.sell_prices = []
        self.weighted_sell_prices = []
        for values in cursor.execute('''SELECT "sell", "wa_sell" FROM "prices" WHERE "time" > ?''', (self.last_buy_time, )):

            self.sell_prices.append(values[0])
            self.weighted_sell_prices.append(values[1])

        # Convert array of prices in to R vectors
        self.buy_prices = robjects.FloatVector(self.buy_prices)
        self.sell_prices = robjects.FloatVector(self.sell_prices)
        self.weighted_sell_prices = robjects.FloatVector(self.weighted_sell_prices)

        cursor.close()
def push(log=True):
    """
    Fetches transactions from BitStamp and pushes them in to the sqlite3 database where they are used to determine the
    latest buy and sell prices.
    """

    conn = sqlite3.connect( bitcoin.get_db() )
    cursor = conn.cursor()

    if log: print("Fetching transactions from BitStamp server ...")
    data = bitcoin.client.transactions()

    if log: print("Inserting data in to 'transactions' table ...")

    for trx in data:

        ts = unix_timestamp(trx['datetime'])

        cursor.execute('''REPLACE INTO "transactions" ("time", "usd", "btc", "rate") VALUES (?,?,?,?)''', (ts, trx['usd'], trx['btc'], trx['btc_usd']))

    conn.commit()
    conn.close()

    if log: print("Done\n")
Example #3
0
#
#
# Author: Abid H. Mujtaba
# Date: 2014-04-05
#
# This script reads buy and price data from the database, calculates the first and second finite differences and stores
# it in the database.

import rpy2.robjects as robjects
import sqlite3

from bitcoin import get_db, round2

if __name__ == '__main__':

    conn = sqlite3.connect(get_db())
    cursor = conn.cursor()

    s_time = []
    s_buy = []
    s_sell = []

    print("Reading in time and prices from database.")

    for values in cursor.execute(
            '''SELECT "time", "buy", "sell" FROM "prices"'''):

        s_time.append(values[0])
        s_buy.append(values[1])
        s_sell.append(values[2])
    def __init__(self):
        """
        Initialization method. Here is where we poll the database and the BitStamp API to collect relevant data.
        """
        # The first step is to fetch and store transactions from the backend to ensure that our knowledge of transactional data is up to Date
        push_transactions.push(log=False)

        # The next step is to fetch current price data from the sqlite3 database

        conn = sqlite3.connect(bitcoin.get_db())
        cursor = conn.cursor()

        values = cursor.execute(
            '''SELECT "time", "buy", "sell", "wa_buy", "wa_sell" FROM "prices" ORDER BY "time" DESC LIMIT 1'''
        ).fetchone()

        self.time = values[0]
        self.buy = values[1]
        self.sell = values[2]
        self.avg_buy = values[3]
        self.avg_sell = values[4]

        # Use BitStamp API client to fetch the USD and BTC balance
        bal = client.balance()

        self.usd_balance = float(bal['usd_balance'])
        self.btc_balance = float(bal['btc_balance'])

        # Query "transactions" table to database to get the latest buy and sell prices and the times they occurred (needed for orienting/analysis)
        values = cursor.execute(
            '''SELECT "time", "rate" FROM "transactions" WHERE "usd" > 0 ORDER BY "time" DESC LIMIT 1'''
        ).fetchone()
        self.last_sell_time = values[0]
        self.last_sell_price = values[1]

        values = cursor.execute(
            '''SELECT "time", "rate" FROM "transactions" WHERE "usd" < 0 ORDER BY "time" DESC LIMIT 1'''
        ).fetchone()
        self.last_buy_time = values[0]
        self.last_buy_price = values[1]

        # Fetch all buy prices since the last time BTC was sold
        self.buy_prices = []
        for values in cursor.execute(
                '''SELECT "buy" FROM "prices" WHERE "time" > ?''',
            (self.last_sell_time, )):

            self.buy_prices.append(values[0])

        # Fetch all sell prices since the last time BTC was bought
        self.sell_prices = []
        self.weighted_sell_prices = []
        for values in cursor.execute(
                '''SELECT "sell", "wa_sell" FROM "prices" WHERE "time" > ?''',
            (self.last_buy_time, )):

            self.sell_prices.append(values[0])
            self.weighted_sell_prices.append(values[1])

        # Convert array of prices in to R vectors
        self.buy_prices = robjects.FloatVector(self.buy_prices)
        self.sell_prices = robjects.FloatVector(self.sell_prices)
        self.weighted_sell_prices = robjects.FloatVector(
            self.weighted_sell_prices)

        cursor.close()
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Author: Abid H. Mujtaba
# Date: 2014-03-27
#
# A script for extracting the last 6 hours of buy prices (180 samples) from the database and storing it in a file.


import sqlite3

import bitcoin

SAMPLES = 6 * 60


if __name__ == '__main__':

    fout = open('buy.txt', 'w')

    conn = sqlite3.connect(bitcoin.get_db())
    cursor = conn.cursor()

    for values in cursor.execute('''SELECT "buy" FROM (SELECT "time", "buy" FROM "prices" ORDER BY "time" DESC LIMIT ?) ORDER BY "time" ASC''', (SAMPLES,)):   # Get list of times in descending order

        fout.write("%.2f\n" % values[0])

    conn.close();
    fout.close();
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Author: Abid H. Mujtaba
# Date: 2014-03-27
#
# A script for extracting the last 6 hours of buy prices (180 samples) from the database and storing it in a file.

import sqlite3

import bitcoin

SAMPLES = 6 * 60

if __name__ == '__main__':

    fout = open('buy.txt', 'w')

    conn = sqlite3.connect(bitcoin.get_db())
    cursor = conn.cursor()

    for values in cursor.execute(
            '''SELECT "buy" FROM (SELECT "time", "buy" FROM "prices" ORDER BY "time" DESC LIMIT ?) ORDER BY "time" ASC''',
        (SAMPLES, )):  # Get list of times in descending order

        fout.write("%.2f\n" % values[0])

    conn.close()
    fout.close()
# Author: Abid H. Mujtaba
# Date: 2014-04-05
#
# This script reads buy and price data from the database, calculates the first and second finite differences and stores
# it in the database.


import rpy2.robjects as robjects
import sqlite3

from bitcoin import get_db, round2


if __name__ == '__main__':

    conn = sqlite3.connect( get_db() )
    cursor = conn.cursor()

    s_time = []
    s_buy = []
    s_sell = []

    print("Reading in time and prices from database.")

    for values in cursor.execute('''SELECT "time", "buy", "sell" FROM "prices"'''):

        s_time.append( values[0] )
        s_buy.append( values[1] )
        s_sell.append( values[2] )