Mariner Backtesting - TrailBy

Trailing Stop Orders

TrailBy() (Class)

Creates the instance.

 TrailBy( IsBelow, InitialStopPrice, TrailingBy, Increment, Shares, ReferencePrice, ActiveBeginTime, ActiveEndTime )

Parameters:

Name Type Default Information
IsBelow   required  
InitialStopPrice   required  
TrailingBy   required  
Increment   required  
Shares   required  
ReferencePrice   required  
ActiveBeginTime   required  
ActiveEndTime   required  

Attributes:

Name Type Default Information
IsBelow   IsBelow  
StopPrice   InitialStopPrice  
TrailingBy   TrailingBy  
Increment   Increment  
Shares   Shares  
ReferencePrice   ReferencePrice  
BestInTrade   ReferencePrice  
WorstInTrade   ReferencePrice  
ActiveBeginTime   ActiveBeginTime int milliseconds after midnight
ActiveEndTime   ActiveEndTime int milliseconds after midnight
IsActiveTime   False  
Distance   0.0  
DistanceHistogram   1.0  
Exposure   0.0  
Phase   "Initial"  

UpdateStopPrice() (Method)

Call to update the instance variables. Call method for checking instance variables.

 UpdateStopPrice( ReferencePrice, MarketTime)

Parameters:

Name Type Default Information
ReferencePrice float required  
MarketTime MUTS required current system time

SetTrailBy() (Method)

Call to update the instance variables. Call method for checking instance variables.

 SetTrailBy( NewTrailBy, ReferencePrice, MarketTime )

Parameters:

Name Type Default Information
NewTrailBy float required new trail by amount
ReferencePrice float required reference price for calculation
MarketTime MUTS required current system time

SetStopPrice() (Method)

Call to update the instance variables. Call method for checking instance variables.

 SetStopPrice( NewTrailBy, ReferencePrice, MarketTime )

Parameters:

Name Type Default Information
NewTrailBy float required new trail by amount
ReferencePrice float required reference price for calculation
MarketTime MUTS required current system time
Working Example:
from cloudquant.interfaces import Strategy
import ktgfunc


class TrailByExample(Strategy):
    @classmethod
    def is_symbol_qualified(cls, symbol, md, service, account):
        return symbol == "AAL"

    def on_start(self, md, order, service, account):
        # print symbol and timestamp
        print(self.symbol + "\n" + service.time_to_string(service.system_time) + "\tin on start")

        # create variables for the market open and close timestamps
        self.market_open_time = md.market_open_time
        self.market_close_time = md.market_close_time

        # Initialize a TrailBy object for a trailing stop
        # The shares, active begin price reference price, and initial stop price will be set once a position is entered
        self.trail = ktgfunc.TrailBy(IsBelow=True, InitialStopPrice=0, TrailingBy=0.1, Increment=0.01, Shares=0,
                                     ReferencePrice=0, ActiveBeginTime=self.market_open_time,
                                     ActiveEndTime=self.market_close_time)

        # buy order
        order.algo_buy(self.symbol, "market", intent="init", order_quantity=100)
        print service.time_to_string(service.system_time)[11:19], self.symbol , 'Long 100'


        self.begin_trail = False

        # create a variable to run code once
        self.once =True

        # create a variable to track current position
        self.in_position = False

    def on_minute_bar(self, event, md, order, service, account, bar):

        if account[self.symbol].position.inventory != []:
            self.begin_trail = True

        if self.begin_trail and self.once:

            # set boolean to false to avoid re-running code
            self.once = False

            # To adjust attributes after they have been created, you can manually call them
            # Is Below is True for Long orders and False for Shorts
            # set TrailingBy and Increment to choose how the stop is adjusted
            # use event.price - 0.1 to set the stop 10 cents below entry price
            # use account[self.symbol].position.inventory[0].execution[2] for the time the stock was bought

            self.trail.StopPrice = account[self.symbol].position.entry_price - 0.1
            self.trail.Shares = account[self.symbol].position.capital_long
            self.trail.ReferencePrice = md.L1.last
            self.trail.ActiveBeginTime = account[self.symbol].position.inventory[0].execution[2]
            self.in_position = True

            # print information about the stop
            print("\nA stop has been created with a starting price of " + str(self.trail.StopPrice))
            print"The stop will trail by " + str(self.trail.TrailingBy) + " with an increment of " + str(
                self.trail.Increment), '\n'


        if self.begin_trail:
            # updates the stop price
            current_bar = bar.minute()
            self.trail.UpdateStopPrice(current_bar.high, current_bar.timestamp)
            print 'Updating StopPrice:', self.trail.StopPrice[0]

        # check if in position; sell if the last trade is equal or greater than the stop price
        if self.in_position and self.trail.StopPrice >= current_bar.high:
            # sell order
            order.algo_sell(self.symbol, "market", intent="exit")

            print("\n\nYour stop price of " + str(
                self.trail.StopPrice[0]) + " has been reached. An order to sell has been sent.")

            # set the variable to false to avoid multiple sell orders
            self.in_position = False

            service.terminate()

Console

AAL
2016-08-09 09:30:00.000000  in on start
100 shares of AAL purchased.

2016-08-09 09:31:00.447000
A stop has been created with a starting price of 35.1799987793
The stop will trail by 0.1 with an increment of 0.01

09:31:00    Updating StopPrice: 35.3900016785
09:32:00    Updating StopPrice: 35.3900016785
09:33:00    Updating StopPrice: 35.3900016785
09:34:01    Updating StopPrice: 35.3900016785
09:35:00    Updating StopPrice: 35.3900016785
09:36:02    Updating StopPrice: 35.3900016785
09:37:00    Updating StopPrice: 35.4
09:38:00    Updating StopPrice: 35.4


Your stop price of 35.4 has been reached. An order to sell has been sent.