Unable to Create Trade on OKX Exchange

·

Trading automation has become a cornerstone for modern crypto traders, especially when leveraging platforms like OKX with algorithmic tools such as Freqtrade. However, users occasionally encounter technical roadblocks — one of the most common being the inability to create live trades on the OKX exchange when using futures and isolated margin modes. This article dives into the root cause of this specific issue, offers a clear resolution path, and provides best practices to ensure smooth, uninterrupted automated trading.

Understanding the Error: "posSide Argument Required"

When attempting to execute a live trade using Freqtrade with OKX futures, you may encounter an error similar to:

okx setLeverage() requires the posSide argument to be either "long" or "short"

This message indicates that the CCXT library, which Freqtrade uses to communicate with exchanges, is unable to set leverage because it lacks a required parameter: posSide. The posSide (position side) defines whether your trade is part of a long or short position — a mandatory field in OKX’s API for futures trading.

Even if your strategy logic correctly identifies entry signals, the trade fails at the execution stage due to this missing configuration.

Environment Overview

The issue commonly appears in setups like:

While these versions are generally stable, they highlight a known limitation in how older or default configurations handle OKX's position-based futures model.

👉 Discover how to fix common API errors in automated crypto trading

Root Cause: Position Mode Mismatch

OKX supports multiple position modes:

  1. One-Way Mode: Single position per symbol (either long or short).
  2. Hedge Mode: Separate long and short positions allowed.

To use leverage effectively via API, OKX requires explicit specification of the posSide — even in one-way mode. If Freqtrade doesn’t pass this parameter during the setLeverage() call, the request fails.

The core problem lies not in your credentials or network setup, but in missing configuration directives that inform CCXT and Freqtrade about your intended position strategy.

Solution: Configure Position Side in Freqtrade

To resolve the error, you must explicitly define the posSide in your strategy or configuration so that leverage can be set correctly before trade creation.

Step 1: Update Your Strategy Code

In your Freqtrade strategy file (e.g., SomeStrategy.py), override the set_leverage() method or ensure the exchange parameters include posSide.

def custom_entry_signals(self, pair: str, current_time: 'datetime', current_rate: float,
                         proposed_rate: float, side: str, **kwargs) -> dict:
    # Ensure position side is passed
    return {
        'enter_tag': 'long_entry',
        'side': side,
        'leverage': 5,  # Example leverage
        'order_tag': f'{side}_pos',
        'position_adjustment': True,
        'data': {'posSide': 'long' if side == 'buy' else 'short'}
    }
Note: In futures trading on OKX, “buy” does not always mean “long” unless explicitly defined under Hedge Mode. Always map side to posSide.

Step 2: Modify Config to Include Headers (Optional)

Ensure your config includes proper options for CCXT:

"exchange": {
  "name": "okx",
  "key": "your_api_key",
  "secret": "your_api_secret",
  "password": "your_api_password",
  "ccxt_config": {
    "options": {
      "defaultType": "future"
    }
  },
  "ccxt_fapi_params": {
    "defaultType": "swap",
    "options": {
      "adjustForTimeDifference": true,
      "defaultPosSide": "long"
    }
  }
}

Setting "defaultPosSide": "long" tells CCXT to assume long positions unless otherwise specified.

Step 3: Force Position Side in Order Creation

If using a custom order template, ensure each order includes:

params = {
    'posSide': 'Long'  # or 'Short'
}

You can inject this via custom_order_options() in your strategy:

def custom_order_options(self, pair: str, order_type: str, *args, **kwargs):
    return {'posSide': 'Long'}

👉 Learn how to optimize API settings for seamless futures trading

Best Practices to Prevent Future Issues

Avoiding this error in future deployments involves proactive configuration and awareness of exchange-specific requirements.

Use Latest Stable Versions

Upgrade to the latest stable versions:

Newer versions have improved support for OKX’s position-side logic and auto-detect common mode mismatches.

Enable Debug Logging

Always run with verbose logging enabled:

freqtrade trade --strategy SomeStrategy -v

This allows you to trace exactly where the failure occurs — whether during leverage setting, order placement, or wallet sync.

Validate Exchange Capabilities

Use CCXT directly to test connectivity and capabilities:

import ccxt
exchange = ccxt.okx({
    'apiKey': 'your_key',
    'secret': 'your_secret',
    'password': 'your_pass',
    'options': {'defaultType': 'swap'}
})
markets = exchange.load_markets()
print(exchange.has['setLeverage'])  # Should return True

This helps isolate issues between Freqtrade and underlying API behavior.

Frequently Asked Questions (FAQ)

Why does OKX require posSide while other exchanges don’t?

OKX enforces strict position management for risk control. Unlike spot trading or simpler futures models, OKX differentiates between one-way and hedge modes, requiring explicit position side declaration for accurate margin calculation.

Can I trade without setting leverage?

While possible in some cases, OKX mandates leverage configuration for futures contracts. Skipping this step results in rejected orders. Always set appropriate leverage based on your risk tolerance.

Does Freqtrade support hedge mode on OKX?

Yes, but only with correct configuration. You must enable dual-sided positions and ensure every order specifies its posSide. Otherwise, conflicts arise when opening both long and short positions simultaneously.

Is this issue specific to Raspbian or Python version?

No. While resource-constrained environments like Raspbian may slow execution, the error stems from API logic — not OS or Python version. However, outdated libraries (like CCXT < 2.8) increase likelihood of encountering it.

How do I check my current position mode on OKX?

Log into your OKX account:

  1. Go to Futures Trading.
  2. Click the gear/settings icon.
  3. Check Position Mode: One-way or Hedge Mode.
    Ensure your bot matches this setting.

Can I automate mode switching?

Not recommended. Switching between one-way and hedge modes while live trading can cause unexpected behavior. Choose one mode and configure your bot accordingly.


By addressing the posSide requirement head-on and ensuring proper integration between Freqtrade, CCXT, and OKX’s API rules, you can eliminate trade creation failures and maintain reliable automated performance.

👉 Start optimizing your trading bot with advanced API integration techniques

Remember: Automated trading success depends not just on strategy quality, but on precise technical execution. Stay updated, test thoroughly, and configure deliberately for optimal results.