Henry Tsai

How to implement stoploss?

Programming


Hello team, I am trying to implement a stop loss in my strategy. I’m not quite sure how to do it. Can someone provide more guidance?
 
Jeremy
It supports order level and portfolio level stop loss.
Which one you are talking about? It's better if you can give some codes that you have already tried.

 
admin

There are several ways to do it:

For example, you want to open a market buy order with a stoploss level being 10% from its entry price.



1. Open order with a stop loss condition

Refer to the TechDoc's PlaceOrder section, you can do it as in line #19.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from AlgoAPI import AlgoAPIUtil, AlgoAPI_Backtest
from datetime import datetime, timedelta

class AlgoEvent:
    def __init__(self):
        pass

    def start(self, mEvt):
        self.evt = AlgoAPI_Backtest.AlgoEvtHandler(self, mEvt)
        self.evt.start()

    def on_marketdatafeed(self, md, ab):
        order = AlgoAPIUtil.OrderObject(
            instrument = md.instrument,
            openclose = 'open', 
            buysell = 1,    #1=buy, -1=sell
            ordertype = 0,  #0=market, 1=limit
            volume = 0.01,
            stopLossLevel=md.askPrice*0.9
        )
        self.evt.sendOrder(order)



2. Update order condition

Alternatively, you can use the UpdateOpenedOrder function to update the stoploss level after an order has been successfully opened. Just in line #26 and #28.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from AlgoAPI import AlgoAPIUtil, AlgoAPI_Backtest
from datetime import datetime, timedelta

class AlgoEvent:
    def __init__(self):
        pass

    def start(self, mEvt):
        self.evt = AlgoAPI_Backtest.AlgoEvtHandler(self, mEvt)
        self.evt.start()

    def on_marketdatafeed(self, md, ab):
        order = AlgoAPIUtil.OrderObject(
            instrument = md.instrument,
            openclose = 'open', 
            buysell = 1,    #1=buy, -1=sell
            ordertype = 0,  #0=market, 1=limit
            volume = 0.01
        )
        self.evt.sendOrder(order)

    def on_orderfeed(self, of): 
        if of.status=="success":
            # update take profit level
            if of.buysell==1:
                sl = of.fill_price*0.9
            else:
                sl = of.fill_price*1.1
            res = self.evt.update_opened_order(tradeID=of.tradeID, sl=sl)

            # print to console
            self.evt.consoleLog(res["status"], res["msg"])