Python Forum
Can anyone tell me why this code isn't looping properly?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can anyone tell me why this code isn't looping properly?
#1
I made a basic buy bot for a crypto exchange. It searches a database and loops like I want it to, however when there is a trade that is triggered, the loop seems to break. I would like it to loop again even if there is an order made. Here is the code:

import sqlite3
import datetime
import sys
import platform
import time
import base64
import hashlib
import hmac
import urllib.request as urllib2
import dontshare_config
import requests

def calculate_average_score():
    # Establish a connection to the database
    conn = sqlite3.connect('C:/Users/Chris/Python/Python Projects/mock_database/crypto_data.db')

    # Create a cursor
    cursor = conn.cursor()

    # Calculate the datetime 5 minutes ago from the current time
    current_time = datetime.datetime.now()
    time_5_minutes_ago = current_time - datetime.timedelta(minutes=5)

    # Format the datetime objects to match the database format
    current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
    time_5_minutes_ago_str = time_5_minutes_ago.strftime("%Y-%m-%d %H:%M:%S")

    # Example: Calculate average score within the last 5 minutes
    cursor.execute("SELECT AVG(score) FROM crypto_data WHERE time BETWEEN ? AND ?",
                   (time_5_minutes_ago_str, current_time_str))
    average_score = cursor.fetchone()[0]

    # Close the connection
    conn.close()

    if average_score is not None:
        return average_score
    else:
        return 0  # Or any default value you want to use when average_score is None


def get_price(pair):
    url = f"https://api.kraken.com/0/public/Depth?pair={pair}"

    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()
        if 'result' in data:
            pair_data = data['result'][pair]
            bids = pair_data['bids']
            asks = pair_data['asks']

            highest_bid = float(bids[0][0])
            lowest_ask = float(asks[0][0])

            return highest_bid, lowest_ask
        else:
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return None

def make_buy_order_on_kraken(price):
    # TODO: Update with your buy order code from Kraken
    # Placeholder: Replace with code to execute buy order on Kraken
    # Example code:
    api_key = dontshare_config.api_key
    api_secret = base64.b64decode(dontshare_config.api_secret)

    api_domain = "https://api.kraken.com"
    api_path = "/0/private/"

    # PlaceOrder parameters
    api_endpoint = "AddOrder"
    api_parameters = f"pair=XXBTZUSD&type=buy&ordertype=limit&volume=0.0002&price={price}"

    api_nonce = str(int(time.time() * 1000))

    api_postdata = api_parameters + "&nonce=" + api_nonce
    api_postdata = api_postdata.encode('utf-8')

    api_sha256Data = api_nonce.encode('utf-8') + api_postdata
    api_sha256 = hashlib.sha256(api_sha256Data).digest()

    api_hmacSha512Data = api_path.encode('utf-8') + api_endpoint.encode('utf-8') + api_sha256
    api_hmacsha512 = hmac.new(api_secret, api_hmacSha512Data, hashlib.sha512)

    api_sig = base64.b64encode(api_hmacsha512.digest())

    api_url = api_domain + api_path + api_endpoint
    api_request = urllib2.Request(api_url, api_postdata)
    api_request.add_header("API-Key", api_key)
    api_request.add_header("API-Sign", api_sig)
    api_request.add_header("User-Agent", "Kraken REST API")

    print("DEBUG DATA     : ")
    print("api_url        : " + api_url)
    print("api_endpoint   : " + api_endpoint)
    print("api_parameters : " + api_parameters)
    print("")

    api_reply = urllib2.urlopen(api_request).read()
    api_reply = api_reply.decode()

    print("API JSON DATA:")
    print(api_reply)
    sys.exit(0)

def make_sell_order_on_kraken(price):
    # TODO: Update with your sell order code from Kraken
    # Placeholder: Replace with code to execute sell order on Kraken
    # Example code:
    api_key = dontshare_config.api_key
    api_secret = base64.b64decode(dontshare_config.api_secret)

    api_domain = "https://api.kraken.com"
    api_path = "/0/private/"

    # PlaceOrder parameters
    api_endpoint = "AddOrder"
    api_parameters = f"pair=XXBTZUSD&type=sell&ordertype=limit&volume=0.0002&price={price}"

    api_nonce = str(int(time.time() * 1000))

    api_postdata = api_parameters + "&nonce=" + api_nonce
    api_postdata = api_postdata.encode('utf-8')

    api_sha256Data = api_nonce.encode('utf-8') + api_postdata
    api_sha256 = hashlib.sha256(api_sha256Data).digest()

    api_hmacSha512Data = api_path.encode('utf-8') + api_endpoint.encode('utf-8') + api_sha256
    api_hmacsha512 = hmac.new(api_secret, api_hmacSha512Data, hashlib.sha512)

    api_sig = base64.b64encode(api_hmacsha512.digest())

    api_url = api_domain + api_path + api_endpoint
    api_request = urllib2.Request(api_url, api_postdata)
    api_request.add_header("API-Key", api_key)
    api_request.add_header("API-Sign", api_sig)
    api_request.add_header("User-Agent", "Kraken REST API")

    print("DEBUG DATA     : ")
    print("api_url        : " + api_url)
    print("api_endpoint   : " + api_endpoint)
    print("api_parameters : " + api_parameters)
    print("")

    api_reply = urllib2.urlopen(api_request).read()
    api_reply = api_reply.decode()

    print("API JSON DATA:")
    print(api_reply)
    sys.exit(0)

def execute_trading_logic():
    average_score = calculate_average_score()
    pair = "XXBTZUSD"

    if average_score >= 30:
        print("Average score is 30 or above. Making buy order on Kraken...")
        highest_bid, _ = get_price(pair)
        price = round(highest_bid + 0.01, 1)  # Round the price to 1 decimal place
        make_buy_order_on_kraken(price)
    elif average_score <= -30:
        print("Average score is -30 or below. Making sell order on Kraken...")
        _, lowest_ask = get_price(pair)
        price = round(lowest_ask - 0.01, 1)  # Round the price to 1 decimal place
        make_sell_order_on_kraken(price)
    else:
        print("No action required.")

while True:
    execute_trading_logic()
    time.sleep(300)  # Sleep for 5 minutes
Reply
#2
My guess would be that your code is hitting one of the sys.exit(0) calls: Line 108 & 154
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Virtual Assistant code is looping back in python ShishirModi 1 2,579 Oct-13-2020, 08:04 AM
Last Post: Nickd12

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020