Python / MT5, how to close half a position? - page 2

 

If you code it correctly it will work!

Go through your code with the debugger (knowing this is part of knowing to code!)

Code debugging:  https://www.metatrader5.com/en/metaeditor/help/development/debug
Error Handling and Logging in MQL5:  https://www.mql5.com/en/articles/2041
Tracing, Debugging and Structural Analysis of Source Code, scroll down to: "Launching and Debuggin": https://www.mql5.com/en/articles/272

What are the error messages?

Code debugging - Developing programs - MetaEditor Help
  • www.metatrader5.com
MetaEditor has a built-in debugger allowing you to check a program execution step by step (by individual functions). Place breakpoints in the code...
 

Well, here is my code (you can read it from def manageAlerts function) then it's very simple, only a BUY entry and the Half close entry:

from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
import json
import MetaTrader5 as mt5
import os
import json
import base.mt5_interface as mt5_interface


# Create your views here.
@api_view(['GET', 'POST'])
def getRoutes(request):
    routes = [
        '/api/tradealerts/'
    ]
    return Response(routes)


######################################
########## UTIL FUNCTIONS ############
######################################

def get_project_settings(importFilepath):
    if os.path.exists(os.path.join(os.getcwd()+"\\base",importFilepath)):
        f = open(os.path.join(os.getcwd()+"\\base",importFilepath), "r")
        project_settings = json.load(f)
        f.close()
        return project_settings
    else:
        return ImportError


def start_mt5(username, password, server):
    uname = int(username) # Username must be an int
    pword = str(password) # Password must be a string
    trading_server = str(server) # Server must be a string
    if mt5.initialize(login=uname, password=pword, server=trading_server):
        print("Trading Bot Starting")
        if mt5.login(login=uname, password=pword, server=trading_server):
            print("Trading Bot Logged in and Ready to Go!")
            return True
        else:
            print("Login Fail")
            quit()
            return PermissionError
    else:
        print("MT5 Initialization Failed")
        quit()
        return ConnectionAbortedError

def initialize_symbols(symbol_array):
    all_symbols = mt5.symbols_get()
    symbol_names = []
    for symbol in all_symbols:
        symbol_names.append(symbol.name)
    for provided_symbol in symbol_array:
        if provided_symbol in symbol_names:
            if mt5.symbol_select(provided_symbol, True):
                print(f"Sybmol {provided_symbol} enabled")
            else:
                return ValueError
        else:
            return SyntaxError
    return True

# Function to retrieve all open positions
def get_open_positions():
    positions = mt5.positions_get()
    return positions


######################################
########## END UTIL FUNCTIONS ########
######################################



######################################
########## ORDER FUNCTIONS ###########
######################################


def place_order(order_type, symbol, volume, price, stop_loss, take_profit, comment):    
    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": volume,
        "type": order_type,
        "price": round(price, 3),
        "sl": round(stop_loss, 3),
        "tp": round(take_profit, 3),
        "type_filling": mt5.ORDER_FILLING_IOC,
        "type_time": mt5.ORDER_TIME_GTC,
        "comment": comment,
    }
    order_result = mt5.order_send(request)
    if order_result[0] == 10009:
        print(f"Order for {symbol} successful")
    else:
        print(f"Error placing order. ErrorCode {order_result[0]}, Error Details: {order_result}")
    return order_result

def close_half_position(order_number, symbol, position_ticket):
    request = {
        "type" : mt5.ORDER_TYPE_SELL,
        "price" : mt5.symbol_info_tick(symbol).bid,
        "action" : mt5.TRADE_ACTION_DEAL,
        "symbol" : symbol,
        "volume" : 0.005,
        "position" : position_ticket,
        "deviation": 20,
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }
    order_result = mt5.order_send(request)
    if order_result[0] == 10009:
        print(f"Order for {symbol} successful")
    else:
        print(f"Error placing order. ErrorCode {order_result[0]}, Error Details: {order_result}")
    return order_result

######################################
########## END ORDER FUNCTIONS #######
######################################









#### This the function that receives the HTTP POST request from TradingView
@api_view(['GET', 'POST'])
def manageAlerts(request):

    # setting up the settigs for using mt5
    import_filepath = "settings.json"
    project_settings = get_project_settings(import_filepath)
    # start mt5
    start_mt5(project_settings["username"], project_settings["password"], project_settings["server"])
    # initialize symbols
    initialize_symbols(project_settings["symbols"])
    # select symbol to run strategy on
    symbol_for_strategy = project_settings['symbols'][0]
    # volume
    lot = 0.01
    # ask price
    price = mt5.symbol_info_tick(symbol_for_strategy).ask

    # if TradingView sends a BUY signal
    if (request.body.decode('utf-8') == "Buyy"):
        # if a position is already open, don't enter
        positions = mt5_interface.get_open_positions()
        if (len(positions) > 0):
            Response("request canceled, alreay a BUY order 'pending'")
        # sl & tp
        stop_loss = price - price/2
        take_profit = price + price/2
        # we send the order
        result = place_order(mt5.ORDER_TYPE_BUY, symbol_for_strategy, lot, price, stop_loss, take_profit, comment="JustBought")
        print(result)
        
    # if TradingView sends a close HALF signal
    if (request.body.decode('utf-8') == "CloseHalf"):
        # Get positions
        positions = get_open_positions()
        for position in positions:
            # close half position
            result = close_half_position(position[0], symbol_for_strategy, position.ticket)
            print(result)
    return Response("request")


Here are the outputs from the console:

Result from the BUY order:

OrderSendResult(retcode=10009, deal=32312451, order=36655310, volume=0.01, price=29011.53, bid=0.0, ask=0.0, comment='Request executed', request_id=2025472887, retcode_external=0, request=TradeRequest(action=1, magic=0, order=0, symbol='BTCUSD', volume=0.01, price=29011.53, stoplimit=0.0, sl=14505.765, tp=43517.295, deviation=0, type=0, type_filling=1, type_time=0, expiration=0, comment='JustBought', position=0, position_by=0))

Result from the Half close:

Error placing order. ErrorCode 10030, Error Details: OrderSendResult(retcode=10030, deal=0, order=0, volume=0.0, price=0.0, bid=0.0, ask=0.0, comment='Unsupported 
filling mode', request_id=0, retcode_external=0, request=TradeRequest(action=1, magic=0, order=0, symbol='BTCUSD', volume=0.005, price=29033.92, stoplimit=0.0, sl=0.0, tp=0.0, deviation=20, type=1, type_filling=2, type_time=0, expiration=0, comment='', position=36655310, position_by=0))


Regards

 

You have to learn how to debug your code:

Code debugging:  https://www.metatrader5.com/en/metaeditor/help/development/debug
Error Handling and Logging in MQL5:  https://www.mql5.com/en/articles/2041
Tracing, Debugging and Structural Analysis of Source Code, scroll down to: "Launching and Debuggin": https://www.mql5.com/en/articles/272

Have you looked up what 10030 means? It tells you where is your fault (at least one).

Code debugging - Developing programs - MetaEditor Help
  • www.metatrader5.com
MetaEditor has a built-in debugger allowing you to check a program execution step by step (by individual functions). Place breakpoints in the code...
 
Carl Schreiber #:

You have to learn how to debug your code:

Code debugging:  https://www.metatrader5.com/en/metaeditor/help/development/debug
Error Handling and Logging in MQL5:  https://www.mql5.com/en/articles/2041
Tracing, Debugging and Structural Analysis of Source Code, scroll down to: "Launching and Debuggin": https://www.mql5.com/en/articles/272

Have you looked up what 10030 means? It tells you where is your fault (at least one).

please review the former posts, I already know what the error means, and I have tested all the other filling types, none of them work
 
I think the error comes from the request syntax themselves, which is not "really" code related (I mean, it just amount to change one line in the request), I will open a new more high level thread
 
AYMERIC75 #:
I think the error comes from the request syntax themselves, which is not "really" code related (I mean, it just amount to change one line in the request), I will open a new more high level thread

It comes from your understanding of the filling type.

Please do a search, it was discussed a lot of times.

 

Indeed, I will try to understand this better

 

my BUY order:

action: TRADE_ACTION_DEAL

type: ORDER_TYPE_BUY

filling type: ORDER_FILLING_IOC

type time: ORDER_TIME_GTC

volume: 0.01


my "half close" order:

action: TRADE_ACTION_DEAL

type: ORDER_TYPE_SELL

filling type: ORDER_FILLING_RETURN

volume: 0.005

position: ticket_from_the_buy_order



ORDER_FILLING_RETURN should work here since the order is a market order ( ORDER_TYPE_SELL)


 
AYMERIC75 #:

my BUY order:

action: TRADE_ACTION_DEAL

type: ORDER_TYPE_BUY

filling type: ORDER_FILLING_IOC

type time: ORDER_TIME_GTC

volume: 0.01


my "half close" order:

action: TRADE_ACTION_DEAL

type: ORDER_TYPE_SELL

filling type: ORDER_FILLING_RETURN

volume: 0.005

position: ticket_from_the_buy_order



ORDER_FILLING_RETURN should work here since the order is a market order ( ORDER_TYPE_SELL)


Why are you using a different filling mode for the close ?

You can only use allowed filling mode according to the symbol's settings. See https://www.mql5.com/en/docs/constants/environment_state/marketinfoconstants#symbol_filling_mode

Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Symbol Properties
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Symbol Properties
  • www.mql5.com
Symbol Properties - Environment State - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
AYMERIC75 #:

my BUY order:

action: TRADE_ACTION_DEAL

type: ORDER_TYPE_BUY

filling type: ORDER_FILLING_IOC

type time: ORDER_TIME_GTC

volume: 0.01


my "half close" order:

action: TRADE_ACTION_DEAL

type: ORDER_TYPE_SELL

filling type: ORDER_FILLING_RETURN

volume: 0.005

position: ticket_from_the_buy_order



ORDER_FILLING_RETURN should work here since the order is a market order ( ORDER_TYPE_SELL)


  1. If you post code please use Alt+S or the code button:
  2. Your first post about this problem was from Apr. 26. It took me less than a minute to find a working example in the Codebase: https://www.mql5.com/en/code/35335
  3. Searching is our AI.
  4. To search, copy, paste, and amend is easier to learn than to code, its incredibly much faster but and it's a good beginning to learn coding!
closing partially script and Stop loss to Break Even point
closing partially script and Stop loss to Break Even point
  • www.mql5.com
closing partially script and Stop loss to Break Even point