A buy and hold strategy is when you want to open a trade at a specific point in time and hold it through time to exit it at another point of time.
In the example below let's buy and hold an instrument RELIANCE from Jan 1st, 2018 through May 31, 2021.
The setup strategy function in this case can actually be empty, but since we'd like to capture the length of the time period, let's capture that in self.length
In process candle, let's initialize the counter variable to keep track of the datapoints. When counter is 0 (first data point), you enter the trade with self.buy. When counter is at the end of the dataframe, you exit the trade with self.close. Alternatively, self.sell can be used to close the long position as well.
def process_candle(self):
counter = self.current_iloc
print('close', self.current['close'])
if counter == 0:
self.buy(info="Enter Buy and Hold", quantity=1)
if counter == self.length - 1:
self.close(info="Exit Buy and Hold", quantity=1)
Let's now take a look at the entire code.
from Orca import *
class Custom_Strategy(BaseIntradayStrategy):
def setup_strategy(self):
print("Current DF is:\n", self.primary_df.head(10))
self.length = len(self.primary_df)
def process_candle(self):
counter = self.current_iloc
print('close', self.current['close'])
if counter == 1:
self.buy(info="Enter Buy and Hold", quantity=1)
if counter == self.length - 1:
self.close(info="Exit Buy and Hold", quantity=1)
user_input_dict = {
#'instrument_list': get_nifty100(), # Instrument Name
'instrument_list' : ['RELIANCE'],
'table_name': 'india_eod',
'start_date': "01-01-2018",
'end_date': "01-31-2021",
'interval': '1D', # Time Interval - Day Level data
'initial_capital': 10000,
'market_hours': 1,
'data_input_type': 'db',
'user_file_name': 'buy_and_hold_strategy',
'root_file_path': os.path.splitext(__file__)[0], # Current File Path
'path_type': 'AWS'
}
def main():
if __name__ == '__main__':
run_object = user_input_invoke_run(
user_input_dict=user_input_dict, strategy_name=Custom_Strategy)
run_object.invoke_run()
main()