I'm using ccxt kucoin futures to create_order with a limit order entry with this following logic:
``if name == "main": # Example: Create a long order at a specific limit price with a 15% stop loss and 25X leverage symbol = 'MATIC/USDT:USDT' entry_price = 0.7341 entry_size = 5 # Positive entry_size for opening a long position stop_loss_percentage = 0.15 # 15% stop loss leverage = 10 # 25X leverage
create_order_at_limit(symbol, entry_price, entry_size, stop_loss_percentage, leverage, order_type='long')
`
When I run the code, its successfully created an order for me but the order was close immidiately after.
I have tried to modify the leverages by checking the correct leverage tiers as follow:
def fetch_market_leverage_tiers(symbol: str): try: # Load markets if not already loaded exchange.load_markets()
# Get the market information for the specified symbol
market = exchange.market(symbol)
if not market['contract']:
raise ValueError(f"The symbol {symbol} does not represent a contract market.")
# Fetch the leverage tiers for the specified symbol
leverage_tiers = exchange.futuresPublicGetContractsRiskLimitSymbol({'symbol': market['id']})
return leverage_tiers['data']
except ccxt.BaseError as e:
print(f"Error fetching leverage tiers: {e}")
return None
Based on the output, I set my leverage size, and the order is still being canceled.
Here is my full create_order method:
`import ccxt
import os
import time
from typing import Optional
from dotenv import load_dotenv
# Fetch API credentials from environment variables
API_KEY = os.getenv("API_KEY")
SECRET_KEY = os.getenv("SECRET_KEY")
PASSPHRASE = os.getenv("PASSPHRASE")
# Create an instance of the Kucoin Futures exchange
exchange = ccxt.kucoinfutures({
'apiKey': API_KEY,
'secret': SECRET_KEY,
'password': PASSPHRASE,
'enableRateLimit': True # Adjust as needed
})
def fetch_server_time():
try:
# Fetch the server's timestamp
server_timestamp = exchange.fetch_time()
return server_timestamp
except ccxt.BaseError as e:
print(f"Error fetching server timestamp: {e}")
return None
def create_order_at_limit(symbol: str, entry_price: float, entry_size: float,
stop_loss_percentage: float = 0.15, leverage: int = 25,
order_type: str = 'long'):
try:
# Validate input parameters
if leverage <= 0:
raise ValueError("Leverage must be greater than 0.")
if entry_size <= 0:
raise ValueError("Entry size must be greater than 0.")
if stop_loss_percentage < 0 or stop_loss_percentage > 1:
raise ValueError("Stop loss percentage must be between 0 and 1.")
if order_type not in ['long', 'short']:
raise ValueError("Invalid order type. Use 'long' or 'short'.")
# Fetch the server's timestamp
server_timestamp = fetch_server_time()
if server_timestamp is None:
return
# Determine the side (buy or sell) based on the order type
side = 'buy' if order_type == 'long' else 'sell'
# Calculate stop loss price based on the entry price and stop loss percentage
stop_loss_price = entry_price * (1 - stop_loss_percentage)
# Prepare additional parameters for the order
params = {
'leverage': leverage,
'stopLossPrice': stop_loss_price,
'triggerType': 'mark', # Use 'mark' for stop loss orders
}
# Retrieve the current position for the symbol
positions = exchange.fetch_positions()
current_position = next((p for p in positions if p['symbol'] == symbol), None)
# Check if there is an open position for the given symbol
if current_position:
# Calculate the updated entry size based on the current position size
entry_size = entry_size - abs(current_position['size'])
if entry_size <= 0:
raise ValueError("Entry size must be greater than the current position size.")
# Place a limit order to enter a position
order_result = exchange.create_order(symbol, 'limit', side, entry_size, entry_price, params)
print("Order created successfully:")
print(f"Order ID: {order_result['id']}")
print(f"Entry Price: {entry_price}")
print(f"Entry Size: {entry_size}")
print(f"Stop Loss Price: {stop_loss_price}")
except ccxt.BaseError as e:
print(f"Error placing the order: {e}")
except ValueError as ve:
print(f"Invalid input: {ve}")
# Usage example:
if __name__ == "__main__":
# Example: Create a long order at a specific limit price with a 15% stop loss and 25X leverage
symbol = 'MATIC/USDT:USDT'
entry_price = 0.7341
entry_size = 5 # Positive entry_size for opening a long position
stop_loss_percentage = 0.15 # 15% stop loss
leverage = 10 # 25X leverage
create_order_at_limit(symbol, entry_price, entry_size, stop_loss_percentage, leverage, order_type='long')
`
What implementation did I miss?