We’re rewarding the question askers & reputations are being recalculated! Read more.
8 Change title to describe the code, rather than a request for changes.
| link

Use math to project Project price rather than a loopof publicly traded contract

    Post Reopened by RubberDuck, 410_Gone, Dannnno, IEatBagels, VisualMelon
    Post Closed as "off-topic" by πάντα ῥεῖ, t3chb0t, pacmaninbw, Toby Speight, VisualMelon
7 Added code sample
source | link

You see most of the contract's properties in the unit test below. Position is a Property set by the execution engine that holds a tuple:

Position=(pos:0,avgCost:0.00M)

Commision per trade is provided by the exchange and is a property holding the value

CommisionPertradeclass Contract
{get;set;
    public string Symbol { get; set; }

This method on the contract calculates the price based on a projected P&L

    public string Currency { get; set; }
    public decimal CommisionPerTrade { get; set; }
    public decimal MinTick { get; set; }
    public string PriceFormat { get; set; }

    private (int pos, decimal avgCost) position;

    public void AssignPossition(int shares, decimal averagePrice)
    {
        position = (shares, averagePrice);
    }

    public (int pos, decimal avgCost) Position => position;

    /// <summary>
    /// Get an exchange acceptable price for a contract for a given Profit & Loss value.
    /// The price depends on the rounding of a given contract, possible minimum - ticks are 100, 10, 1.0, 0.1, 0.01, 0.001, 0.0005
    /// </summary>
    /// <param name="pnl">The P&L that is aimed for.</param>
    /// <param name="mayBeHigher">if set to <c>true</c> then loss may be higher as well as profit to take the next acceptable 
    /// contract price else accept less rather them more.</param>
    /// <returns>a acceptable price at a given Min-Tick range that would get a approximate P&L</returns>
    /// <remarks>Please note that loss is a negative number, loss may be higher is actually a lower number as a loss of -100 is 
    /// higher than a loss of -50</remarks> 
    public bool TryGetPriceAtPnl(decimal pnl, bool mayBeHigher, out double price)
    {

        if ((Math.Abs(pnl) <= CommisionPerTrade && mayBeHigher == false)

            || (Position.avgCost == 0 || Position.pos == 0))
        {
            price = 0;
            return false;
        }


        //the current price paid for the contract
        decimal priceAtPnl = Position.avgCost;

        //start with deducting the commission that will need to be paid
        decimal sum = -CommisionPerTrade;

        //get the Price for minimal price change (min-tick) in the current position on a contract
        //positions when short contain negative values so best to take abs values
        decimal pnlPerTick = (Math.Abs(Position.pos) *( (Position.avgCost + MinTick))
                            - (Math.Abs(Position.pos) * Position.avgCost);

        if (position.pos > 0)// long trade
        {

            if (pnl > 0) //profit target
            {
                //positive P&L 
                while ((!mayBeHigher && sum + pnlPerTick <= pnl) || (mayBeHigher && sum <= pnl))
                {
                    sum += pnlPerTick;
                    priceAtPnl += MinTick;//next allowed price by adding the minimum price change
                }
            }
            else //loss target
            {
                //when a negative P&L "may be higher" then this actually is, and must be, a lower value
                while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
                {
                    sum -= pnlPerTick;
                    priceAtPnl -= MinTick;//previous allowed price by subtracting the minimum price change
                }
            }
        }
        else // short trade
        {
            if (pnl > 0) //profit target
            {
                //positive P&L 
                while ((!mayBeHigher && sum + pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
                {
                    sum += pnlPerTick;
                    priceAtPnl -= MinTick;//next allowed price by adding the minimum price change
                }
            }
            else //loss target
            {
                //when a negative P&L "may be higher" then this actually is, and must be, a lower value
                while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
                {
                    sum -= pnlPerTick;
                    priceAtPnl += MinTick;//previous allowed price by subtracting the minimum price change
                }
            }


        }

        //can't have floating point imprecision but need to return a double so cast the decimal to a double
    price=    price = Convert.ToDouble(priceAtPnl);
        return true;
    }

}

You see most of the contract's properties in the unit test below. Position is a Property set by the execution engine that holds a tuple:

Position=(pos:0,avgCost:0.00M)

Commision per trade is provided by the exchange and is a property holding the value

CommisionPertrade {get;set;}

This method on the contract calculates the price based on a projected P&L

/// <summary>
/// Get an exchange acceptable price for a contract for a given Profit & Loss value.
/// The price depends on the rounding of a given contract, possible minimum - ticks are 100, 10, 1.0, 0.1, 0.01, 0.001, 0.0005
/// </summary>
/// <param name="pnl">The P&L that is aimed for.</param>
/// <param name="mayBeHigher">if set to <c>true</c> then loss may be higher as well as profit to take the next acceptable 
/// contract price else accept less rather them more.</param>
/// <returns>a acceptable price at a given Min-Tick range that would get a approximate P&L</returns>
/// <remarks>Please note that loss is a negative number, loss may be higher is actually a lower number as a loss of -100 is 
/// higher than a loss of -50</remarks> 
public bool TryGetPriceAtPnl(decimal pnl, bool mayBeHigher, out double price)
{

    if ((Math.Abs(pnl) <= CommisionPerTrade && mayBeHigher == false)

        || (Position.avgCost == 0 || Position.pos == 0))
    {
        price = 0;
        return false;
    }


    //the current price paid for the contract
    decimal priceAtPnl = Position.avgCost;

    //start with deducting the commission that will need to be paid
    decimal sum = -CommisionPerTrade;

    //get the Price for minimal price change (min-tick) in the current position on a contract
    //positions when short contain negative values so best to take abs values
    decimal pnlPerTick = (Math.Abs(Position.pos) *( Position.avgCost + MinTick))
                        - (Math.Abs(Position.pos) * Position.avgCost);

    if (position.pos > 0)// long trade
    {

        if (pnl > 0) //profit target
        {
            //positive P&L 
            while ((!mayBeHigher && sum + pnlPerTick <= pnl) || (mayBeHigher && sum <= pnl))
            {
                sum += pnlPerTick;
                priceAtPnl += MinTick;//next allowed price by adding the minimum price change
            }
        }
        else //loss target
        {
            //when a negative P&L "may be higher" then this actually is, and must be, a lower value
            while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
            {
                sum -= pnlPerTick;
                priceAtPnl -= MinTick;//previous allowed price by subtracting the minimum price change
            }
        }
    }
    else // short trade
    {
        if (pnl > 0) //profit target
        {
            //positive P&L 
            while ((!mayBeHigher && sum + pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
            {
                sum += pnlPerTick;
                priceAtPnl -= MinTick;//next allowed price by adding the minimum price change
            }
        }
        else //loss target
        {
            //when a negative P&L "may be higher" then this actually is, and must be, a lower value
            while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
            {
                sum -= pnlPerTick;
                priceAtPnl += MinTick;//previous allowed price by subtracting the minimum price change
            }
        }


    }

    //can't have floating point imprecision but need to return a double so cast the decimal to a double
    price= Convert.ToDouble(priceAtPnl);
    return true;
}
class Contract
{
    public string Symbol { get; set; }
    public string Currency { get; set; }
    public decimal CommisionPerTrade { get; set; }
    public decimal MinTick { get; set; }
    public string PriceFormat { get; set; }

    private (int pos, decimal avgCost) position;

    public void AssignPossition(int shares, decimal averagePrice)
    {
        position = (shares, averagePrice);
    }

    public (int pos, decimal avgCost) Position => position;

    /// <summary>
    /// Get an exchange acceptable price for a contract for a given Profit & Loss value.
    /// The price depends on the rounding of a given contract, possible minimum - ticks are 100, 10, 1.0, 0.1, 0.01, 0.001, 0.0005
    /// </summary>
    /// <param name="pnl">The P&L that is aimed for.</param>
    /// <param name="mayBeHigher">if set to <c>true</c> then loss may be higher as well as profit to take the next acceptable 
    /// contract price else accept less rather them more.</param>
    /// <returns>a acceptable price at a given Min-Tick range that would get a approximate P&L</returns>
    /// <remarks>Please note that loss is a negative number, loss may be higher is actually a lower number as a loss of -100 is 
    /// higher than a loss of -50</remarks> 
    public bool TryGetPriceAtPnl(decimal pnl, bool mayBeHigher, out double price)
    {

        if ((Math.Abs(pnl) <= CommisionPerTrade && mayBeHigher == false)

            || (Position.avgCost == 0 || Position.pos == 0))
        {
            price = 0;
            return false;
        }


        //the current price paid for the contract
        decimal priceAtPnl = Position.avgCost;

        //start with deducting the commission that will need to be paid
        decimal sum = -CommisionPerTrade;

        //get the Price for minimal price change (min-tick) in the current position on a contract
        //positions when short contain negative values so best to take abs values
        decimal pnlPerTick = (Math.Abs(Position.pos) * (Position.avgCost + MinTick))
                            - (Math.Abs(Position.pos) * Position.avgCost);

        if (position.pos > 0)// long trade
        {

            if (pnl > 0) //profit target
            {
                //positive P&L 
                while ((!mayBeHigher && sum + pnlPerTick <= pnl) || (mayBeHigher && sum <= pnl))
                {
                    sum += pnlPerTick;
                    priceAtPnl += MinTick;//next allowed price by adding the minimum price change
                }
            }
            else //loss target
            {
                //when a negative P&L "may be higher" then this actually is, and must be, a lower value
                while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
                {
                    sum -= pnlPerTick;
                    priceAtPnl -= MinTick;//previous allowed price by subtracting the minimum price change
                }
            }
        }
        else // short trade
        {
            if (pnl > 0) //profit target
            {
                //positive P&L 
                while ((!mayBeHigher && sum + pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
                {
                    sum += pnlPerTick;
                    priceAtPnl -= MinTick;//next allowed price by adding the minimum price change
                }
            }
            else //loss target
            {
                //when a negative P&L "may be higher" then this actually is, and must be, a lower value
                while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
                {
                    sum -= pnlPerTick;
                    priceAtPnl += MinTick;//previous allowed price by subtracting the minimum price change
                }
            }


        }

        //can't have floating point imprecision but need to return a double so cast the decimal to a double
        price = Convert.ToDouble(priceAtPnl);
        return true;
    }

}
6 edited body
source | link

I have to project the price for a publicly traded contract when the price should be approximately matching the targeted profit or loss. I have written the following code, runs under 0.02MS02ms.. could be a faster and could be a bit more elegant as the code will get slower progressively depending on the iterations needed. I have documented the code, hope that it makes sense.

I have to project the price for a publicly traded contract when the price should be approximately matching the targeted profit or loss. I have written the following code, runs under 0.02MS.. could be a faster and could be a bit more elegant as the code will get slower progressively depending on the iterations needed. I have documented the code, hope that it makes sense.

I have to project the price for a publicly traded contract when the price should be approximately matching the targeted profit or loss. I have written the following code, runs under 0.02ms.. could be a faster and could be a bit more elegant as the code will get slower progressively depending on the iterations needed. I have documented the code, hope that it makes sense.

5 added 77 characters in body
source | link
4 altered title based on commend
source | link
3 altered title based on commend
| link
2 edited title
| link
1
source | link