Profit Estimate
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kaigouthro
//@version=5

// @description Simple profit Estimatr. Engages when Position != 0
// and holds until posittion is na/0... 
// if position changes sizes, it will update automatically and adjust.
// it has an input for comission to estmate exit fees
library("profitestimate",true)

// @function Get a new Average position Price
// @param    _sizewas    (float) the position prior
// @param    _delta      (float) the order amount
// @param    _pricewas   (float) the prior price
// @param    _newprice   (float) the price of order 
// @returns  New Avg Price
export update_avgprice(float _sizewas, float _delta, float _pricewas, float _newprice) =>
    (_sizewas * _pricewas + _delta * _newprice) / (_sizewas + _delta)


// @function Position Net Profit Net Commission, automatic on/off if position != 0
// @param    _position	  (float)  position size (total or margin size)
// @param    _commission  (float)  % where (0.1 = 0.1%)
// @param    _leverage	  (float)  optional if leveraged, default 1x
// @param    _fullqty     (bool)   if position entered is tottal trade size default is margin qty (1/lev)
// @returns  quote value of profit 
export amount(float _position, float _close, float _commission, float _leverage = 1, bool _fullqty = false) =>
	var _price = float(na)
    var _size  = float(na)
    var _new = true
    _price := nz(_price)
    _size  := nz(_size)
    _new := _position != _size 
    switch
        _new  =>
            _price    := update_avgprice(_size,_position-_size,_price,_close)
            _size    :=  _position
            _new := false
    _size  := nz(_position)
    _value  = _price   * ( _fullqty  ? _size : _size  * _leverage ) 
	_fee    = math.abs   ( _value )  /  100* _commission   
	(_price * _size    * ( _close    / _price - 1 ) ) - _fee

// @function Position Net Profit, automatic on/off if position != 0
// @param    _position	  (float)  position size (total or margin size)
// @param    _commission  (float)  % where (0.1 = 0.1%)
// @param    _leverage	  (float)  optional if leveraged, default 1x
// @param    _fullqty     (bool)   if position entered is tottal trade size, default is margin qty (1/lev)
// @returns  percentage profit (1% = 1)
export percent(float _position, float _close, float _commission, float _leverage = 1, bool _fullqty = false) =>
    amount    (_position, _close, _commission, _leverage , _fullqty ) / (math.abs(_position) * _close)
