def justStartedAppDirectionCheck(self): log.debug( "justStartedAppDirectionCheck: Application just restarted. Going through our checks" ) # do we need to reverse positions? # first check to see if we have positions or open orders. If not exit otherwise continue # Are we positioned in the wrong direction (i.e. long when we should be short?) If so, we need to close STP and open open trades. # not going to take a position at this time. # the bars data is the current, not completed, bar so we have to go back to get closed bars. # # checking for wrong direction contContract, contracthours = get_contract( self) #basic information on continuious contact tradeContract = self.ib.qualifyContracts(contContract)[ 0] # gives all the details of a contract so we can trade it open_long, open_short, long_position_qty, short_position_qty, account_qty = orders.countOpenPositions( self.ib, "") # do we have an open position - not orders but positions? open_today, tradingDayRules, currentTimeFrame = helpers.is_open_today( contracthours) wait_time, self.datetime_15, self.datetime_1h, self.datetime_1d, self.log_time = self.define_times( self.ib) dataContract = Contract(exchange=config.EXCHANGE, secType="FUT", localSymbol=contContract.localSymbol) bars_15m = calculations.Calculations(self.ib, dataContract, "2 D", "15 mins", self.datetime_15, False, 0) # bars_1h = calculations.Calculations(self.ib, dataContract, "5 D", "1 hour", self.datetime_1h, True, bars_15m.closePrice) bars_1d = calculations.Calculations(self.ib, dataContract, "75 D", "1 day", self.datetime_1d, False, 0) updated = self.update_tk(bars_15m, bars_1h, bars_1d) # #rint("bars15 cci_third, ccia_third, cci_prior, ccia_prior, cci, ccia",bars_15m.cci_third,bars_15m.ccia_third,bars_15m.cci_prior, bars_15m.ccia_prior, bars_15m.cci, bars_15m.ccia) if bars_15m.cci_prior > bars_15m.ccia_prior and open_short and abs( bars_15m.cci - bars_15m.ccia) > config.SPREAD: log.info( "justStartedAppDirectionCheck: we are in app start up and we need to reverse due to wrong direction" ) allClosed = orders.closeOutMain( self.ib, tradeContract, True ) # we don't worry about whether we are long or short. just passing the contract, need to add order. Second false is whether this is an opening order. it is not log.info( "justStartedAppDirectionCheck: crossed but not tradeNow so lets close stp and open positions" ) elif bars_15m.cci_prior > bars_15m.ccia_prior and open_short and abs( bars_15m.cci - bars_15m.ccia) <= config.SPREAD: return True, False, 1 log.info( "justStartedAppDirectionCheck: we are in app start up and we crossed but not exceed the spread - going pending" ) elif bars_15m.cci_prior < bars_15m.ccia_prior and open_long and abs( bars_15m.cci - bars_15m.ccia) > config.SPREAD: log.info( "justStartedAppDirectionCheck: we are in app start up and we need to reverse due to wrong direction. Came in long and crossed down > spread" ) allClosed = orders.closeOutMain( self.ib, tradeContract, True ) # we don't worry about whether we are long or short. just passing the contract, need to add order. Second false is whether this is an opening order. it is not log.info( "justStartedAppDirectionCheck: crossed but not tradeNow so lets close stp and open positions" ) elif bars_15m.cci_prior < bars_15m.ccia_prior and open_long and abs( bars_15m.cci - bars_15m.ccia) <= config.SPREAD: return False, True, 1 log.info( "justStartedAppDirectionCheck: we are in app start up and we crossed but not exceed the spread - going pending" ) else: log.info( "justStartedAppDirectionCheck: we are in app start up and we DO NOT need to reverse due to wrong direction - checking pending" ) log.info( "justStartedAppPendingCheck:: bars_15m.prior {ccip} {cciap}, third {ccip3} {cciap3} open long and short {ol} {os}" .format(ccip=bars_15m.cci_prior, cciap=bars_15m.ccia_prior, ccip3=bars_15m.cci_third, cciap3=bars_15m.ccia_third, ol=open_long, os=open_short)) if bars_15m.cci_prior > bars_15m.ccia_prior and abs(bars_15m.cci_prior - bars_15m.ccia_prior) <= config.SPREAD and \ bars_15m.cci_third < bars_15m.ccia_third and abs(bars_15m.cci_third - bars_15m.ccia_third) > config.SPREAD and \ not open_long and not open_short: return True, False, 1 elif bars_15m.cci_prior < bars_15m.ccia_prior and abs(bars_15m.cci_prior - bars_15m.ccia_prior) <= config.SPREAD and \ bars_15m.cci_third > bars_15m.ccia_third and abs(bars_15m.cci_third - bars_15m.ccia_third) > config.SPREAD and \ not open_long and not open_short: return False, True, 1 else: log.info("not going into this session pending") return False, False, 0
def run(self): """ Execute the algorithm """ # check for command line arguments # key_arr = ['blank','ATR15','ATR1','ATRD','CCI15','CCIA15','CCIA1h','CCIA1d','BBW15','BBb15','BBW1h','BBb1h','BBW1d','BBb1d'] #log.info("Account values: {av}".format(av=self.ib.accountValues())) tradeNow, not_finished, pendingShort, pendingLong, pendingSkip, cci_trade, ccibb_trade, crossed, justStartedApp = False, True, False, False, False, False, False, False, True pendingCnt = 0 # any variable that is used within the class will be defined with self if justStartedApp: pendingLong, pendingShort, pendingCnt = self.justStartedAppDirectionCheck( ) #if not pendingLong and not pendingShort: # pendingLong, pendingShort, pendingCnt = self.justStartedAppPendingCheck() justStartedApp = False # do we need to reset pending reviewIBTrades = orders.getListOfTrades(self.ib) while not_finished: log.info( "top of algo run self*************************************************" ) #top of logic - want to check status as we enter a new bar/hour/day/contract contContract, contracthours = get_contract( self) #basic information on continuious contact tradeContract = self.ib.qualifyContracts(contContract)[ 0] # gives all the details of a contract so we can trade it open_long, open_short, long_position_qty, short_position_qty, account_qty = orders.countOpenPositions( self.ib, "") # do we have an open position? self.app.shares.update(long_position_qty + short_position_qty) dataContract = Contract(exchange=config.EXCHANGE, secType="FUT", localSymbol=contContract.localSymbol) log.debug("Got Contract:{dc} local symbol {ls}".format( dc=dataContract, ls=dataContract.localSymbol)) self.app.contract.update(dataContract.localSymbol) wait_time, self.datetime_15, self.datetime_1h, self.datetime_1d, self.log_time = self.define_times( self.ib) log.info( "next datetime for 15 minutes - should be 15 minutes ahead of desired nextqtr{wt} and current time {ct}" .format(wt=wait_time, ct=datetime.today())) # need to determine if this is normal trading hours or not dayNightProfileCCI, dayNightProfileCCIBB = self.duringOrAfterHours( self.ib, contracthours) # # debug #current_time = datetime.now() #wait_time = wait_time = current_time.replace(minute = 1,second=0) # #self.ib.disconnect() self.ib.waitUntil(wait_time) #self.ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) #log.debug("before loop start:{ls}".format(ls=datetime.now())) #self.ib.loopUntil(condition=self.ib.isConnected()) # rying to fix 1100 error on nightly reset # # first attempt at fix #try: # logger.getLogger().info("Connecting...") # self.ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) # self.ib.reqMarketDataType(config.DATATYPE.value) #except NameError: # got this block from https://groups.io/g/insync/message/4045 # self.num_disconnects += 1 # print(datetime.now(), 'Connection error exception', self.num_disconnects) # self.ib.cancelHistoricalData(bars) # log.info('Sleeping for 10sec...') # self.ib.disconnect # self.ib.sleep(10) # self.ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) # if not self.backTest: stpSell, stpBuy = orders.countOpenOrders( self.ib) # don't want to execute covering log.info( "we have the follow number of open stp orders for Sell: {sell} and Buy: {buy} " .format(sell=stpSell, buy=stpBuy)) #if datetime.now().hour == 0: # log.info("0 hour and disconnecting".format(datetime.now(),datetime.now().hour)) # self.ib.disconnect() # self.ib.sleep(500) # self.ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID) # log.info("0 hour and re-connecting".format(datetime.now(),datetime.now().hour)) #log.debug("after loop start:{ls}".format(ls=datetime.now())) #log.debug("requesting info for the following timeframe today: {} ".format(wait_time)) bars_15m = calculations.Calculations(self.ib, dataContract, "2 D", "15 mins", self.datetime_15, False, 0) #rint("bars15m ",bars_15m) if bars_15m.atr < config.ATR_STOP_MIN: bars_1h = calculations.Calculations(self.ib, dataContract, "5 D", "1 hour", self.datetime_1h, True, bars_15m.closePrice) modBuyStopLossPrice = bars_1h.buyStopLossPrice modSellStopLossPrice = bars_1h.sellStopLossPrice modTrailStopLoss = (bars_1h.sellStopLossPrice - bars_1h.buyStopLossPrice) / 2 else: bars_1h = calculations.Calculations(self.ib, dataContract, "5 D", "1 hour", self.datetime_1h, False, 0) modBuyStopLossPrice = bars_15m.buyStopLossPrice modSellStopLossPrice = bars_15m.sellStopLossPrice modTrailStopLoss = (bars_1h.sellStopLossPrice - bars_1h.buyStopLossPrice) / 2 bars_1d = calculations.Calculations(self.ib, dataContract, "75 D", "1 day", self.datetime_1d, False, 0) updated = self.update_tk(bars_15m, bars_1h, bars_1d) pendingLong, pendingShort, pendingCnt, pendingSkip, tradeNow, tradeAction, crossed = self.crossoverPending( bars_15m, pendingLong, pendingShort, pendingSkip, pendingCnt) cci_key, ccibb_key, summ_key = build_key_array( tradeAction, bars_15m, bars_1h, bars_1d) #setsum = self.setupsummary(summ_key) log.debug("tradeNow: {trade} pendingSkip {skip}".format( trade=tradeNow, skip=pendingSkip)) log.debug( "going into tradenow: {tn}, backtest: {bt}, open long: {ol} and short: {os}" .format(tn=tradeNow, bt=self.backTest, ol=open_long, os=open_long)) #handeling existing position if crossed and (open_long or open_short) and not ( pendingLong or pendingShort): # need to close stp and open positions log.info( "crossed and not pending so lets close stp and open positions. Open Long: {ol} open short: {os} pending long: {pl} pending short: {ps}" .format(ol=open_long, os=open_short, pl=pendingLong, ps=pendingShort)) allClosed = orders.closeOutMain( self.ib, tradeContract, False) # we don't worry about whether we are long or short elif (not (pendingLong or pendingShort)) and open_long and tradeAction == "Sell": log.info( "Not pending we are open_long and tradeaction is sell so lets close out stp and open positions Open Long: {ol} open short: {os} pending long: {pl} pending short: {ps}" .format(ol=open_long, os=open_short, pl=pendingLong, ps=pendingShort)) allClosed = orders.closeOutMain( self.ib, tradeContract, False) # we don't worry about whether we are long or short elif (not (pendingLong or pendingShort)) and open_short and tradeAction == "Buy": log.info( "Not pending we are open_short and tradeaction is buy so lets close out stp and open positions Open Long: {ol} open short: {os} pending long: {pl} pending short: {ps}" .format(ol=open_long, os=open_short, pl=pendingLong, ps=pendingShort)) allClosed = orders.closeOutMain( self.ib, tradeContract, False) # we don't worry about whether we are long or short if tradeNow: log.info("tradeNow - Tradeing this bar {cci} - {ccibb}".format( cci=cci_key, ccibb=ccibb_key)) csv_file1 = csv.reader(open('data/ccibb.csv', "rt"), delimiter=",") #cci_key, ccibb_key = build_key_array(self, tradeAction, bars_15m, bars_1h, bars_1d) for row1 in csv_file1: if ccibb_key == row1[0] and row1[ 13] == "Y": #13 is winrisk - whether we trade or not #log.info("we have a match in ccibb.csv") log.info( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" ) log.info( " +++++++++++++++++++++++++++++++++++++++++++++++++ found a match in CCIBB " .format(str(row1[0]))) log.info( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" ) ccibb_trade = True quantity = 1 # do we need to close out current order # do we need to close out current stop loss orders? if not self.backTest: fillStatus = orders.createOrdersMain( self.ib, tradeContract, tradeAction, quantity, dayNightProfileCCI, modBuyStopLossPrice, modSellStopLossPrice, False, modTrailStopLoss, bars_15m.closePrice) log.info( "logic.CCIbb: order placed, fillStatus: {fs}". format(fs=fillStatus)) open_long, open_short, tradenow = False, False, False status_done = self.row_results(row1, cci_trade, ccibb_trade) break elif ccibb_key == row1[0] and row1[13] == "N": log.info( "Entry found in CCIBB but not traded. See if this changes" ) self.app.status1.update( "Entry found in CCIBB but not traded.") log.info("Profit : {p}".format(p=row1[6])) log.info("Orders : {p}".format(p=row1[7])) log.info("Wins $ : {p}".format(p=row1[10])) log.info("Losses $: {p}".format(p=row1[11])) log.info("Wins # : {p}".format(p=row1[8])) log.info("Losses #: {p}".format(p=row1[9])) ccibb_trade = False csv_file2 = csv.reader(open('data/cci.csv', "rt"), delimiter=",") for row2 in csv_file2: #rint("cci row: ",row2[0],row2[13]) if cci_key == row2[0] and row2[13] == "Y": log.info( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" ) log.info( "+++++++++++++++++++++++++++++++++++++++++++++++++ we have a match in cci.csv - tradeAction" .format(tradeAction)) log.info( "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" ) cci_trade = True quantity = 1 if not self.backTest: fillStatus = orders.createOrdersMain( self.ib, tradeContract, tradeAction, quantity, dayNightProfileCCIBB, modBuyStopLossPrice, modSellStopLossPrice, False, modTrailStopLoss, bars_15m.closePrice) open_long, open_short, tradenow = False, False, False status_done = self.row_results(row2, cci_trade, ccibb_trade) break elif cci_key == row2[0] and row2[13] == "N": log.info( "Entry found in CCI but not traded. See if this changes" ) self.app.status1.update( "Entry found in CCI but not traded.") log.info("Profit : {p}".format(p=row2[6])) log.info("Orders : {p}".format(p=row2[7])) log.info("Wins $ : {p}".format(p=row2[10])) log.info("Losses $: {p}".format(p=row2[11])) log.info("Wins # : {p}".format(p=row2[8])) log.info("Losses #: {p}".format(p=row2[9])) cci_trade = True if tradeNow: log.info( "we did not find a match in CCI: {cci} or CCI BB: {ccib}" .format(cci=cci_trade, ccib=ccibb_trade)) #csv_row_add = helpers.build_csv_bars_row(","+(''.join(key_arr))+","+(''.join(key_arr[0:8]))+","+str(cci_trade)+","+str(ccibb_trade)+","+str(pendingLong)+","+str(pendingShort),True) wrote_bar_to_csv = helpers.build_csv_bars_row( self.log_time, tradeAction, bars_15m, bars_1h, bars_1d, pendingLong, pendingShort, pendingCnt, tradeNow, ccibb_trade, cci_trade, ccibb_key, cci_key) tradenow, cci_trade, ccibb_trade = False, False, False changed = orders.modifySTPOrder(self.ib, modBuyStopLossPrice, modSellStopLossPrice, bars_15m.closePrice)
from flask import Flask, request, jsonify import calculations token = '<INSERT TOKEN HERE>' app = Flask(__name__) calc = calculations.Calculations(token) @app.route('/') def home_page(): return 'Please navigate to /reporting to return a report. The required query parameters are business_id, report, timeInterval, start, and end.' @app.route('/reporting') def report_page(): report = request.args.get('report') text = 'The required query parameters are business_id, report, timeInterval, start, and end.' # User incorrectly inputs the report type if report not in ['LCP', 'FCP', 'EGS']: return text + 'Report can only be LCP, FCP, or EGS. Please try again with a correct report name.' else: business_id = request.args.get('business_id') timeInterval = request.args.get('timeInterval') start = request.args.get('start') end = request.args.get('end') if report == "LCP": output = calc.LCP(business_id, report, timeInterval, start, end) elif report == "FCP": output = calc.FCP(business_id, report, timeInterval, start, end) else:
modify it under the terms of the GNU General Public License version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' import calculations as calculations_base import database as database_base # open up the database db_connection = database_base.ServerDatabase() db_connection.db_open() calc_inst = calculations_base.Calculations(db_connection) db_connection.db_wealth_poe_ninja_currency_write( calc_inst.com_wealth_ninja_fetch_api()) # commit db_connection.db_commit() # close the database db_connection.db_close()
def perform_calculations(): """Performs calculations based on user input""" user_input_type = input( "What calculation would you like to perform (type 'list calcs' to list calculations, or 'quit'): " ) calculator = calculations.Calculations() user_team, user_match = 0, 0 input_choice = [ "quit", "most balls", "least balls", "match info", "total balls", "average balls", "matches played", "team info", "list teams", "list matches" ] if user_input_type in input_choice: if user_input_type not in [ "quit", "list calculations", "list teams", "list matches" ]: user_team = input_data.repeat_input("Enter the team number: ") if user_input_type == "match info": user_match = input_data.repeat_input("Enter a match number: ") input_choice = { "list calcs": { "function_name": print, "parameters": [calculator.get_calculations()], }, "quit": { "function_name": take_input, "parameters": None }, "default": { "function_name": perform_calculations, "parameters": None }, "most balls": { "function_name": print, "parameters": [calculator.most_balls(user_team)], }, "least balls": { "function_name": print, "parameters": [calculator.least_balls(user_team)], }, "match info": { "function_name": print, "parameters": [calculator.match_info(user_team, user_match)], }, "total balls": { "function_name": print, "parameters": [calculator.total_balls(user_team)], }, "average balls": { "function_name": print, "parameters": [calculator.average_balls(user_team)], }, "matches played": { "function_name": print, "parameters": [calculator.num_matches(user_team)], }, "team info": { "function_name": print, "parameters": [calculator.team_info(user_team)] }, "list teams": { "function_name": print, "parameters": [calculator.list_teams()] }, "list matches": { "function_name": print, "parameters": [calculator.list_matches()] } } switch_case(input_choice, user_input_type) perform_calculations()
def justStartedAppDirectionCheck(self): log.debug( "justStartedAppDirectionCheck: Application just restarted. Going through our checks" ) # do we need to reverse positions? # first check to see if we have positions or open orders. If not exit otherwise continue # Are we positioned in the wrong direction (i.e. long when we should be short?) If so, we need to close STP and open open trades. # not going to take a position at this time. # the bars data is the current, not completed, bar so we have to go back to get closed bars. contContract, contracthours = get_contract( self) #basic information on continuious contact tradeContract = self.ib.qualifyContracts(contContract)[ 0] # gives all the details of a contract so we can trade it open_long, open_short, long_position_qty, short_position_qty, account_qty = orders.countOpenPositions( self.ib, "") # do we have an open position - not orders but positions? open_today, tradingDayRules = helpers.is_open_today(contracthours) wait_time, self.datetime_15, self.datetime_1h, self.datetime_1d, self.log_time = self.define_times( self.ib) dataContract = Contract(exchange=config.EXCHANGE, secType="FUT", localSymbol=contContract.localSymbol) bars_15m = calculations.Calculations(self.ib, dataContract, "2 D", "15 mins", self.datetime_15, False, 0) #print("bars15 cci_third, ccia_third, cci_prior, ccia_prior, cci, ccia",bars_15m.cci_third,bars_15m.ccia_third,bars_15m.cci_prior, bars_15m.ccia_prior, bars_15m.cci, bars_15m.ccia) if (bars_15m.cci_prior > bars_15m.ccia_prior and open_short) or (bars_15m.cci_prior < bars_15m.ccia_prior and open_long): log.debug( "justStartedAppDirectionCheck: we are in app start up and we need to reverse due to wrong direction" ) allClosed = orders.closeOutMain( self.ib, tradeContract, True ) # we don't worry about whether we are long or short. just passing the contract, need to add order. Second false is whether this is an opening order. it is not log.debug( "justStartedAppDirectionCheck: crossed but not tradeNow so lets close stp and open positions" ) else: log.debug( "justStartedAppDirectionCheck: we are in app start up and we DO NOT need to reverse due to wrong direction" ) # now check if we should be pending on restart if (bars_15m.cci_four > bars_15m.ccia_four and bars_15m.cci_third < bars_15m.ccia_third and bars_15m.cci_prior < bars_15m.ccia_prior and \ abs(bars_15m.cci_third - bars_15m.ccia_third) < config.SPREAD and abs(bars_15m.cci_prior - bars_15m.ccia_prior) < config.SPREAD) or \ (bars_15m.cci_four < bars_15m.ccia_four and bars_15m.cci_third > bars_15m.ccia_third and bars_15m.cci_prior > bars_15m.ccia_prior and \ abs(bars_15m.cci_third - bars_15m.ccia_third) < config.SPREAD and abs(bars_15m.cci_prior - bars_15m.ccia_prior) < config.SPREAD): log.debug( "justStartedAppDirectionCheck: we are in a second leg pending situation on start up" ) if bars_15m.cci_prior > bars_15m.ccia_prior: return True, False, 2 else: return False, True, 2 elif (bars_15m.cci_third > bars_15m.ccia_third and bars_15m.cci_prior < bars_15m.ccia_prior and abs(bars_15m.cci_prior - bars_15m.ccia_prior) < config.SPREAD) or \ (bars_15m.cci_third < bars_15m.ccia_third and bars_15m.cci_prior > bars_15m.ccia_prior and abs(bars_15m.cci_prior - bars_15m.ccia_prior) < config.SPREAD): log.debug( "justStartedAppDirectionCheck: we are in a first leg pending situation on start up" ) if bars_15m.cci_prior > bars_15m.ccia_prior: return True, False, 1 else: return False, True, 1 else: log.debug( "justStartedAppDirectionCheck: we are not in an exiting pending pattern" ) return False, False, 0