Back to Community
I am a Newbie & help needed: How to code a buy and take profit trading algoritm using MA

Good Day everyone

I am a newbie in coding, appreciate some kind help on coding. E.g. I like to buy when current price near moving average between 10MA to 20MA and start taking profit when current price is above 1MA. I dont know whether is it possible to code "a take profit strategy" e.g. ride the momentum and take profit only if current price starting to dip from the previous high e.g. price is way above above 1MA and take profit only if it weaken to below 4MA etc. My code now just take profit when price is above 1MA and if current price dont hit 1 MA, it wont protect the profit and when price dip, it will only cut loss at below 20MA.

I would also like to keep my loss tight. Is it possible to code a cut loss strategy? My coding is very elementary and i can only code a simple cut loss when current price is below 20MA. But bec my buy price can varies between 10MA and 20MA range so i would like to keep a tight cut loss. My loss can be very big is i bought at 10MA and only cut at 20MA. Is it possible to set various cut loss point for shares bot at 10MA, 11MA, 12MA etc? E.g. if current price drop below 1% below the price bot at 10 MA? Or is there any cut loss algo sample i may use?

Last but not least, I would like to check whether is there any code to positioning? Currently based on the logic below, I can only buy all shares on only 1 stock at one go using all my cash. Is it possible to buy from 3 different stocks and proportion the cash equally to each stocks? E.g. I have $100,000 cash, can it be quoted so that i allocate $20k to each stock and reserve $40k in cash for contingency.

Thank you so much for you help and advice.

Here is my coding on buying using MA and appreciate some kind help to improve it.

def initialize(context): = symbol('APPL')

def handle_data(context, data):

average_price_1 = data[].mavg(1)
average_price_14 = data[].mavg(15)
average_price_20 = data[].mavg(20)

current_price = data[].price

cash =

if current_price > average_price_MA20 and current_price < average_price_MA14 and cash > current_price:

    # Need to calculate how many shares we can buy  
    number_of_shares = int(cash/current_price)  
    # Place the buy order (positive means buy, negative means sell)  
    order(, +number_of_shares)"Buying %s" % (

else current_price < average_price_20 or current_price > average_price_MA1:

    # Cut loss and Sell all of our shares by setting the target position to zero or take profit when price above MA = 1  
    order_target(, 0)"Selling %s" % (  
2 responses