'Making A Trading Bot' Part 2- Learning to Code

in Learn to Code6 months ago

So @strava2hive pointed me out to Beem... So I started piddling. Updated the code a little.


import pandas as pd
import time
import logging
from beem import Hive
from beem.account import Account
from beem.market import Market
from beem.transactionbuilder import TransactionBuilder

# Configure logging
logging.basicConfig(level=logging.INFO, filename='trading_bot.log',
                    format='%(asctime)s - %(levelname)s - %(message)s')

# Initialize Hive instance
hive = Hive()

def get_market_history(symbol, bucket_seconds, start, end):
    market = Market()
    return market.get_market_history(bucket_seconds, start, end)

def get_signal(data):
    data['SMA50'] = data['close'].rolling(window=50).mean()
    data['SMA200'] = data['close'].rolling(window=200).mean()

    if data['SMA50'].iloc[-1] > data['SMA200'].iloc[-1]:
        return 'buy'
    elif data['SMA50'].iloc[-1] < data['SMA200'].iloc[-1]:
        return 'sell'
    else:
        return 'hold'

def fetch_data(symbol, bucket_seconds, start, end):
    market_data = get_market_history(symbol, bucket_seconds, start, end)
    df = pd.DataFrame(market_data)
    df['date'] = pd.to_datetime(df['open'], unit='s')
    df.set_index('date', inplace=True)
    df['close'] = df['close_base'] / df['close_quote']
    return df

def check_transaction_status(transaction_id):
    tx = TransactionBuilder()
    try:
        tx.get_transaction(transaction_id)
        return "confirmed"
    except:
        return "unknown"

def get_account_balance(account_name, symbol):
    account = Account(account_name)
    balance = account.get_balance(symbol)
    return balance

def buy(symbol, amount, account_name):
    account = Account(account_name)
    market = Market()
    order = market.buy(amount, symbol, account_name=account_name)
    logging.info(f'Bought {amount} of {symbol} for account {account_name}')
    return order['transaction_id']

def sell(symbol, amount, account_name):
    account = Account(account_name)
    market = Market()
    order = market.sell(amount, symbol, account_name=account_name)
    logging.info(f'Sold {amount} of {symbol} for account {account_name}')
    return order['transaction_id']

def execute_trade(signal, symbol, amount, account_name):
    try:
        if signal == 'buy':
            transaction_id = buy(symbol, amount, account_name)
        elif signal == 'sell':
            transaction_id = sell(symbol, amount, account_name)

        # Check transaction status
        status = check_transaction_status(transaction_id)
        logging.info(f'Transaction status for {transaction_id}: {status}')
    except Exception as e:
        logging.error(f'Error executing trade: {e}')

def run_bot(symbol, amount, account_name, bucket_seconds, interval=60):
    while True:
        try:
            end = int(time.time())
            start = end - (bucket_seconds * 200)
            data = fetch_data(symbol, bucket_seconds, start, end)
            signal = get_signal(data)
            if signal != 'hold':
                execute_trade(signal, symbol, amount, account_name)
            time.sleep(interval)
        except Exception as e:
            logging.error(f'Error in run_bot loop: {e}')
            time.sleep(interval)

# Run the bot
run_bot('BEE', 10, 'alice', 86400)  # Example with daily buckets (86400 seconds)
Sort:  

hahaha, I'm helpful...Yay!!! Glad I was able to assist. Yeah, I have been using beem for a little while and it really simplifies things when working with Hive.

It simplified it for me a lot

Ok ok... So your ever work with Flask on Beem? To put a bot on my geocities account I have some work to do with it.

Curated by @arc7icwolf.byte for the #LearnToCode Community.