How to Place a Strategy Order via Webhook in Algomojo Using Python

Algomojo allows traders to execute strategies using webhooks, providing seamless integration with trading systems. In this blog, we’ll explore how to send strategy orders via webhook in Python using the requests library.

πŸ“Œ Overview

The function PlaceStrategyOrder sends a BUY/SELL order with a specified date to the Algomojo webhook. Users can automate their strategy execution by integrating this function into their trading system.

πŸš€ Improved Python Code for Placing a Strategy Order

Here’s the optimized function:

import requests
import json 

def PlaceStrategyOrder(webhook_url, date, action):
    try:
        payload = {
            "date": date,
            "action": action
        }
        
        headers = {
            "Content-Type": "application/json"
        }
        
        response = requests.post(webhook_url, json=payload, headers=headers)
        response_data = response.json()  # Parse JSON response
        
        if response.status_code == 200 and response_data.get("status") == "success":
            return f"Order placed successfully: {response_data}"
        else:
            return f"Error placing order: {response_data.get('error_msg', 'Unknown error')}"
        
    except requests.exceptions.RequestException as e:
        return f"Network error: {e}"
    except json.JSONDecodeError:
        return "Error decoding response JSON"
    except Exception as e:
        return f"Unexpected error: {e}"

πŸ”₯ Key Improvements

βœ… Better Error Handling – Catches network errors, JSON decoding errors, and unexpected exceptions.
βœ… Validates HTTP Status Code – Ensures response status is 200 OK before checking for success.
βœ… Handles API Response Properly – Parses JSON correctly and extracts error messages when necessary.


πŸ“Œ How to Run the Python Function and Call It Correctly

1️⃣ Install Python and Required Libraries

Make sure you have Python installed on your system. If not, download it from Python.org.

Next, install the required requests library by running this command in your terminal or command prompt:

pip install requests

2️⃣ Where to Keep the Function Source?

  • Create a separate Python file (e.g., strategy_order.py) and save the function inside it.
  • This makes it reusable for multiple scripts.

strategy_order.py

import requests
import json 

def PlaceStrategyOrder(webhook_url, date, action):
    try:
        payload = {
            "date": date,
            "action": action
        }
        
        headers = {
            "Content-Type": "application/json"
        }
        
        response = requests.post(webhook_url, json=payload, headers=headers)
        response_data = response.json()
        
        if response.status_code == 200 and response_data.get("status") == "success":
            return f"Order placed successfully: {response_data}"
        else:
            return f"Error placing order: {response_data.get('error_msg', 'Unknown error')}"
        
    except requests.exceptions.RequestException as e:
        return f"Network error: {e}"
    except json.JSONDecodeError:
        return "Error decoding response JSON"
    except Exception as e:
        return f"Unexpected error: {e}"

3️⃣ How to Call the Function in place_order.py

Now, create another Python file (place_order.py) and call the function from strategy_order.py.

place_order.py

from strategy_order import PlaceStrategyOrder

# Copy and paste the webhook URL from the strategy screen
webhook_url = "<YOUR_WEBHOOK_URL>"

# Define order parameters
date = "2025-03-18 15:30:00"  # Set the order execution date and time
action = "BUY"  # Choose between "BUY" or "SELL"

# Place the strategy order
response = PlaceStrategyOrder(webhook_url, date, action)

# Print the response from the webhook
print(response)

4️⃣ Run the Python Script

Save both files in the same directory and run place_order.py:

python place_order.py

If the order is successfully placed, you will see:

{
    "status": "success",
    "data": {
        "signal_ids": [
            3516986,
            3516987
        ]
    }
}

If there is an error, it will return:

{
    "status": "error",
    "error_msg": "Strategy Code does not exist/inactive",
    "error_type": "E"
}

πŸ“Œ Common Issues & Fixes

❌ requests.exceptions.ConnectionError: [Errno 110] Connection timed out

βœ” Fix: Check your internet connection or ensure the webhook URL is correct.

❌ Error decoding response JSON

βœ” Fix: The API response may not be valid JSON. Use print(response.text) to inspect the output.

❌ Error placing order: Strategy Code does not exist/inactive

βœ” Fix: Ensure the webhook URL is correct and your strategy is active in Algomojo.


🎯 Conclusion

By using this Python function, traders can seamlessly integrate Algomojo webhooks into their trading automation. This ensures fast, reliable, and accurate order execution.

πŸš€ Start automating your strategy orders today! Let us know if you need further enhancements or support.

πŸ”— Learn More: Algomojo API Documentation

Leave a Comment

Your email address will not be published. Required fields are marked *