Assistance Needed to Fix Kraken Futures Trading Bot Code

Job ID: 38596667

Budget: $250 – $750 USD

I'm seeking assistance in resolving issues with a Python Flask application I've been developing, which is intended to place orders on Kraken Futures via their API. Despite multiple attempts and revisions, I'm still encountering errors that prevent the application from functioning correctly. Below, I've outlined the details of the problem and included the latest version of the code.

Problem Description:

Error Message: When sending a POST request to the /webhook endpoint, I receive the following error response:

json
Kopiera kod
{
"message": {
"error": "requiredArgumentMissing",
"result": "error",
"serverTime": "2024-09-20T15:07:23.508Z"
},
"status": "error"
}
Context: The application is supposed to receive webhook signals (e.g., "buy_eth") and then place a corresponding order on Kraken Futures. Despite adjusting the code multiple times, the API continues to return the requiredArgumentMissing error.

What I've Tried:

Adjusted the Request Payload: Ensured that all required parameters are included in the API request. This includes orderType, symbol, side, size, and cliOrdId.

Checked Data Types: Made sure that numerical values are sent as integers or floats where appropriate, and strings where required.

Signature Generation: Updated the method for generating the HMAC signature according to Kraken's documentation, using HMAC-SHA256 and including the correct requestPath, nonce, and postData.

Endpoint URLs: Verified that the API endpoints and request paths are correctly specified as per Kraken's API documentation.

Error Handling: Added try-except blocks to catch exceptions and print out more detailed error messages for debugging.

Current Code:

Below is the latest version of the code I'm using:
--------------------------------

import requests
import hmac
import hashlib
import time
import base64
import json
from flask import Flask, request, jsonify

# Kraken Futures API URL
API_URL = 'https://futures.kraken.com/derivatives/api/v3'

# My Kraken Futures API keys
API_KEY = "YOUR_PUBLIC_KEY_HERE"
API_SECRET = "YOUR_PRIVATE_KEY_HERE"

app = Flask(__name__)

# Function to create signature
def sign_futures_request(path, nonce, postdata):
message = path + nonce + postdata
secret_key = base64.b64decode(API_SECRET)
signature = hmac.new(secret_key, message.encode('utf-8'), hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest()).decode()
return signature_b64

# Function to place an order on Kraken Futures
def place_futures_order(symbol, size, side):
try:
path = '/sendorder'
nonce = str(int(time.time() * 1000))
postdata = {
"orderType": "mkt", # 'mkt' for market order
"symbol": symbol,
"side": side, # 'buy' or 'sell'
"size": size, # Number of contracts as an integer
"cliOrdId": nonce # Unique client order ID
}

# Serialize postdata to a JSON string
postdata_str = json.dumps(postdata, separators=(',', ':'))

# Correct requestPath for signature
requestPath = '/derivatives/api/v3' + path

signature = sign_futures_request(requestPath, nonce, postdata_str)

headers = {
'APIKey': API_KEY,
'Nonce': nonce,
'Authent': signature,
'Content-Type': 'application/json'
}

url = 'https://futures.kraken.com' + requestPath
response = requests.post(url, headers=headers, data=postdata_str)
response.raise_for_status() # Raise exception for HTTP errors

return response.json()

except Exception as e:
return {"error": str(e)}

# Route to receive webhook from TradingView
@app.route('/webhook', methods=['POST'])
def webhook():
try:
data = request.get_json()
if data and 'signal' in data:
signal = data['signal']
order = None

if signal == 'buy_eth':
order = place_futures_order('PI_ETHUSD', 1, 'buy') # Buy 1 contract of ETH
elif signal == 'sell_eth':
order = place_futures_order('PI_ETHUSD', 1, 'sell') # Sell 1 contract of ETH
else:
return jsonify({"status": "error", "message": "Invalid signal"}), 400

# Check if the order was successful
if order and 'error' not in order:
return jsonify({"status": "success", "order": order}), 200
else:
return jsonify({"status": "error", "message": order}), 400
else:
return jsonify({"status": "error", "message": "Invalid data"}), 400
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500

# Run the Flask server on port 5000
if __name__ == "__main__":
app.run(port=5000)

-------------------------------------------------------------------------------------
What I Need Help With:

Debugging the Error: Identify why the API is returning the requiredArgumentMissing error despite including all required parameters.

Verifying Signature Generation: Ensure that the HMAC signature is generated correctly according to Kraken Futures API specifications.

Confirming API Request Format: Verify that the request payload and headers are correctly formatted and that the endpoint URLs are accurate.

Testing the Application: Help me test the application to ensure that it can successfully place buy and sell orders when receiving webhook signals.

Additional Information:

API Keys: I can provide my API keys for testing purposes. I understand the security implications and will regenerate them after the issue is resolved.

Environment: The application is run locally on a Windows machine using Python 3.x.

API Documentation: The Kraken Futures API documentation can be found at https://docs.futures.kraken.com/.

Error Details:

Latest Error Response:

{
"message": {
"error": "requiredArgumentMissing",
"result": "error",
"serverTime": "2024-09-20T15:07:23.508Z"
},
"status": "error"
}
Curl Command Used:

curl -X POST -H "Content-Type: application/json" -d "{\"signal\": \"buy_eth\"}" http://localhost:5000/webhook
Contact Information:

Please let me know if you need any additional information or clarification. I appreciate your expertise and assistance in resolving this issue.

Thank you!
Related categories: Python Data Entry API Testing Cryptocurrency