create account

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

View this thread on: hive.blogpeakd.comecency.com
· @paulmoon410 ·
$0.31
'Making A Trading Bot' Part 2- Learning to Code
<center>![](https://images.ecency.com/DQmUzS18cvVuTV177wmSnpzXcSkBCcTxekz9BNdJ5vjgUQ8/image.png)</center>


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

````html 

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)
👍  , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorpaulmoon410
permlinkmaking-a-trading-bot-part
categoryhive-188262
json_metadata"{"app":"ecency/3.2.0-vision","tags":["hive-188262","neoxian","pimp","thgaming","blockchaingaming","hivehustlers","palnet","waivio","ctp","lassecash","archon","ecency","ecency"],"format":"markdown+html","image":["https://images.ecency.com/DQmUzS18cvVuTV177wmSnpzXcSkBCcTxekz9BNdJ5vjgUQ8/image.png"],"thumbnails":["https://images.ecency.com/DQmUzS18cvVuTV177wmSnpzXcSkBCcTxekz9BNdJ5vjgUQ8/image.png"],"description":"Making a trading bot for hive... but I am so out of my depths.","image_ratios":["1.7820"]}"
created2024-05-23 20:23:00
last_update2024-05-23 20:23:00
depth0
children4
last_payout2024-05-30 20:23:00
cashout_time1969-12-31 23:59:59
total_payout_value0.158 HBD
curator_payout_value0.156 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,443
author_reputation40,653,574,175,519
root_title"'Making A Trading Bot' Part 2- Learning to Code"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id133,881,818
net_rshares739,944,836,224
author_curate_reward""
vote details (26)
@arc7icwolf ·
Curated by @arc7icwolf.byte for the #LearnToCode Community.
properties (22)
authorarc7icwolf
permlinkre-paulmoon410-2024526t223354394z
categoryhive-188262
json_metadata{"tags":["hive-188262","neoxian","pimp","thgaming","blockchaingaming","hivehustlers","palnet","waivio","ctp","lassecash","archon","ecency","ecency"],"app":"ecency/3.2.0-vision","format":"markdown+html"}
created2024-05-26 20:33:54
last_update2024-05-26 20:33:54
depth1
children0
last_payout2024-06-02 20:33:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length59
author_reputation508,055,258,566,757
root_title"'Making A Trading Bot' Part 2- Learning to Code"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id133,949,832
net_rshares0
@strava2hive ·
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.
properties (22)
authorstrava2hive
permlinksdyqxr
categoryhive-188262
json_metadata{"app":"hiveblog/0.1"}
created2024-05-24 00:05:51
last_update2024-05-24 00:05:51
depth1
children2
last_payout2024-05-31 00:05:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length159
author_reputation30,416,414,992,927
root_title"'Making A Trading Bot' Part 2- Learning to Code"
beneficiaries
0.
accounthiveonboard
weight100
1.
accountocdb
weight100
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id133,885,423
net_rshares0
@paulmoon410 ·
It simplified it for me a lot
properties (22)
authorpaulmoon410
permlinkre-strava2hive-2024523t211114691z
categoryhive-188262
json_metadata{"type":"comment","tags":["ecency"],"app":"ecency/3.1.0-mobile","format":"markdown+html"}
created2024-05-24 01:11:15
last_update2024-05-24 01:11:15
depth2
children0
last_payout2024-05-31 01:11:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length29
author_reputation40,653,574,175,519
root_title"'Making A Trading Bot' Part 2- Learning to Code"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id133,886,360
net_rshares0
@paulmoon410 ·
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.
properties (22)
authorpaulmoon410
permlinkre-strava2hive-2024523t231737242z
categoryhive-188262
json_metadata{"type":"comment","tags":["ecency"],"app":"ecency/3.1.0-mobile","format":"markdown+html"}
created2024-05-24 03:17:39
last_update2024-05-24 03:17:39
depth2
children0
last_payout2024-05-31 03:17:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length115
author_reputation40,653,574,175,519
root_title"'Making A Trading Bot' Part 2- Learning to Code"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id133,888,579
net_rshares0