'PineScript - Quantity for the Last Order

I want to know the quantity of the last closed contract, and if it is negative, the quantity will doubled in the new entry, and if it is positive, it will be the same specified quantity

I tried to do it using strategy.closedtrades.size(strategy.closedtrades) But orders do not appear on chart ?

//@version=5
strategy("My Strategy1", overlay=true, margin_long=100, margin_short=100)
q= 0.1

trade_profit = strategy.closedtrades.profit(strategy.closedtrades)
last_trade_size = strategy.closedtrades.size(strategy.closedtrades)


longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long,qty=trade_profit > 0? q : last_trade_size*2)

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short,qty=trade_profit > 0? q : last_trade_size*2)


Solution 1:[1]

While strategy.closedtrades.size and strategy.closedtrades.profit are zero based, strategy.closedtrades returned the total number of trades (not zero based).

Therefor you will need to write:

trade_profit = strategy.closedtrades.profit(strategy.closedtrades - 1)
last_trade_size = strategy.closedtrades.size(strategy.closedtrades - 1)

The other issue is that if the last closed trade is short, than last_trade_size*2 will be a negative number which is not allowed in qty parameter. It's best if you'll use math.abs(last_trade_size*2) for this.

Here is the full code after the changes (I made a small change also to check if there were any closed trades):

//@version=5
strategy("My Strategy1", overlay=true, margin_long=100, margin_short=100)

q = 1.0

trade_profit = strategy.closedtrades.profit(strategy.closedtrades-1)
last_trade_size = strategy.closedtrades.size(strategy.closedtrades-1)


if strategy.closedtrades > 0 and trade_profit > 0
    q := math.abs(last_trade_size * 2)


longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long, qty=q)
    

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short, qty=q)
   

Here is a list of example trades:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s