def sellTheUnrealized(self): if self.getTheBull().isUnRealized(): self.sellTheBull() if shouldUsePrint(): print("Roundtrip Completed. Bull was sold. {0}".format( self.printProfitAndLosses())) else: self.sellTheBear() if shouldUsePrint(): print("Roundtrip Completed. Bear was sold. {0}".format( self.printProfitAndLosses()))
def isPastMaximumHoldTime(self): if shouldUsePrint(): print("Maximum Hold time: {} Time Since Purchase: {} ".format( self.robot.getMaxHoldTimeInMinutes(), self.getTimeSincePurchase())) return self.getTimeSincePurchase( ) > self.robot.getMaxHoldTimeInMinutes()
def getTodayMaxTransactionsSize(self): all_results = [c for c in self.completed_list if c.completedToday()] if shouldUsePrint(): print( "CompletedRoundTrips: getTodayMaxTransactionsSize: {}".format( len(all_results))) return len(all_results)
def setUpTestData(self): if shouldUsePrint(): print("Setting up {0}".format(self.testname)) self.buy_order_ids=TradeDataHolder.generateBuyOrderClientIDs(project_root='project_name', bull_symbol=self.bull_symbol,bear_symbol=self.bear_symbol) self.sell_order_ids=TradeDataHolder.generateSellOrderClientIDs(project_root='project_name', bull_symbol=self.bull_symbol,bear_symbol=self.bear_symbol)
def processTradeData(self, start_date=None, end_date=None, pairs=None): if not self.isValid(): return False if shouldUsePrint(): print(self.config) default_start_date = datetime.datetime( 2020, 10, 1, tzinfo=timezone.utc).isoformat() default_end_date = default_start_date default_pairs = self.config[self.entries_key] self.start_date = start_date if not (start_date == None) else default_start_date self.end_date = end_date if not (end_date == None) else default_end_date self.pairs = pairs if not (pairs == None) else default_pairs alpaca = AlpacaMarketClock() trading_dates = alpaca.getTradingCalendar(start_date=self.start_date, end_date=end_date) entries = [] for pair in self.pairs: displayOutput(str="Pair={}".format(pair)) #for day in trading_dates: config_dict = dict() entry = [{ 'bull': pair['bull'], 'bear': pair['bear'], 'etf': pair['etf'], 'start_date': day['start_date'], 'end_date': day['start_date'] } for day in trading_dates] config_dict['entries'] = entry entries.append(config_dict.copy()) self.config = entries return entries
def setUpTestData(self): if shouldUsePrint(): print("Setting up {0}".format(self.testname)) index = 0 self.bullish = dict() self.bearish = dict() for x in self.current_times: self.bullish['symbol']=self.bull_symbol self.bullish['price']=self.bull_prices[index] self.bullish['qty']=10 self.bullish['date']=self.current_times[index] self.bearish['symbol']=self.bear_symbol self.bearish['price']=self.bear_prices[index] self.bearish['qty']=170 self.bearish['date']=self.current_times[index] order_ids = TradeDataHolder.generateBuyOrderClientIDs(bear_symbol=self.bear_symbol,bull_symbol=self.bull_symbol, project_root='HelloWorld') self.bullish['bull_buy_order_client_id']= order_ids['bull_buy_order_client_id'] self.bearish['bear_buy_order_client_id']= order_ids['bear_buy_order_client_id'] TradeDataHolder.recordAcquisitionTransaction(robot=None,bullish=self.bullish,bearish=self.bearish) index = index+1
def isInRegression(self): regression_start = self.robot.getRegressionStartDayInMinutes() max_hold_time = self.robot.getMaxHoldTimeInMinutes() if shouldUsePrint(): print("Regression Start:{}".format(regression_start)) return regression_start < self.getTimeSincePurchase() < max_hold_time
def downloadAndStore(self, target=None, update=False): if not self.isValid(): return False if shouldUsePrint(): print(self.config) #Store the downloaded files from the location of the if self.data_folder_root_key in os.environ: temp_data_folder = os.environ[self.data_folder_root_key] else: temp_data_folder = self.config_file_folder + 'data' #Add trailing '/', if none exist data_root_folder = temp_data_folder if temp_data_folder.endswith( '/') else temp_data_folder + '/' # Check if the folder exists. If not, then create one ... if not os.path.exists(data_root_folder): os.mkdir(data_root_folder) #Set the default values first. Make sure to calculate the dates properly start_date_hl = self.config['start_date'] if ( 'start_date' in self.config) else self.default_start_date end_date_hl = self.config['end_date'] if ( 'end_date' in self.config) else self.default_end_date trading_unit_hl = self.config['trading_unit'] if ( 'trading_unit' in self.config) else self.default_trading_unit trading_unit_etf_hl = self.config['trading_unit_etf'] if ( 'trading_unit_etf' in self.config) else self.default_trading_unit_etf resolution_hl = self.config['resolution'] if ( 'resolution' in self.config) else self.default_resolution payload_data = [{ 'bull': x[self.bullish_key], 'bear': x[self.bearish_key], 'etf': x[self.etf_key], 'start_date': x['start_date'] if ('start_date' in x) else start_date_hl, 'end_date': x['end_date'] if ('end_date' in x) else end_date_hl, 'resolution': x['resolution'] if ('resolution' in x) else resolution_hl, 'data_folder_root': data_root_folder, 'force': False, 'trading_unit': x['trading_unit'] if ('trading_unit' in x) else trading_unit_hl, 'trading_unit_etf': x['trading_unit_etf'] if ('trading_unit_etf' in x) else trading_unit_etf_hl } for x in self.config[self.entries_key]] payload = dict() payload['data'] = payload_data for x in payload_data: downloadable = DownloadableETFBullBear(payload=x) if target == 'both': success = downloadable.downloadAndSaveToFile() success = downloadable.downloadAndSaveToDatabase(update=update) if target == None or target == 'file': success = downloadable.downloadAndSaveToFile() elif target == 'database': success = downloadable.downloadAndSaveToDatabase(update=update) return True
def setUpTestData(self): if shouldUsePrint(): print("Setting up {0}".format(self.testname))
def setUpTestData(self): if shouldUsePrint(): print("Setting up {0}".format(self.testname)) TradeDataHolder.recordAcquisitionTransaction(robot=None,bullish=self.bull1,bearish=self.bear1) TradeDataHolder.recordAcquisitionTransaction(robot=None,bullish=self.bull2,bearish=self.bear2) TradeDataHolder.recordAcquisitionTransaction(robot=None,bullish=self.bull3,bearish=self.bear3)
def setUpTestData(self): if shouldUsePrint(): print("Setting up {0}".format(self.testname)) #Build the Robot now = datetime.datetime.now(getTimeZoneInfo()) alpacaBrokerage = BrokerageInformation.objects.create( brokerage_type='Alpaca', name='Alpaca', website='alpaca.markets/') alpacaPortfolio = Portfolio.objects.create( name='Alpaca Portfolio', initial_cash_funds=100000, current_cash_funds=100000, brokerage_id=alpacaBrokerage.id, max_robot_fraction=.10, cash_position_update_policy='immediate', description='Alpaca Portfolio description') strategy = EquityStrategy.objects.create( name='My Best Equity Strategy So Far', description='This is just a test', creation_date=now, modify_date=now, strategy_class='Bullish Bearish Pair', strategy_category='Babadjou', visibility=False, minimum_entries_before_trading=2, trade_only_after_fully_loaded=False, manual_asset_composition_policy=True, automatic_generation_client_order_id=True) self.entry_id = strategy.pk acquisition = AcquisitionPolicy.objects.create( strategy=strategy, acquisition_time_proximity=False, min_time_between_purchases=60, and_or_1='AND', acquisition_volume_proximity=False, min_volume_between_purchases='15M', volume_fraction_to_average=3, and_or_2='AND', acquisition_price_proximity=True, acquisition_price_factor='Bull', bear_acquisition_volatility_factor='.01', number_or_percentage='Stock Price by Number', proximity_calculation_automatic=True, bull_acquisition_volatility_factor='.10', simultaneous_bull_bear_acquisitions=True) self.acq_entry = acquisition.pk disposition = DispositionPolicy.objects.create( strategy=strategy, in_transition_profit_policy=True, in_transition_profit_target_ratio='.15', completion_profit_policy=True, completion_complete_target_ratio='.40', in_transition_asset_composition='2Bull x 1Bear', in_transition_entry_strategy='bestbull_and_worstbear') self.disposition_id = disposition.pk ############################ Robot ############################## nasdaq = RobotEquitySymbols.objects.create(name='Nasdaq', symbol=self.etf, bullishSymbol=self.bullish, bearishSymbol=self.bearish) robot = ETFAndReversePairRobot.objects.create( name=self.base_name, description=self.description, portfolio=alpacaPortfolio, strategy=strategy, symbols=nasdaq, enabled=True, owner=None, visibility=True, version='1.0.0', max_hold_time='14', minimum_hold_time='1', hold_time_includes_holiday=True, sell_remaining_before_buy=False, liquidate_on_next_opportunity=False, internal_name=self.internal_name, max_roundtrips=self.max_roundtrips, cost_basis_per_roundtrip=self.cost_basis_per_roundtrip, profit_target_per_roundtrip=self.profit_basis_per_roundtrip) self.robot_id = robot.pk sentiment = EquityAndMarketSentiment.objects.create( pair_robot=robot, influences_acquisition=True, circuit_breaker=False, sentiment_feed='Automatic') self.sentiment_id = sentiment.pk self.budget_management = RobotBudgetManagement.objects.create( pair_robot=robot, max_budget_per_purchase_number=self.cost_basis_per_roundtrip, use_percentage_or_fixed_value='Number') activities = RobotActivityWindow.objects.create( pair_robot=robot, trade_before_open=True, trade_after_close=False, trade_during_extended_opening_hours=False, offset_after_open='0', offset_before_close='0', blackout_midday_from='10:00am', blackout_midday_time_interval='0')