Averaging down on unrealized loss

Coding newbie here! I am trying to code the following strategy and have not been successful yet. Will appreciate some help





Here is the logic I am trying to code (in python)





 - 10 stocks universe [AAPL, AMZN, MSFT, GOOGL, JPM, V, MA, NVDA, ROKU, BAC]

 - Algo runs every minute

 - Max positions in portfolio at any time  = 5 stocks



Buy 10 shares when the following conditions are met

  - RSI (14 days) > 60

  - ADX ( 14 days) > 25

   - CCI (14 days) > 90

   - Last price > SMA (5 days)

   - MACD (6, 13) > 0



 - For any of the 5 positions in portfolio, if unrealized loss of >5%, then place a limit but order for an extra one share at 0.95% of my average purchase price (average down)

  • For any of the 5 positions in portfolio, if unrealized profit is > 2%, then place limit sell order for 5% profit.

     - Wait at least 2 days before rebuying a closed position

The entry part of your strategy (the entry signals and combining them) is rather straightforward. You can use the data.history and the built-in indicators library (see the bollinger band template) to compute and define your signal_fn, (you can also use ta-lib directly if you prefer). For the exit part of your strategy, you need to query the context variable for the positions like below:

def compute_pnls(context):
    for asset in context.portfolio.positions:
        pos = context.portfolio.positions[asset]
        pnl = pos.amount*(pos.last_sale_price - pos.cost_basis)
        pct_pnl = pos.last_sale_price/pos.cost_basis - 1

You can insert the  function above inside handle_data (before anything else) to check for exit condition. Also set a variable to track if you want to wait for n-days to exit. At the before_trading_starts - which is fired everyday once, you can check for this variable and reset it back when n-days are over.



Note: the attributes above for pnls are different in live trading, replace amount by quantity, and last_sale_price by last_price. Or you can directly query unrealized_pnl for the current (unrealized) profit or loss. If you need more help, please send a mail to blueshift-support@quantinsti.com with your current effort.