Skip to content

Rounding error on 32-bit makes Order.size float instead of integer #954

Closed

Description

@IMYin

Discussed in #953

Originally posted by IMYin March 31, 2023
My trading target is futures, with a minimum trading size of 1 lot and a minimum unit of 300 per lot. When I trigger a certain signal, I only want to reduce my position instead of closing it completely. However, the parameter in the close function is a proportion value. So, if I hold a position of 7 lots and my size is 2100, the parameter set for self.position.close(portion=6/7), which is not wrong. But the result is that my position is 301, which is incorrect and causes a chain reaction of position errors later on.

image
The sample shown in the picture is incorrect.

The correct one should look like the following.
image

So I am wondering if it is possible to adjust the setting of the portion parameter?

Activity

  1. kernc commented on Apr 1, 2023

    @kernc
    Owner

    def close(self, portion: float = 1.):
    """Place new `Order` to close `portion` of the trade at next market price."""
    assert 0 < portion <= 1, "portion must be a fraction between 0 and 1"
    size = copysign(max(1, round(abs(self.__size) * portion)), -self.__size)
    order = Order(self.__broker, size, parent_trade=self, tag=self.__tag)
    self.__broker.orders.insert(0, order)

    >>> (1 - 6/7) * 2100
    300.0000000000001
    
    >>> from math import copysign
    >>> copysign(max(1, round(abs(2100) * (6/7))), -2100)
    -1800.0

    Looks like a rounding error on your platform. 32-bit OS by chance?

  2. added
    bugSomething isn't working
    on Feb 4, 2025
  3. changed the title [-]When closing a trade, can the size be specified as larger than an integer?[/-] [+]Rounding error on 32-bit makes Order.size float instead of integer[/+] on Feb 4, 2025
  4. added a commit that references this issue on Jul 12, 2025
  5. added a commit that references this issue on Mar 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions