Esempio n. 1
0
File: aGen.py Progetto: grmte/ml
def main():
    try:
        attribute.initializeInstDetails(args.iT, args.sP, args.oT, args.rev)
        if args.i is not None:
            attribute.checkIfAttributeOutputFileExists(
                os.path.basename(moduleName), args.n, args.i, args.o, args.m,
                args.d)
        else:
            attribute.checkIfAttributeOutputFileExists(
                os.path.basename(moduleName), args.n, args.c, args.o, args.m,
                args.d)
        if args.rev != None and args.rev.lower() == "yes":
            dataFile.getSelectedDataIntoMatrix(args.d)
        else:
            if (args.cType == "synthetic"):
                if "For6Levels" not in args.g:
                    dataFile.getDataIntoMatrix(args.d, args.c, level=5)
                else:
                    try:
                        dataFile.getDataIntoMatrix(args.d, args.c, level=5)
                    except:
                        dataFile.getDataIntoMatrix(args.d, args.c, level=6)
            else:
                if "For6Levels" not in args.g:
                    dataFile.getDataIntoMatrix(args.d, level=5)
                else:
                    try:
                        dataFile.getDataIntoMatrix(args.d, level=5)
                    except:
                        dataFile.getDataIntoMatrix(args.d, level=6)

        attribute.initList()
        lHeaderColumnNamesList = userModule.extractAttributeFromDataMatrix(
            args)
        if args.i is not None:
            fileName = attribute.getOutputFileNameFromGeneratorName(
                os.path.basename(moduleName), args.n, args.i, args.o, args.m,
                args.d)
        else:
            fileName = attribute.getOutputFileNameFromGeneratorName(
                os.path.basename(moduleName), args.n, args.c, args.o, args.m,
                args.d)
        print fileName
        attribute.writeToFile(fileName, lHeaderColumnNamesList)
        attribute.callRProgramToConvertToBinary(fileName)
    except:
        traceback.print_exc()
        e = sys.exc_info()[0]
        print e
        os._exit(-1)
Esempio n. 2
0
File: aGen.py Progetto: grmte/ml
def main():
   try:
      attribute.initializeInstDetails(args.iT,args.sP,args.oT,args.rev) 
      if args.i is not None: 
          attribute.checkIfAttributeOutputFileExists(os.path.basename(moduleName),args.n,args.i,args.o,args.m,args.d)
      else:
          attribute.checkIfAttributeOutputFileExists(os.path.basename(moduleName),args.n,args.c,args.o,args.m,args.d)
      if args.rev!= None and args.rev.lower()=="yes":
          dataFile.getSelectedDataIntoMatrix(args.d)
      else:
          if(args.cType == "synthetic"):
              if "For6Levels" not in args.g:
                  dataFile.getDataIntoMatrix(args.d,args.c , level=5)
              else:
                  try:
                      dataFile.getDataIntoMatrix(args.d,args.c, level=5)
                  except:
                      dataFile.getDataIntoMatrix(args.d,args.c, level=6)
          else:
              if "For6Levels" not in args.g:
                  dataFile.getDataIntoMatrix(args.d , level=5)
              else:
                  try:
                      dataFile.getDataIntoMatrix(args.d, level=5)
                  except:
                      dataFile.getDataIntoMatrix(args.d, level=6)

      attribute.initList()
      lHeaderColumnNamesList = userModule.extractAttributeFromDataMatrix(args)
      if args.i is not None:
          fileName = attribute.getOutputFileNameFromGeneratorName(os.path.basename(moduleName),args.n,args.i,args.o,args.m,args.d )
      else:
          fileName = attribute.getOutputFileNameFromGeneratorName(os.path.basename(moduleName),args.n,args.c,args.o,args.m,args.d )
      print fileName
      attribute.writeToFile(fileName , lHeaderColumnNamesList)
      attribute.callRProgramToConvertToBinary(fileName) 
   except:
      traceback.print_exc()
      e = sys.exc_info()[0]
      print e
      os._exit(-1)
Esempio n. 3
0
def readOnceAndWrite(pFileName, pIndexOfEntryOrExitCL, predictedValuesDict):
    global transactionCost , currencyDivisor 
    attribute.initList()
    enterTradeShort = 0
    enterTradeLong = 0
    ltpAtTimeOfPreviousDataRow = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    askQ0AtTimeOfPreviousDataRow = 0
    bidQ0AtTimeOfPreviousDataRow = 0
    currentTimeStamp = 0
    tradeStats = dict()
    tradeStats['totalSellValueShort'] = 0
    tradeStats['totalBuyValueShort'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['totalSellValueLong'] = 0
    tradeStats['totalBuyValueLong'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentSellPredictedValue = 0
    currentBuyPredictedValue = 0
    entryCL = float(totalEntryCL[pIndexOfEntryOrExitCL])/100
    exitCL = float(totalExitCL[pIndexOfEntryOrExitCL])/100
    print (entryCL, exitCL)
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    numberOfTimesAskedToEnterTradeShort = 0
    numberOfTimesAskedToEnterTradeLong = 0
    numberOfTimesAskedToExitTradeShort = 0
    numberOfTimesAskedToExitTradeLong = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
    reasonForTrade['CloseBuyTradeHappened'] = 0
    reasonForTrade['OpenBuyTradeHappened'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
    reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
    reasonForTrade['OpenSellTradeHappened'] = 0
    reasonForTrade['CloseSellTradeHappened'] = 0
    reasonForTrade['PrevWasOurOrder'] = 0
    lReasonForTradingOrNotTradingShort = ""
    lReasonForTradingOrNotTradingLong = ""
    currentIndex = 0
    print("Processing the data file for trades :")
    attribute.initList()
    for currentDataRow in dataFile.matrix[10000:]:
        
        lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,ttqAtTimeOfPreviousDataRow,askP0AtTimeOfPreviousDataRow,bidP0AtTimeOfPreviousDataRow,\
                                                                             askQ0AtTimeOfPreviousDataRow , bidQ0AtTimeOfPreviousDataRow , enterTradeShort,enterTradeLong,tradeStats,reasonForTrade,\
                                                                             lReasonForTradingOrNotTradingLong,lReasonForTradingOrNotTradingShort )
    
        lReasonForTradingOrNotTradingShort = lReturnList[0]
        lReasonForTradingOrNotTradingLong = lReturnList[1] 
        lDummyBidQ0 = lReturnList[2]
        lDummyAskQ0 = lReturnList[3]
        lDummyTTQForBuy = lReturnList[4]
        lDummyTTQForSell = lReturnList[5]
        if currentIndex > 0:
            attribute.aList[currentIndex-1][0] = currentTimeStamp
            attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
            attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
            listOfStringsToPrint = [ str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , \
                                    str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) ,\
                                    str(currentSellPredictedValue) , str(enterTradeShort) ,lReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                                    str(enterTradeLong) ,lReasonForTradingOrNotTradingLong , str(reasonForTrade['CloseBuyTradeHappened']),\
                                    str(reasonForTrade['OpenBuyTradeHappened']),str(reasonForTrade['OpenSellTradeHappened']),\
                                    str(reasonForTrade['CloseSellTradeHappened']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                    str(lDummyTTQForBuy),str(lDummyTTQForSell)]
            attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])
    
        try:
            currentSellPredictedValue = float(predictedValuesDict[currentTimeStamp]['sell']) 
            currentBuyPredictedValue  = float(predictedValuesDict[currentTimeStamp]['buy'])
        except:
            noPredictionForThisRow += 1
    
        #short decisions
        if(currentSellPredictedValue >= entryCL and tradeStats['currentPositionLong'] == 0):
            enterTradeShort = 1
            numberOfTimesAskedToEnterTradeShort += 1
        elif(currentBuyPredictedValue >= exitCL and tradeStats['currentPositionShort'] > 0):
            numberOfTimesAskedToExitTradeShort += 1
            enterTradeShort = -1  # Implies to exit the trade
        else:
            enterTradeShort = 0  # Implies make no change
            
    #       if enterTradeShort == 1:
    #           if currentPredictedValue <= entryCLCutoff:
    #               enterTrade = 0
    #       if enterTrade == -1:
    #           if currentPredictedValue >= exitCLCutoff:
    #               enterTrade = 0
                
        #long decisions
        if(currentBuyPredictedValue >= entryCL and tradeStats['currentPositionShort'] == 0):
            enterTradeLong = 1
            numberOfTimesAskedToEnterTradeLong += 1
        elif(currentSellPredictedValue >= exitCL and tradeStats['currentPositionLong'] > 0):
            numberOfTimesAskedToExitTradeLong += 1
            enterTradeLong = -1  # Implies to exit the trade
        else:
            enterTradeLong = 0  # Implies make no change
        
        ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ])
        if((args.e).find("nsefut") >= 0):
            askP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BestAskP])
            bidP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BestBidP])
            askQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BestAskQ])
            bidQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BestBidQ])
        else:
            askP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskP0])
            bidP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidP0])
            askQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskQ0])
            bidQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidQ0])
        ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
        currentIndex = currentIndex + 1
    
    # Squaring off if some open position there   
    if tradeStats['currentPositionLong'] > 0:
        reasonForTrade['CloseSellTradeHappened'] += tradeStats['currentPositionLong']
        tradeStats['totalSellValueLong'] += tradeStats['currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionLong'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    if tradeStats['currentPositionShort'] > 0:
        reasonForTrade['CloseBuyTradeHappened'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyValueShort'] += tradeStats['currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionShort'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'
    
    attribute.aList[currentIndex-1][0] = currentTimeStamp
    attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
    listOfStringsToPrint = [ str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , str(currentSellPredictedValue) , str(enterTradeShort) , "" , str(currentBuyPredictedValue) , str(enterTradeLong) ,"" , str(reasonForTrade['CloseBuyTradeHappened']),str(reasonForTrade['OpenBuyTradeHappened']),str(reasonForTrade['OpenSellTradeHappened']),str(reasonForTrade['CloseSellTradeHappened']),str(lDummyBidQ0),str(lDummyAskQ0),str(lDummyTTQForBuy),str(lDummyTTQForSell)]
    attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
    
    dirName = args.pd.replace('/ro/','/rs/')
    tradeLogMainDirName = dirName+"/t/"
    if not os.path.exists(tradeLogMainDirName):
         os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeLogSubDirectoryName):
         os.mkdir(tradeLogSubDirectoryName)
    
    fileName = tradeLogSubDirectoryName + pFileName + ".trade" 
    lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP','CurPredValueShort','EnterTradeShort','ReasonForTradingOrNotTradingShort','CurPredValueLong','EnterTradeLong','ReasonForTradingOrNotTradingLong','totalBuyTradeShort','totalBuyLong','totalSellShort','totalSellLong','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy']
    attribute.writeToFile(fileName , lHeaderColumnNamesList)
    
    tradeResultMainDirName = dirName+"/r/"
    if not os.path.exists(tradeResultMainDirName):
         os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeResultSubDirectoryName):
         os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName+pFileName+".result" 
    outputFile = open(fileName,"w")
    gross_short_profit = tradeStats['totalSellValueShort'] - tradeStats['totalBuyValueShort']
    gross_long_profit = tradeStats['totalSellValueLong'] - tradeStats['totalBuyValueLong']
    gross_profit = gross_short_profit + gross_long_profit
    net_short_profit = gross_short_profit - ( transactionCost * ( tradeStats['totalSellValueShort'] +  tradeStats['totalBuyValueShort'] ) ) 
    net_long_profit = gross_long_profit - ( transactionCost * ( tradeStats['totalSellValueLong'] +  tradeStats['totalBuyValueLong'] ) )
    net_profit = net_short_profit + net_long_profit
    
    gross_short_profit_in_dollars = gross_profit / (currencyDivisor * 60)
    net_profit_in_dollars = net_profit / (currencyDivisor * 60 )
    #changed file write to modify it to Short Long version
    print("Starting to write: "+pFileName)
    print("The gross results for Short are: %.6f" %gross_short_profit, file = outputFile)
    print("The gross results for Long are: %.6f" %gross_long_profit, file = outputFile)
    print("Number of rows for which there is no prediction: " + str(0), file = outputFile)    
    print("Number of times asked to enter trade Short: " + str(numberOfTimesAskedToEnterTradeShort), file = outputFile)    
    print("Number of times asked to enter trade Long: " + str(numberOfTimesAskedToEnterTradeLong), file = outputFile)    
    print("Number of times asked to exit trade Short: " + str(numberOfTimesAskedToExitTradeShort), file = outputFile)
    print("Number of times asked to exit trade Long: " + str(numberOfTimesAskedToExitTradeLong), file = outputFile)
    print("The net results for Short are: %.6f" %net_short_profit, file = outputFile)
    print("The net results for Long are: %.6f" %net_long_profit, file = outputFile)
    print("Gross Results in Dollars: %.6f" %gross_short_profit_in_dollars, file = outputFile)
    print("Net Results in Dollars: %.6f" %net_profit_in_dollars, file = outputFile)
    print("Number of times Close buy trade happened: " + str(reasonForTrade['CloseBuyTradeHappened']), file = outputFile)
    print("Number of times open buy trade happened: " + str(reasonForTrade['OpenBuyTradeHappened']), file = outputFile)
    print("Assumed open sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']), file = outputFile)
    print("Assumed close sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']), file = outputFile)
    print("Assumed open sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Short']), file = outputFile)
    print("Assumed close sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Long']), file = outputFile)
    print("Number of Open sell trade happened: " + str(reasonForTrade['OpenSellTradeHappened']), file = outputFile)
    print("Number of Close sell trade happened: " + str(reasonForTrade['CloseSellTradeHappened']), file = outputFile)
    print("The total open sell value is: " + str(tradeStats['totalSellValueShort']), file = outputFile)
    print("The total close sell value is: " + str(tradeStats['totalSellValueLong']), file = outputFile)
    print("The total close buy value is: " + str(tradeStats['totalBuyValueShort']), file = outputFile)
    print("The total open buy value is: " + str(tradeStats['totalBuyValueLong']), file = outputFile)

    try:
        averageOpenSellPrice = tradeStats['totalSellValueShort']/reasonForTrade['OpenSellTradeHappened']
        averageCloseBuyPrice = tradeStats['totalBuyValueShort']/reasonForTrade['CloseBuyTradeHappened']
    except:
        averageOpenSellPrice = 0 
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellValueLong']/reasonForTrade['CloseSellTradeHappened']
        averageOpenBuyPrice = tradeStats['totalBuyValueLong']/reasonForTrade['OpenBuyTradeHappened']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0 
    
    print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
    print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
    print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
    print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
    print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
    print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
    pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
    pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)
Esempio n. 4
0
def readOnceAndWrite(pFileName, targetValuesDict):
    global gOpenBuyPrice, gCloseSellPrice, gOpenSellPrice, gCloseBuyPrice
    attribute.initList()
    enterTradeShort = 0
    enterTradeLong = 0
    ltpAtTimeOfPreviousDataRow = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    askQ0AtTimeOfPreviousDataRow = 0
    bidQ0AtTimeOfPreviousDataRow = 0
    exchangeTimeStamp = 0
    currentTimeStamp = 0
    tradeStats = dict()
    tradeStats['totalSellValueShort'] = 0
    tradeStats['totalBuyValueShort'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['totalSellValueLong'] = 0
    tradeStats['totalBuyValueLong'] = 0
    tradeStats['currentPositionLong'] = 0
    noTargetForThisRow = 0
    currentSellTargetValue = 0
    currentBuyTargetValue = 0
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    numberOfTimesAskedToEnterTradeShort = 0
    numberOfTimesAskedToEnterTradeLong = 0
    numberOfTimesAskedToExitTradeShort = 0
    numberOfTimesAskedToExitTradeLong = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
    reasonForTrade['CloseBuyTradeHappened'] = 0
    reasonForTrade['OpenBuyTradeHappened'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
    reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
    reasonForTrade['OpenSellTradeHappened'] = 0
    reasonForTrade['CloseSellTradeHappened'] = 0
    reasonForTrade['PrevWasOurOrder'] = 0
    lReasonForTradingOrNotTradingShort = ""
    lReasonForTradingOrNotTradingLong = ""
    currentIndex = 0
    lDummyBidQ0 = 0
    lDummyAskQ0 = 0
    lDummyTTQForBuy = 0
    lDummyTTQForSell = 0
    print("Processing the data file for trades :")
    attribute.initList()
    prevBuyTargetValue = 0
    prevSellTargetValue = 0
    exchangeTimeStamp = 0
    lOpenBuyIndex = 0
    lOpenSellIndex = 0
    l_exchange_time_stamp_to_print = ""
    for currentDataRow in dataFile.matrix:

        l_expiry_wrt_1970 = exchangeTimeStamp + 315513000.0

        l_dt = datetime.datetime.fromtimestamp(l_expiry_wrt_1970)
        l_exchange_time_stamp_to_print = str(l_dt.hour) + ":" + str(
            l_dt.minute) + ":" + str(l_dt.second)
        lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,ttqAtTimeOfPreviousDataRow,askP0AtTimeOfPreviousDataRow,bidP0AtTimeOfPreviousDataRow,\
                                                                                 askQ0AtTimeOfPreviousDataRow , bidQ0AtTimeOfPreviousDataRow , enterTradeShort,enterTradeLong,tradeStats,reasonForTrade,\
                                                                                 lReasonForTradingOrNotTradingLong,lReasonForTradingOrNotTradingShort )

        lReasonForTradingOrNotTradingShort = lReturnList[0]
        lReasonForTradingOrNotTradingLong = lReturnList[1]
        lDummyBidQ0 = lReturnList[2]
        lDummyAskQ0 = lReturnList[3]
        lDummyTTQForBuy = lReturnList[4]
        lDummyTTQForSell = lReturnList[5]
        if currentIndex > 0:
            lFlag = 0
            if "CloseSell" in lReasonForTradingOrNotTradingLong:
                if gCloseSellPrice - gOpenBuyPrice <= 0:
                    for i in range(lOpenBuyIndex, currentIndex):
                        attribute.aList[i][1] = 0
                else:
                    lFlag = 1
                lOpenBuyIndex = 0
            if "CloseBuy" in lReasonForTradingOrNotTradingShort:
                if gOpenSellPrice - gCloseBuyPrice <= 0:
                    for i in range(lOpenSellIndex, currentIndex):
                        attribute.aList[i][1] = 0
                else:
                    lFlag = 1
                lOpenSellIndex = 0
            if "OpenSell" in lReasonForTradingOrNotTradingShort:
                lOpenSellIndex = currentIndex - 1
            if "OpenBuy" in lReasonForTradingOrNotTradingLong:
                lOpenBuyIndex = currentIndex - 1

            if (lOpenSellIndex != 0 or lOpenBuyIndex != 0):
                lFlag = 1

            attribute.aList[currentIndex - 1][0] = currentTimeStamp
            attribute.aList[currentIndex - 1][1] = lFlag
            attribute.aList[currentIndex -
                            1][2] = tradeStats['currentPositionLong']
            listOfStringsToPrint = [ str(tradeStats['currentPositionShort']) , str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , \
                                    str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) ,\
                                    str(currentSellTargetValue) , str(enterTradeShort) ,lReasonForTradingOrNotTradingShort , str(currentBuyTargetValue) ,\
                                    str(enterTradeLong) ,lReasonForTradingOrNotTradingLong ,l_exchange_time_stamp_to_print, str(reasonForTrade['CloseBuyTradeHappened']),\
                                    str(reasonForTrade['OpenBuyTradeHappened']),str(reasonForTrade['OpenSellTradeHappened']),str(reasonForTrade['CloseSellTradeHappened']),\
                                    str(gCloseSellPrice),str(gOpenBuyPrice),str(gOpenSellPrice),str(gCloseBuyPrice)]
            attribute.aList[currentIndex -
                            1][3] = ";".join(listOfStringsToPrint)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(
            currentDataRow[colNumberOfData.TimeStamp])

        try:
            currentSellTargetValue = float(
                targetValuesDict[currentTimeStamp]['sell'])
            currentBuyTargetValue = float(
                targetValuesDict[currentTimeStamp]['buy'])
        except:
            noTargetForThisRow += 1

        #short decisions
        if (currentSellTargetValue == 1):
            enterTradeShort = 1
            numberOfTimesAskedToEnterTradeShort += 1
        elif (currentSellTargetValue == 0
              and tradeStats['currentPositionShort'] > 0):
            numberOfTimesAskedToExitTradeShort += 1
            enterTradeShort = -1  # Implies to exit the trade
        else:
            enterTradeShort = 0  # Implies make no change

        #long decisions
        if (currentBuyTargetValue == 1):
            enterTradeLong = 1
            numberOfTimesAskedToEnterTradeLong += 1
        elif (currentBuyTargetValue == 0
              and tradeStats['currentPositionLong'] > 0):
            numberOfTimesAskedToExitTradeLong += 1
            enterTradeLong = -1  # Implies to exit the trade
        else:
            enterTradeLong = 0  # Implies make no change

        ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ])
        askP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskP0])
        bidP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidP0])
        askQ0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskQ0])
        bidQ0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidQ0])
        ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
        currentIndex = currentIndex + 1
        prevBuyTargetValue = currentBuyTargetValue
        prevSellTargetValue = currentSellTargetValue
        exchangeTimeStamp = float(currentDataRow[colNumberOfData.ExchangeTS])

    # Squaring off if some open position there
    if tradeStats['currentPositionLong'] > 0:
        reasonForTrade['CloseSellTradeHappened'] += tradeStats[
            'currentPositionLong']
        tradeStats['totalSellValueLong'] += tradeStats[
            'currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionLong'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
        gCloseSellPrice = bidP0AtTimeOfPreviousDataRow
        if gCloseSellPrice - gOpenBuyPrice < 0:
            for i in range(lOpenBuyIndex, currentIndex):
                attribute.aList[i][1] = 0

    if tradeStats['currentPositionShort'] > 0:
        reasonForTrade['CloseBuyTradeHappened'] += tradeStats[
            'currentPositionShort']
        tradeStats['totalBuyValueShort'] += tradeStats[
            'currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionShort'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'
        gCloseBuyPrice = askP0AtTimeOfPreviousDataRow
        if gOpenSellPrice - gCloseBuyPrice < 0:
            for i in range(lOpenSellIndex, currentIndex):
                attribute.aList[i][1] = 0

    attribute.aList[currentIndex - 1][0] = currentTimeStamp
    attribute.aList[currentIndex - 1][1] = attribute.aList[currentIndex - 2][1]
    attribute.aList[currentIndex - 1][2] = tradeStats['currentPositionLong']
    listOfStringsToPrint = [ str(tradeStats['currentPositionShort']),str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) ,\
                             str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , \
                             str(currentSellTargetValue) , str(enterTradeShort) , "" , str(currentBuyTargetValue) , str(enterTradeLong) ,\
                             "" ,l_exchange_time_stamp_to_print, str(reasonForTrade['CloseBuyTradeHappened']),str(reasonForTrade['OpenBuyTradeHappened']),str(reasonForTrade['OpenSellTradeHappened']),\
                             str(reasonForTrade['CloseSellTradeHappened']),str(gCloseSellPrice),str(gOpenBuyPrice),str(gOpenSellPrice),str(gCloseBuyPrice)]
    attribute.aList[currentIndex - 1][3] = ";".join(listOfStringsToPrint)

    dirName = args.d.replace('/ro/', '/wf/')
    tradeLogMainDirName = dirName + "/tr/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName = tradeLogMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)

    fileName = tradeLogSubDirectoryName + pFileName + ".targetTrade"
    lHeaderColumnNamesList  = ['TimeStamp','targetValue','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP',\
                               'CurTargetValueShort','EnterTradeShort','ReasonForTradingOrNotTradingShort','CurTargetValueLong','EnterTradeLong',\
                               'ReasonForTradingOrNotTradingLong','Exchange_TS','totalBuyShort','totalBuyLong','totalSellShort','totalSellLong','CloseSellPrice',\
                               'OpenBuyPrice','OpenSellPrice','CloseBuyPrice']
    attribute.writeToFile(fileName, lHeaderColumnNamesList)

    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName + pFileName + ".targetResult"
    outputFile = open(fileName, "w")

    #changed file write to modify it to Short Long version
    print("Starting to write: " + fileName)
    print("The net results for Short are: " +
          str(tradeStats['totalSellValueShort'] -
              tradeStats['totalBuyValueShort']),
          file=outputFile)
    print("The net results for Long are: " +
          str(tradeStats['totalSellValueLong'] -
              tradeStats['totalBuyValueLong']),
          file=outputFile)
    print("Number of rows for which there is no target: " +
          str(noTargetForThisRow),
          file=outputFile)
    print("Number of times asked to enter trade Short: " +
          str(numberOfTimesAskedToEnterTradeShort),
          file=outputFile)
    print("Number of times asked to enter trade Long: " +
          str(numberOfTimesAskedToEnterTradeLong),
          file=outputFile)
    print("Number of times asked to exit trade Short: " +
          str(numberOfTimesAskedToExitTradeShort),
          file=outputFile)
    print("Number of times asked to exit trade Long: " +
          str(numberOfTimesAskedToExitTradeLong),
          file=outputFile)
    print(
        "Assumed close buy trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort']),
        file=outputFile)
    print(
        "Assumed open buy trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong']),
        file=outputFile)
    print(
        "Assumed close buy trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualBidP0Short']),
        file=outputFile)
    print(
        "Assumed open buy trade did not happen since bidP0 not same as LTP: " +
        str(reasonForTrade['LTPDoesNotEqualBidP0Long']),
        file=outputFile)
    print("Assumed close buy trade happened: " +
          str(reasonForTrade['CloseBuyTradeHappened']),
          file=outputFile)
    print("Assumed open buy trade happened: " +
          str(reasonForTrade['OpenBuyTradeHappened']),
          file=outputFile)
    print(
        "Assumed open sell trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']),
        file=outputFile)
    print(
        "Assumed close sell trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']),
        file=outputFile)
    print(
        "Assumed open sell trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualAskP0Short']),
        file=outputFile)
    print(
        "Assumed close sell trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualAskP0Long']),
        file=outputFile)
    print("Assumed open sell trade happened: " +
          str(reasonForTrade['OpenSellTradeHappened']),
          file=outputFile)
    print("Assumed close sell trade happened: " +
          str(reasonForTrade['CloseSellTradeHappened']),
          file=outputFile)
    print("The total open sell value is: " +
          str(tradeStats['totalSellValueShort']),
          file=outputFile)
    print("The total close sell value is: " +
          str(tradeStats['totalSellValueLong']),
          file=outputFile)
    print("The total close buy value is: " +
          str(tradeStats['totalBuyValueShort']),
          file=outputFile)
    print("The total open buy value is: " +
          str(tradeStats['totalBuyValueLong']),
          file=outputFile)

    try:
        averageOpenSellPrice = tradeStats[
            'totalSellValueShort'] / reasonForTrade['OpenSellTradeHappened']
        averageCloseBuyPrice = tradeStats[
            'totalBuyValueShort'] / reasonForTrade['CloseBuyTradeHappened']
    except:
        averageOpenSellPrice = 0
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats[
            'totalSellValueLong'] / reasonForTrade['CloseSellTradeHappened']
        averageOpenBuyPrice = tradeStats['totalBuyValueLong'] / reasonForTrade[
            'OpenBuyTradeHappened']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0

    print("Average open sell price per unit is: " + str(averageOpenSellPrice),
          file=outputFile)
    print("Average close sell price per unit is: " +
          str(averageCloseSellPrice),
          file=outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice),
          file=outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice),
          file=outputFile)
    print("The current position Short: " +
          str(tradeStats['currentPositionShort']),
          file=outputFile)
    print("The current position Long: " +
          str(tradeStats['currentPositionLong']),
          file=outputFile)
    print("Profit or loss per Qty traded Short is: " +
          str(averageOpenSellPrice - averageCloseBuyPrice),
          file=outputFile)
    print("Profit or loss per Qty traded Long is: " +
          str(averageCloseSellPrice - averageOpenBuyPrice),
          file=outputFile)
    pLPerLotShort = (averageOpenSellPrice - averageCloseBuyPrice) * 1000
    pLPerLotLong = (averageCloseSellPrice - averageOpenBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " +
          str(pLPerLotShort),
          file=outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong),
          file=outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10),
          file=outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10),
          file=outputFile)
Esempio n. 5
0
File: tradeE12.py Progetto: grmte/ml
def readOnceAndWrite(pFileName, entryCL1 , entryCL2 , entryCL3 , entryCL4 , exitCL1 , exitCL2 , exitCL3 , exitCL4 , predictedValuesDict):
    global g_bestqty_list_for_sell, g_bestqty_list_for_buy
    attribute.initList()
    tradeStats = dict()
    tradeStats['totalSellAmountShort'] = 0
    tradeStats['totalBuyAmountShort'] = 0
    tradeStats['totalSellAmountLong'] = 0
    tradeStats['totalBuyAmountLong'] = 0
    tradeStats['NumberOfOpenBuy'] = 0
    tradeStats['NumberOfCloseSell'] = 0
    tradeStats['NumberOfOpenSell'] = 0
    tradeStats['NumberOfCloseBuy'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentSellPredictedValue = 0
    currentBuyPredictedValue = 0
    currentIndex = 0
    l_previous_obj = None
    l_obj= None
    print("Processing the data file for trades :")
    attribute.initList()
    print("EntryLevels",entryCL1 , entryCL2 , entryCL3 , entryCL4 , exitCL1 , exitCL2 , exitCL3 , exitCL4)
    for currentDataRow in dataFile.matrix:
        
        l_obj = update_obj_list(currentDataRow)
        if(l_previous_obj != None):
            lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful( l_obj , l_previous_obj , tradeStats )
            
            lDummyBidQ0 = lReturnList[0]
            lDummyAskQ0 = lReturnList[1]
            lDummyTTQForBuy = lReturnList[2]
            lDummyTTQForSell = lReturnList[3]
            lBuyTradedPrice = lReturnList[4]
            lBuyTradedQty = lReturnList[5]
            lSellTradedPrice = lReturnList[6]
            lSellTradedQty = lReturnList[7]
            if currentIndex > 0:
                if(g_bestqty_list_for_buy != {}):
                    l_best_bidq = g_bestqty_list_for_buy['qty']
                    l_best_bidp = g_bestqty_list_for_buy['price']
                else:
                    l_best_bidq = 0
                    l_best_bidp = 0
                if(g_bestqty_list_for_sell != {}):
                    l_best_askq = g_bestqty_list_for_sell['qty']
                    l_best_askp = g_bestqty_list_for_sell['price'] 
                else:
                    l_best_askq = 0
                    l_best_askp = 0
                attribute.aList[currentIndex-1][0] = l_obj.currentTimeStamp
                attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
                attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
                listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP) , \
                                        str(l_previous_obj.AskQ) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                                        str(currentSellPredictedValue) , str(l_previous_obj.EnterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                                        str(l_previous_obj.EnterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                                        str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                                        str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                        str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp),\
                                        str(l_best_askq) ,str(lBuyTradedPrice), str(lBuyTradedQty), str(lSellTradedPrice),str(lSellTradedQty)]
                attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
            currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])
            
            try:
                currentSellPredictedValue = float(predictedValuesDict[l_obj.currentTimeStamp]['sell']) 
                currentBuyPredictedValue  = float(predictedValuesDict[l_obj.currentTimeStamp]['buy'])
            except:
                noPredictionForThisRow += 1

            #Open sell and Close Buy
            if(currentSellPredictedValue >= entryCL4 and tradeStats['currentPositionLong'] == 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeShort = 4       #For close by hitting
            elif(currentSellPredictedValue >= entryCL3 and tradeStats['currentPositionLong'] == 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeShort = 3       #For standing at Bid +1 
            elif (currentSellPredictedValue >= entryCL2 and currentBuyPredictedValue < exitCL1 and tradeStats['currentPositionLong'] == 0):
                if(l_previous_obj.EnterTradeShort  not in [2,1] ):
                    g_bestqty_list_for_sell = {}
                l_obj.EnterTradeShort = 2       #For standing at bid
            elif (l_previous_obj.EnterTradeShort > 0 and currentSellPredictedValue >= entryCL1 and currentBuyPredictedValue < exitCL1 and tradeStats['currentPositionLong'] == 0):
                l_obj.EnterTradeShort = 1        ##For continuing to stand at bid
            elif(currentBuyPredictedValue >= exitCL4 and tradeStats['currentPositionShort'] > 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeShort = -4       #For close by hitting
            elif(currentBuyPredictedValue >= exitCL3 and tradeStats['currentPositionShort'] > 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeShort = -3       #For standing at Bid +1 
            elif (currentBuyPredictedValue >= exitCL2 and tradeStats['currentPositionShort'] > 0):
                if(l_previous_obj.EnterTradeShort  not in [-2,-1]):
                    g_bestqty_list_for_buy = {}
                l_obj.EnterTradeShort = -2       #For standing at bid
            elif (l_previous_obj.EnterTradeShort < 0 and currentBuyPredictedValue >= exitCL1 and tradeStats['currentPositionShort'] > 0):
                l_obj.EnterTradeShort = -1        ##For continuing to stand at bid
            else:
                l_obj.EnterTradeShort = 0

            #Open Buy
            if(currentBuyPredictedValue >= entryCL4 and tradeStats['currentPositionShort'] == 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeLong = 4       #For close by hitting
            elif(currentBuyPredictedValue >= entryCL3 and tradeStats['currentPositionShort'] == 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeLong = 3       #For standing at Bid +1 
            elif (currentBuyPredictedValue >= entryCL2 and currentSellPredictedValue < exitCL1  and tradeStats['currentPositionShort'] == 0):
                if(l_previous_obj.EnterTradeLong  not in [2,1]):
                    g_bestqty_list_for_buy = {}
                l_obj.EnterTradeLong = 2       #For standing at bid
            elif (l_previous_obj.EnterTradeLong < 0 and currentBuyPredictedValue >= entryCL1 and currentSellPredictedValue < exitCL1 and tradeStats['currentPositionShort'] == 0):
                l_obj.EnterTradeLong = 1       #For continuing to stand at bid
            elif(currentSellPredictedValue >= exitCL4 and tradeStats['currentPositionLong'] > 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeLong = -4       #For close by hitting
            elif(currentSellPredictedValue >= exitCL3 and tradeStats['currentPositionLong'] > 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeLong = -3       #For standing at Bid +1 
            elif (currentSellPredictedValue >= exitCL2  and tradeStats['currentPositionLong'] > 0):
                if(l_previous_obj.EnterTradeLong  not in [-2,-1] ):
                    g_bestqty_list_for_sell = {}
                l_obj.EnterTradeLong = -2       #For standing at bid
            elif (l_previous_obj.EnterTradeLong > 0 and currentSellPredictedValue >= exitCL1 and tradeStats['currentPositionLong'] > 0):
                l_obj.EnterTradeLong = -1        ##For continuing to stand at bid            
            else:
                l_obj.EnterTradeLong = 0        
            

        
        l_previous_obj = l_obj
        currentIndex = currentIndex + 1

# Squaring off if some open position there   
    if tradeStats['currentPositionLong'] > 0:
        tradeStats['NumberOfCloseSell'] += tradeStats['currentPositionLong']
        tradeStats['totalSellAmountLong'] += tradeStats['currentPositionLong'] * (l_previous_obj.BidP)
        tradeStats['currentPositionLong'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    if tradeStats['currentPositionShort'] > 0:
        tradeStats['NumberOfCloseBuy'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyAmountShort'] += tradeStats['currentPositionShort'] * (l_previous_obj.AskP)
        tradeStats['currentPositionShort'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'
    
    attribute.aList[currentIndex-1][0] = currentTimeStamp
    attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
    if(g_bestqty_list_for_buy != {}):
        l_best_bidq = g_bestqty_list_for_buy['qty']
        l_best_bidp = g_bestqty_list_for_buy['price'] 
    else:
        l_best_bidq = 0
        l_best_bidp = 0
    if(g_bestqty_list_for_sell != {}):
        l_best_askq = g_bestqty_list_for_sell['qty']
        l_best_askp = g_bestqty_list_for_sell['price'] 
    else:
        l_best_askq = 0
        l_best_askp = 0
    listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP) , \
                            str(l_previous_obj.AskQ) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                            str(currentSellPredictedValue) , str(l_previous_obj.EnterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                            str(l_previous_obj.EnterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                            str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                            str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                            str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp), str(l_best_askq) , "0;0;0;0"]
    attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
    
    dirName = args.pd.replace('/ro/','/rs/')
    tradeLogMainDirName = dirName+"/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
    
    fileName = tradeLogSubDirectoryName + pFileName + ".trade" 
    lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP','CurPredValueShort',\
                               'EnterTradeShort','ReasonForTradingOrNotTradingShort','CurPredValueLong','EnterTradeLong','ReasonForTradingOrNotTradingLong',\
                               'totalBuyTradeShort','totalBuyLong','totalSellShort','totalSellLong','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy' \
                               ,'BestBidQ','BestBidP','BestAskP','BestAskQ','BuyTradedPrcie','BuyTradedQty','SellTradedPrice','SellTradedQty']
    
    #attribute.writeToFile(fileName , lHeaderColumnNamesList)

    
    tradeResultMainDirName = dirName+"/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName+pFileName+".result" 
    outputFile = open(fileName,"w")
    
    #changed file write to modify it to Short Long version
    print("Starting to write: "+fileName)
    print("The gross profit for Short are: " + str(tradeStats['totalSellAmountShort'] - tradeStats['totalBuyAmountShort']), file = outputFile)
    print("The gross profit for Long are: " + str(tradeStats['totalSellAmountLong'] - tradeStats['totalBuyAmountLong']), file = outputFile)
    print("The total open sell amount is: " + str(tradeStats['totalSellAmountShort']), file = outputFile)
    print("The total close sell amount is: " + str(tradeStats['totalSellAmountLong']), file = outputFile)
    print("The total close buy amount is: " + str(tradeStats['totalBuyAmountShort']), file = outputFile)
    print("The total open buy amount is: " + str(tradeStats['totalBuyAmountLong']), file = outputFile)
    print("Number open sell trade happened: " + str(tradeStats['NumberOfOpenSell']), file = outputFile)
    print("Number close sell trade happened: " + str(tradeStats['NumberOfCloseSell']), file = outputFile)
    print("Number close buy trade happened: " + str(tradeStats['NumberOfCloseBuy']), file = outputFile)
    print("Number open buy trade happened: " + str(tradeStats['NumberOfOpenBuy']), file = outputFile)
       
    try:
        averageOpenSellPrice = tradeStats['totalSellAmountShort']/tradeStats['NumberOfOpenSell']
        averageCloseBuyPrice = tradeStats['totalBuyAmountShort']/tradeStats['NumberOfCloseBuy']
    except:
        averageOpenSellPrice = 0 
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellAmountLong']/tradeStats['NumberOfCloseSell']
        averageOpenBuyPrice = tradeStats['totalBuyAmountLong']/tradeStats['NumberOfOpenBuy']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0 
    
    print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
    print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
    print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
    print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
    print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
    print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
    pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
    pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)
Esempio n. 6
0
def readOnceAndWrite(pFileName, entryCL1, entryCL2, entryCL3, entryCL4,
                     exitCL1, exitCL2, exitCL3, exitCL4, predictedValuesDict):
    global g_bestqty_list_for_sell, g_bestqty_list_for_buy
    attribute.initList()
    tradeStats = dict()
    tradeStats['totalSellAmountShort'] = 0
    tradeStats['totalBuyAmountShort'] = 0
    tradeStats['totalSellAmountLong'] = 0
    tradeStats['totalBuyAmountLong'] = 0
    tradeStats['NumberOfOpenBuy'] = 0
    tradeStats['NumberOfCloseSell'] = 0
    tradeStats['NumberOfOpenSell'] = 0
    tradeStats['NumberOfCloseBuy'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentSellPredictedValue = 0
    currentBuyPredictedValue = 0
    currentIndex = 0
    l_previous_obj = None
    l_obj = None
    print("Processing the data file for trades :")
    attribute.initList()
    print("EntryLevels", entryCL1, entryCL2, entryCL3, entryCL4, exitCL1,
          exitCL2, exitCL3, exitCL4)
    for currentDataRow in dataFile.matrix:

        l_obj = update_obj_list(currentDataRow)
        if (l_previous_obj != None):
            lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(
                l_obj, l_previous_obj, tradeStats)

            lDummyBidQ0 = lReturnList[0]
            lDummyAskQ0 = lReturnList[1]
            lDummyTTQForBuy = lReturnList[2]
            lDummyTTQForSell = lReturnList[3]
            lBuyTradedPrice = lReturnList[4]
            lBuyTradedQty = lReturnList[5]
            lSellTradedPrice = lReturnList[6]
            lSellTradedQty = lReturnList[7]
            if currentIndex > 0:
                if (g_bestqty_list_for_buy != {}):
                    l_best_bidq = g_bestqty_list_for_buy['qty']
                    l_best_bidp = g_bestqty_list_for_buy['price']
                else:
                    l_best_bidq = 0
                    l_best_bidp = 0
                if (g_bestqty_list_for_sell != {}):
                    l_best_askq = g_bestqty_list_for_sell['qty']
                    l_best_askp = g_bestqty_list_for_sell['price']
                else:
                    l_best_askq = 0
                    l_best_askp = 0
                attribute.aList[currentIndex - 1][0] = l_obj.currentTimeStamp
                attribute.aList[currentIndex -
                                1][1] = tradeStats['currentPositionLong']
                attribute.aList[currentIndex -
                                1][2] = tradeStats['currentPositionShort']
                listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP) , \
                                        str(l_previous_obj.AskQ) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                                        str(currentSellPredictedValue) , str(l_previous_obj.EnterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                                        str(l_previous_obj.EnterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                                        str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                                        str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                        str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp),\
                                        str(l_best_askq) ,str(lBuyTradedPrice), str(lBuyTradedQty), str(lSellTradedPrice),str(lSellTradedQty)]
                attribute.aList[currentIndex -
                                1][3] = ";".join(listOfStringsToPrint)
            currentTimeStamp = common.convertTimeStampFromStringToFloat(
                currentDataRow[colNumberOfData.TimeStamp])

            try:
                currentSellPredictedValue = float(
                    predictedValuesDict[l_obj.currentTimeStamp]['sell'])
                currentBuyPredictedValue = float(
                    predictedValuesDict[l_obj.currentTimeStamp]['buy'])
            except:
                noPredictionForThisRow += 1

            #Open sell and Close Buy
            if (currentSellPredictedValue >= entryCL4
                    and tradeStats['currentPositionLong'] == 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeShort = 4  #For close by hitting
            elif (currentSellPredictedValue >= entryCL3
                  and tradeStats['currentPositionLong'] == 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeShort = 3  #For standing at Bid +1
            elif (currentSellPredictedValue >= entryCL2
                  and currentBuyPredictedValue < exitCL1
                  and tradeStats['currentPositionLong'] == 0):
                if (l_previous_obj.EnterTradeShort not in [2, 1]):
                    g_bestqty_list_for_sell = {}
                l_obj.EnterTradeShort = 2  #For standing at bid
            elif (l_previous_obj.EnterTradeShort > 0
                  and currentSellPredictedValue >= entryCL1
                  and currentBuyPredictedValue < exitCL1
                  and tradeStats['currentPositionLong'] == 0):
                l_obj.EnterTradeShort = 1  ##For continuing to stand at bid
            elif (currentBuyPredictedValue >= exitCL4
                  and tradeStats['currentPositionShort'] > 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeShort = -4  #For close by hitting
            elif (currentBuyPredictedValue >= exitCL3
                  and tradeStats['currentPositionShort'] > 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeShort = -3  #For standing at Bid +1
            elif (currentBuyPredictedValue >= exitCL2
                  and tradeStats['currentPositionShort'] > 0):
                if (l_previous_obj.EnterTradeShort not in [-2, -1]):
                    g_bestqty_list_for_buy = {}
                l_obj.EnterTradeShort = -2  #For standing at bid
            elif (l_previous_obj.EnterTradeShort < 0
                  and currentBuyPredictedValue >= exitCL1
                  and tradeStats['currentPositionShort'] > 0):
                l_obj.EnterTradeShort = -1  ##For continuing to stand at bid
            else:
                l_obj.EnterTradeShort = 0

            #Open Buy
            if (currentBuyPredictedValue >= entryCL4
                    and tradeStats['currentPositionShort'] == 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeLong = 4  #For close by hitting
            elif (currentBuyPredictedValue >= entryCL3
                  and tradeStats['currentPositionShort'] == 0):
                g_bestqty_list_for_buy = {}
                l_obj.EnterTradeLong = 3  #For standing at Bid +1
            elif (currentBuyPredictedValue >= entryCL2
                  and currentSellPredictedValue < exitCL1
                  and tradeStats['currentPositionShort'] == 0):
                if (l_previous_obj.EnterTradeLong not in [2, 1]):
                    g_bestqty_list_for_buy = {}
                l_obj.EnterTradeLong = 2  #For standing at bid
            elif (l_previous_obj.EnterTradeLong < 0
                  and currentBuyPredictedValue >= entryCL1
                  and currentSellPredictedValue < exitCL1
                  and tradeStats['currentPositionShort'] == 0):
                l_obj.EnterTradeLong = 1  #For continuing to stand at bid
            elif (currentSellPredictedValue >= exitCL4
                  and tradeStats['currentPositionLong'] > 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeLong = -4  #For close by hitting
            elif (currentSellPredictedValue >= exitCL3
                  and tradeStats['currentPositionLong'] > 0):
                g_bestqty_list_for_sell = {}
                l_obj.EnterTradeLong = -3  #For standing at Bid +1
            elif (currentSellPredictedValue >= exitCL2
                  and tradeStats['currentPositionLong'] > 0):
                if (l_previous_obj.EnterTradeLong not in [-2, -1]):
                    g_bestqty_list_for_sell = {}
                l_obj.EnterTradeLong = -2  #For standing at bid
            elif (l_previous_obj.EnterTradeLong > 0
                  and currentSellPredictedValue >= exitCL1
                  and tradeStats['currentPositionLong'] > 0):
                l_obj.EnterTradeLong = -1  ##For continuing to stand at bid
            else:
                l_obj.EnterTradeLong = 0

        l_previous_obj = l_obj
        currentIndex = currentIndex + 1

# Squaring off if some open position there
    if tradeStats['currentPositionLong'] > 0:
        tradeStats['NumberOfCloseSell'] += tradeStats['currentPositionLong']
        tradeStats['totalSellAmountLong'] += tradeStats[
            'currentPositionLong'] * (l_previous_obj.BidP)
        tradeStats['currentPositionLong'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    if tradeStats['currentPositionShort'] > 0:
        tradeStats['NumberOfCloseBuy'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyAmountShort'] += tradeStats[
            'currentPositionShort'] * (l_previous_obj.AskP)
        tradeStats['currentPositionShort'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'

    attribute.aList[currentIndex - 1][0] = currentTimeStamp
    attribute.aList[currentIndex - 1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex - 1][2] = tradeStats['currentPositionShort']
    if (g_bestqty_list_for_buy != {}):
        l_best_bidq = g_bestqty_list_for_buy['qty']
        l_best_bidp = g_bestqty_list_for_buy['price']
    else:
        l_best_bidq = 0
        l_best_bidp = 0
    if (g_bestqty_list_for_sell != {}):
        l_best_askq = g_bestqty_list_for_sell['qty']
        l_best_askp = g_bestqty_list_for_sell['price']
    else:
        l_best_askq = 0
        l_best_askp = 0
    listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP) , \
                            str(l_previous_obj.AskQ) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                            str(currentSellPredictedValue) , str(l_previous_obj.EnterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                            str(l_previous_obj.EnterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                            str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                            str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                            str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp), str(l_best_askq) , "0;0;0;0"]
    attribute.aList[currentIndex - 1][3] = ";".join(listOfStringsToPrint)

    dirName = args.pd.replace('/ro/', '/rs/')
    tradeLogMainDirName = dirName + "/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName = tradeLogMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)

    fileName = tradeLogSubDirectoryName + pFileName + ".trade"
    lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP','CurPredValueShort',\
                               'EnterTradeShort','ReasonForTradingOrNotTradingShort','CurPredValueLong','EnterTradeLong','ReasonForTradingOrNotTradingLong',\
                               'totalBuyTradeShort','totalBuyLong','totalSellShort','totalSellLong','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy' \
                               ,'BestBidQ','BestBidP','BestAskP','BestAskQ','BuyTradedPrcie','BuyTradedQty','SellTradedPrice','SellTradedQty']

    #attribute.writeToFile(fileName , lHeaderColumnNamesList)

    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName + pFileName + ".result"
    outputFile = open(fileName, "w")

    #changed file write to modify it to Short Long version
    print("Starting to write: " + fileName)
    print("The gross profit for Short are: " +
          str(tradeStats['totalSellAmountShort'] -
              tradeStats['totalBuyAmountShort']),
          file=outputFile)
    print("The gross profit for Long are: " +
          str(tradeStats['totalSellAmountLong'] -
              tradeStats['totalBuyAmountLong']),
          file=outputFile)
    print("The total open sell amount is: " +
          str(tradeStats['totalSellAmountShort']),
          file=outputFile)
    print("The total close sell amount is: " +
          str(tradeStats['totalSellAmountLong']),
          file=outputFile)
    print("The total close buy amount is: " +
          str(tradeStats['totalBuyAmountShort']),
          file=outputFile)
    print("The total open buy amount is: " +
          str(tradeStats['totalBuyAmountLong']),
          file=outputFile)
    print("Number open sell trade happened: " +
          str(tradeStats['NumberOfOpenSell']),
          file=outputFile)
    print("Number close sell trade happened: " +
          str(tradeStats['NumberOfCloseSell']),
          file=outputFile)
    print("Number close buy trade happened: " +
          str(tradeStats['NumberOfCloseBuy']),
          file=outputFile)
    print("Number open buy trade happened: " +
          str(tradeStats['NumberOfOpenBuy']),
          file=outputFile)

    try:
        averageOpenSellPrice = tradeStats['totalSellAmountShort'] / tradeStats[
            'NumberOfOpenSell']
        averageCloseBuyPrice = tradeStats['totalBuyAmountShort'] / tradeStats[
            'NumberOfCloseBuy']
    except:
        averageOpenSellPrice = 0
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellAmountLong'] / tradeStats[
            'NumberOfCloseSell']
        averageOpenBuyPrice = tradeStats['totalBuyAmountLong'] / tradeStats[
            'NumberOfOpenBuy']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0

    print("Average open sell price per unit is: " + str(averageOpenSellPrice),
          file=outputFile)
    print("Average close sell price per unit is: " +
          str(averageCloseSellPrice),
          file=outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice),
          file=outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice),
          file=outputFile)
    print("The current position Short: " +
          str(tradeStats['currentPositionShort']),
          file=outputFile)
    print("The current position Long: " +
          str(tradeStats['currentPositionLong']),
          file=outputFile)
    print("Profit or loss per Qty traded Short is: " +
          str(averageOpenSellPrice - averageCloseBuyPrice),
          file=outputFile)
    print("Profit or loss per Qty traded Long is: " +
          str(averageCloseSellPrice - averageOpenBuyPrice),
          file=outputFile)
    pLPerLotShort = (averageOpenSellPrice - averageCloseBuyPrice) * 1000
    pLPerLotLong = (averageCloseSellPrice - averageOpenBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " +
          str(pLPerLotShort),
          file=outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong),
          file=outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10),
          file=outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10),
          file=outputFile)
Esempio n. 7
0
File: tradeE5.py Progetto: grmte/ml
def main():
    attribute.initList()
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    enterTradeShort = 0
    enterTradeLong = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    askQ0AtTimeOfPreviousDataRow = 0
    bidQ0AtTimeOfPreviousDataRow = 0
    tradeStats = dict()
    tradeStats['totalSellValueShort'] = 0
    tradeStats['totalBuyValueShort'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['totalSellValueLong'] = 0
    tradeStats['totalBuyValueLong'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentPredictedValueShort = 0
    currentPredictedValueLong = 0
    entryCL = float(args.entryCL) / 100
    exitCL = float(args.exitCL) / 100
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    numberOfTimesAskedToEnterTradeShort = 0
    numberOfTimesAskedToEnterTradeLong = 0
    numberOfTimesAskedToExitTradeShort = 0
    numberOfTimesAskedToExitTradeLong = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
    reasonForTrade['AssumingBuyTradeHappenedShort'] = 0
    reasonForTrade['AssumingBuyTradeHappenedLong'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
    reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
    reasonForTrade['AssumingSellTradeHappenedShort'] = 0
    reasonForTrade['AssumingSellTradeHappenedLong'] = 0
    currentIndex = 0
    print("Processing the data file for trades :")
    attribute.initList()
    for currentDataRow in dataFile.matrix:

        lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(
            currentDataRow, ttqAtTimeOfPreviousDataRow,
            askP0AtTimeOfPreviousDataRow, bidP0AtTimeOfPreviousDataRow,
            askQ0AtTimeOfPreviousDataRow, bidQ0AtTimeOfPreviousDataRow,
            enterTradeShort, enterTradeLong, tradeStats, reasonForTrade)

        lReasonForTradingOrNotTradingShort = lReturnList[0]
        lReasonForTradingOrNotTradingLong = lReturnList[1]
        lDummyBidQ0 = lReturnList[2]
        lDummyAskQ0 = lReturnList[3]
        lDummyTTQForBuy = lReturnList[4]
        lDummyTTQForSell = lReturnList[5]
        if currentIndex > 0:
            attribute.aList[currentIndex - 1][0] = currentTimeStamp
            attribute.aList[currentIndex -
                            1][1] = tradeStats['currentPositionLong']
            attribute.aList[currentIndex -
                            1][2] = tradeStats['currentPositionShort']
            listOfStringsToPrint = [
                str(bidQ0AtTimeOfPreviousDataRow),
                str(bidP0AtTimeOfPreviousDataRow),
                str(askP0AtTimeOfPreviousDataRow),
                str(askQ0AtTimeOfPreviousDataRow),
                str(ttqAtTimeOfPreviousDataRow),
                str(ltpAtTimeOfPreviousDataRow),
                str(currentPredictedValueShort),
                str(enterTradeShort), lReasonForTradingOrNotTradingShort,
                str(currentPredictedValueLong),
                str(enterTradeLong), lReasonForTradingOrNotTradingLong,
                str(reasonForTrade['AssumingBuyTradeHappenedShort']),
                str(reasonForTrade['AssumingBuyTradeHappenedLong']),
                str(reasonForTrade['AssumingSellTradeHappenedShort']),
                str(reasonForTrade['AssumingSellTradeHappenedLong']),
                str(lDummyBidQ0),
                str(lDummyAskQ0),
                str(lDummyTTQForBuy),
                str(lDummyTTQForSell)
            ]
            attribute.aList[currentIndex -
                            1][3] = ";".join(listOfStringsToPrint)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(
            currentDataRow[colNumberOfData.TimeStamp])

        try:
            currentPredictedValueShort = (
                float(predictedValuesDict[currentTimeStamp][-2]) +
                float(predictedValuesDict[currentTimeStamp][-1]))
            currentPredictedValueLong = (
                float(predictedValuesDict[currentTimeStamp][2]) +
                float(predictedValuesDict[currentTimeStamp][1]))
        except:
            noPredictionForThisRow += 1

        #short decisions
        if (currentPredictedValueShort > entryCL):
            enterTradeShort = 1
            numberOfTimesAskedToEnterTradeShort += 1
        elif (currentPredictedValueShort < exitCL
              and tradeStats['currentPositionShort'] > 0):
            numberOfTimesAskedToExitTradeShort += 1
            enterTradeShort = -1  # Implies to exit the trade
        else:
            enterTradeShort = 0  # Implies make no change

#       if enterTradeShort == 1:
#           if currentPredictedValue <= entryCLCutoff:
#               enterTrade = 0
#       if enterTrade == -1:
#           if currentPredictedValue >= exitCLCutoff:
#               enterTrade = 0

#long decisions
        if (currentPredictedValueLong > entryCL):
            enterTradeLong = 1
            numberOfTimesAskedToEnterTradeLong += 1
        elif (currentPredictedValueLong < exitCL
              and tradeStats['currentPositionLong'] > 0):
            numberOfTimesAskedToExitTradeLong += 1
            enterTradeLong = -1  # Implies to exit the trade
        else:
            enterTradeLong = 0  # Implies make no change

        ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ])
        askP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskP0])
        bidP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidP0])
        askQ0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskQ0])
        bidQ0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidQ0])
        ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
        currentIndex = currentIndex + 1


# Squaring off if some open position there
    if tradeStats['currentPositionLong'] > 0:
        reasonForTrade['AssumingSellTradeHappenedLong'] += tradeStats[
            'currentPositionLong']
        tradeStats['totalSellValueLong'] += tradeStats[
            'currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionLong'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    elif tradeStats['currentPositionShort'] > 0:
        reasonForTrade['AssumingBuyTradeHappenedShort'] += tradeStats[
            'currentPositionShort']
        tradeStats['totalBuyValueShort'] += tradeStats[
            'currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionShort'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'

    attribute.aList[currentIndex - 1][0] = currentTimeStamp
    attribute.aList[currentIndex - 1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex - 1][2] = tradeStats['currentPositionShort']
    listOfStringsToPrint = [
        str(bidQ0AtTimeOfPreviousDataRow),
        str(bidP0AtTimeOfPreviousDataRow),
        str(askP0AtTimeOfPreviousDataRow),
        str(askQ0AtTimeOfPreviousDataRow),
        str(ttqAtTimeOfPreviousDataRow),
        str(ltpAtTimeOfPreviousDataRow),
        str(currentPredictedValueShort),
        str(enterTradeShort), "",
        str(currentPredictedValueLong),
        str(enterTradeLong), "",
        str(reasonForTrade['AssumingBuyTradeHappenedShort']),
        str(reasonForTrade['AssumingBuyTradeHappenedLong']),
        str(reasonForTrade['AssumingSellTradeHappenedShort']),
        str(reasonForTrade['AssumingSellTradeHappenedLong']),
        str(lDummyBidQ0),
        str(lDummyAskQ0),
        str(lDummyTTQForBuy),
        str(lDummyTTQForSell)
    ]
    attribute.aList[currentIndex - 1][3] = ";".join(listOfStringsToPrint)
    dirName = args.pd.replace('/ro/', '/rs/')
    tradeLogMainDirName = dirName + "/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName = tradeLogMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
    fileName = tradeLogSubDirectoryName + experimentName + initialFileName + ".trade"
    lHeaderColumnNamesList = [
        'TimeStamp', 'CurrentPositionLong', 'CurrentPositionShort', 'BidQ0',
        'BidP0', 'AskP0', 'AskQ0', 'TTQ', 'LTP', 'CurPredValueShort',
        'EnterTradeShort', 'ReasonForTradingOrNotTradingShort',
        'CurPredValueLong', 'EnterTradeLong',
        'ReasonForTradingOrNotTradingLong', 'totalBuyTradeShort',
        'totalBuyLong', 'totalSellShort', 'totalSellLong', 'DummyBidQ0',
        'DummyAskQ0', 'DummyTTQChangeForSell', 'DummyTTQChangeForBuy'
    ]
    attribute.writeToFile(fileName, lHeaderColumnNamesList)

    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName + experimentName + initialFileName + ".result"
    outputFile = open(fileName, "w")

    #changed file write to modify it to Short Long version
    print("Starting to write: " + fileName)
    print("The net results for Short are: " +
          str(tradeStats['totalSellValueShort'] -
              tradeStats['totalBuyValueShort']),
          file=outputFile)
    print("The net results for Long are: " +
          str(tradeStats['totalSellValueLong'] -
              tradeStats['totalBuyValueLong']),
          file=outputFile)
    print("Number of rows for which there is no prediction: " +
          str(noPredictionForThisRow),
          file=outputFile)
    print("Number of times asked to enter trade Short: " +
          str(numberOfTimesAskedToEnterTradeShort),
          file=outputFile)
    print("Number of times asked to enter trade Long: " +
          str(numberOfTimesAskedToEnterTradeLong),
          file=outputFile)
    print("Number of times asked to exit trade Short: " +
          str(numberOfTimesAskedToExitTradeShort),
          file=outputFile)
    print("Number of times asked to exit trade Long: " +
          str(numberOfTimesAskedToExitTradeLong),
          file=outputFile)
    print(
        "Assumed close buy trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort']),
        file=outputFile)
    print(
        "Assumed open buy trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong']),
        file=outputFile)
    print(
        "Assumed close buy trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualBidP0Short']),
        file=outputFile)
    print(
        "Assumed open buy trade did not happen since bidP0 not same as LTP: " +
        str(reasonForTrade['LTPDoesNotEqualBidP0Long']),
        file=outputFile)
    print("Assumed close buy trade happened: " +
          str(reasonForTrade['AssumingBuyTradeHappenedShort']),
          file=outputFile)
    print("Assumed open buy trade happened: " +
          str(reasonForTrade['AssumingBuyTradeHappenedLong']),
          file=outputFile)
    print(
        "Assumed open sell trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']),
        file=outputFile)
    print(
        "Assumed close sell trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']),
        file=outputFile)
    print(
        "Assumed open sell trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualAskP0Short']),
        file=outputFile)
    print(
        "Assumed close sell trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualAskP0Long']),
        file=outputFile)
    print("Assumed open sell trade happened: " +
          str(reasonForTrade['AssumingSellTradeHappenedShort']),
          file=outputFile)
    print("Assumed close sell trade happened: " +
          str(reasonForTrade['AssumingSellTradeHappenedLong']),
          file=outputFile)
    print("The total open sell value is: " +
          str(tradeStats['totalSellValueShort']),
          file=outputFile)
    print("The total close sell value is: " +
          str(tradeStats['totalSellValueLong']),
          file=outputFile)
    print("The total close buy value is: " +
          str(tradeStats['totalBuyValueShort']),
          file=outputFile)
    print("The total open buy value is: " +
          str(tradeStats['totalBuyValueLong']),
          file=outputFile)

    try:
        averageOpenSellPrice = tradeStats[
            'totalSellValueShort'] / reasonForTrade[
                'AssumingSellTradeHappenedShort']
        averageCloseBuyPrice = tradeStats[
            'totalBuyValueShort'] / reasonForTrade[
                'AssumingBuyTradeHappenedShort']
    except:
        averageOpenSellPrice = 0
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats[
            'totalSellValueLong'] / reasonForTrade[
                'AssumingSellTradeHappenedLong']
        averageOpenBuyPrice = tradeStats['totalBuyValueLong'] / reasonForTrade[
            'AssumingBuyTradeHappenedLong']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0

    print("Average open sell price per unit is: " + str(averageOpenSellPrice),
          file=outputFile)
    print("Average close sell price per unit is: " +
          str(averageCloseSellPrice),
          file=outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice),
          file=outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice),
          file=outputFile)
    print("The current position Short: " +
          str(tradeStats['currentPositionShort']),
          file=outputFile)
    print("The current position Long: " +
          str(tradeStats['currentPositionLong']),
          file=outputFile)
    print("Profit or loss per Qty traded Short is: " +
          str(averageOpenSellPrice - averageCloseBuyPrice),
          file=outputFile)
    print("Profit or loss per Qty traded Long is: " +
          str(averageCloseSellPrice - averageOpenBuyPrice),
          file=outputFile)
    pLPerLotShort = (averageOpenSellPrice - averageCloseBuyPrice) * 1000
    pLPerLotLong = (averageCloseSellPrice - averageOpenBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " +
          str(pLPerLotShort),
          file=outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong),
          file=outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10),
          file=outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10),
          file=outputFile)
Esempio n. 8
0
File: tradeE5.py Progetto: grmte/ml
def main():
   attribute.initList()
   dataFile.getDataIntoMatrix(args.pd)
   predictedValuesDict = dict()
   getPredictedValuesIntoDict(predictedValuesDict)
   enterTradeShort = 0
   enterTradeLong = 0
   ttqAtTimeOfPreviousDataRow = 0
   askP0AtTimeOfPreviousDataRow = 0
   bidP0AtTimeOfPreviousDataRow = 0
   askQ0AtTimeOfPreviousDataRow = 0
   bidQ0AtTimeOfPreviousDataRow = 0
   tradeStats = dict()
   tradeStats['totalSellValueShort'] = 0
   tradeStats['totalBuyValueShort'] = 0
   tradeStats['currentPositionShort'] = 0
   tradeStats['totalSellValueLong'] = 0
   tradeStats['totalBuyValueLong'] = 0
   tradeStats['currentPositionLong'] = 0
   noPredictionForThisRow = 0
   currentPredictedValueShort = 0
   currentPredictedValueLong = 0
   entryCL = float(args.entryCL)/100
   exitCL = float(args.exitCL)/100
 #  entryCLCutoff = float(args.entryCLCutoff)
 #  exitCLCutoff = float(args.exitCLCutoff)
   numberOfTimesAskedToEnterTradeShort = 0
   numberOfTimesAskedToEnterTradeLong = 0
   numberOfTimesAskedToExitTradeShort = 0
   numberOfTimesAskedToExitTradeLong = 0
   reasonForTrade = dict()
   reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
   reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
   reasonForTrade['AssumingBuyTradeHappenedShort'] = 0
   reasonForTrade['AssumingBuyTradeHappenedLong'] = 0
   reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
   reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
   reasonForTrade['AssumingSellTradeHappenedShort'] = 0
   reasonForTrade['AssumingSellTradeHappenedLong'] = 0
   currentIndex = 0
   print("Processing the data file for trades :")
   attribute.initList()
   for currentDataRow in dataFile.matrix:
       
       lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,ttqAtTimeOfPreviousDataRow,askP0AtTimeOfPreviousDataRow,bidP0AtTimeOfPreviousDataRow,askQ0AtTimeOfPreviousDataRow , bidQ0AtTimeOfPreviousDataRow , enterTradeShort,enterTradeLong,tradeStats,reasonForTrade )

       lReasonForTradingOrNotTradingShort = lReturnList[0]
       lReasonForTradingOrNotTradingLong = lReturnList[1] 
       lDummyBidQ0 = lReturnList[2]
       lDummyAskQ0 = lReturnList[3]
       lDummyTTQForBuy = lReturnList[4]
       lDummyTTQForSell = lReturnList[5]
       if currentIndex > 0:
           attribute.aList[currentIndex-1][0] = currentTimeStamp
           attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
           attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
           listOfStringsToPrint = [ str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , str(currentPredictedValueShort) , str(enterTradeShort) ,lReasonForTradingOrNotTradingShort , str(currentPredictedValueLong) , str(enterTradeLong) ,lReasonForTradingOrNotTradingLong , str(reasonForTrade['AssumingBuyTradeHappenedShort']),str(reasonForTrade['AssumingBuyTradeHappenedLong']),str(reasonForTrade['AssumingSellTradeHappenedShort']),str(reasonForTrade['AssumingSellTradeHappenedLong']),str(lDummyBidQ0),str(lDummyAskQ0),str(lDummyTTQForBuy),str(lDummyTTQForSell)]
           attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
       currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])

       try:
           currentPredictedValueShort = (float(predictedValuesDict[currentTimeStamp][-2]) + float(predictedValuesDict[currentTimeStamp][-1])) 
           currentPredictedValueLong = (float(predictedValuesDict[currentTimeStamp][2]) + float(predictedValuesDict[currentTimeStamp][1])) 
       except:
           noPredictionForThisRow += 1

       #short decisions
       if(currentPredictedValueShort > entryCL):
           enterTradeShort = 1
           numberOfTimesAskedToEnterTradeShort += 1
       elif(currentPredictedValueShort < exitCL and tradeStats['currentPositionShort'] > 0):
           numberOfTimesAskedToExitTradeShort += 1
           enterTradeShort = -1  # Implies to exit the trade
       else:
           enterTradeShort = 0  # Implies make no change
           
#       if enterTradeShort == 1:
#           if currentPredictedValue <= entryCLCutoff:
#               enterTrade = 0
#       if enterTrade == -1:
#           if currentPredictedValue >= exitCLCutoff:
#               enterTrade = 0
               
       #long decisions
       if(currentPredictedValueLong > entryCL):
           enterTradeLong = 1
           numberOfTimesAskedToEnterTradeLong += 1
       elif(currentPredictedValueLong < exitCL and tradeStats['currentPositionLong'] > 0):
           numberOfTimesAskedToExitTradeLong += 1
           enterTradeLong = -1  # Implies to exit the trade
       else:
           enterTradeLong = 0  # Implies make no change
       
       ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ]) 
       askP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskP0])
       bidP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidP0])
       askQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskQ0])
       bidQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidQ0])
       ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
       currentIndex = currentIndex + 1

# Squaring off if some open position there   
   if tradeStats['currentPositionLong'] > 0:
       reasonForTrade['AssumingSellTradeHappenedLong'] += tradeStats['currentPositionLong']
       tradeStats['totalSellValueLong'] += tradeStats['currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
       tradeStats['currentPositionLong'] = 0
       lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
   elif tradeStats['currentPositionShort'] > 0:
       reasonForTrade['AssumingBuyTradeHappenedShort'] += tradeStats['currentPositionShort']
       tradeStats['totalBuyValueShort'] += tradeStats['currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
       tradeStats['currentPositionShort'] = 0
       lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'

   attribute.aList[currentIndex-1][0] = currentTimeStamp
   attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
   attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
   listOfStringsToPrint = [ str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , str(currentPredictedValueShort) , str(enterTradeShort) , "" , str(currentPredictedValueLong) , str(enterTradeLong) ,"" , str(reasonForTrade['AssumingBuyTradeHappenedShort']),str(reasonForTrade['AssumingBuyTradeHappenedLong']),str(reasonForTrade['AssumingSellTradeHappenedShort']),str(reasonForTrade['AssumingSellTradeHappenedLong']),str(lDummyBidQ0),str(lDummyAskQ0),str(lDummyTTQForBuy),str(lDummyTTQForSell)]
   attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
   dirName = args.pd.replace('/ro/','/rs/')
   tradeLogMainDirName = dirName+"/t/"
   if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
   tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
   if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
   fileName = tradeLogSubDirectoryName+experimentName+initialFileName+".trade" 
   lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP','CurPredValueShort','EnterTradeShort','ReasonForTradingOrNotTradingShort','CurPredValueLong','EnterTradeLong','ReasonForTradingOrNotTradingLong','totalBuyTradeShort','totalBuyLong','totalSellShort','totalSellLong','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy']
   attribute.writeToFile(fileName , lHeaderColumnNamesList)

   tradeResultMainDirName = dirName+"/r/"
   if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
   tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
   if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
   fileName = tradeResultSubDirectoryName+experimentName+initialFileName+".result" 
   outputFile = open(fileName,"w")
 
   #changed file write to modify it to Short Long version
   print("Starting to write: "+fileName)
   print("The net results for Short are: " + str(tradeStats['totalSellValueShort'] - tradeStats['totalBuyValueShort']), file = outputFile)
   print("The net results for Long are: " + str(tradeStats['totalSellValueLong'] - tradeStats['totalBuyValueLong']), file = outputFile)
   print("Number of rows for which there is no prediction: " + str(noPredictionForThisRow), file = outputFile)    
   print("Number of times asked to enter trade Short: " + str(numberOfTimesAskedToEnterTradeShort), file = outputFile)    
   print("Number of times asked to enter trade Long: " + str(numberOfTimesAskedToEnterTradeLong), file = outputFile)    
   print("Number of times asked to exit trade Short: " + str(numberOfTimesAskedToExitTradeShort), file = outputFile)
   print("Number of times asked to exit trade Long: " + str(numberOfTimesAskedToExitTradeLong), file = outputFile)
   print("Assumed close buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort']), file = outputFile)
   print("Assumed open buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong']), file = outputFile)
   print("Assumed close buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0Short']), file = outputFile)
   print("Assumed open buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0Long']), file = outputFile)
   print("Assumed close buy trade happened: " + str(reasonForTrade['AssumingBuyTradeHappenedShort']), file = outputFile)
   print("Assumed open buy trade happened: " + str(reasonForTrade['AssumingBuyTradeHappenedLong']), file = outputFile)
   print("Assumed open sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']), file = outputFile)
   print("Assumed close sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']), file = outputFile)
   print("Assumed open sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Short']), file = outputFile)
   print("Assumed close sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Long']), file = outputFile)
   print("Assumed open sell trade happened: " + str(reasonForTrade['AssumingSellTradeHappenedShort']), file = outputFile)
   print("Assumed close sell trade happened: " + str(reasonForTrade['AssumingSellTradeHappenedLong']), file = outputFile)
   print("The total open sell value is: " + str(tradeStats['totalSellValueShort']), file = outputFile)
   print("The total close sell value is: " + str(tradeStats['totalSellValueLong']), file = outputFile)
   print("The total close buy value is: " + str(tradeStats['totalBuyValueShort']), file = outputFile)
   print("The total open buy value is: " + str(tradeStats['totalBuyValueLong']), file = outputFile)

   try:
       averageOpenSellPrice = tradeStats['totalSellValueShort']/reasonForTrade['AssumingSellTradeHappenedShort']
       averageCloseBuyPrice = tradeStats['totalBuyValueShort']/reasonForTrade['AssumingBuyTradeHappenedShort']
   except:
       averageOpenSellPrice = 0 
       averageCloseBuyPrice = 0
   try:
       averageCloseSellPrice = tradeStats['totalSellValueLong']/reasonForTrade['AssumingSellTradeHappenedLong']
       averageOpenBuyPrice = tradeStats['totalBuyValueLong']/reasonForTrade['AssumingBuyTradeHappenedLong']
   except:
       averageCloseSellPrice = 0
       averageOpenBuyPrice = 0 

   print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
   print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
   print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
   print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
   print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
   print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
   print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
   print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
   pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
   pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
   print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
   print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
   print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
   print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)
Esempio n. 9
0
File: tradeE13.py Progetto: grmte/ml
def readOnceAndWrite(pFileName, entryCL , exitCL , predictedValuesDict):
    global g_bestqty_list_for_sell, g_bestqty_list_for_buy 
    global transactionCost , currencyDivisor
    attribute.initList()
    tradeStats = dict()
    tradeStats['totalSellAmountShort'] = 0
    tradeStats['totalBuyAmountShort'] = 0
    tradeStats['totalSellAmountLong'] = 0
    tradeStats['totalBuyAmountLong'] = 0
    tradeStats['NumberOfOpenBuy'] = 0
    tradeStats['NumberOfCloseSell'] = 0
    tradeStats['NumberOfOpenSell'] = 0
    tradeStats['NumberOfCloseBuy'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentSellPredictedValue = 0
    currentBuyPredictedValue = 0
    currentIndex = 0
    l_previous_obj = None
    l_obj= None
    print("Processing the data file for trades :")
    attribute.initList()
    print("EntryLevels",entryCL , exitCL)
    for currentDataRow in dataFile.matrix:
        
        l_obj = update_obj_list(currentDataRow)
        if(l_previous_obj != None):
            lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful( l_obj , l_previous_obj , tradeStats )
            
            lDummyBidQ0 = lReturnList[0]
            lDummyAskQ0 = lReturnList[1]
            lDummyTTQForBuy = lReturnList[2]
            lDummyTTQForSell = lReturnList[3]
            lBuyTradedPrice = lReturnList[4]
            lBuyTradedQty = lReturnList[5]
            lSellTradedPrice = lReturnList[6]
            lSellTradedQty = lReturnList[7]
            if currentIndex > 0:
                if(g_bestqty_list_for_buy != {}):
                    l_best_bidq = g_bestqty_list_for_buy['qty']
                    l_best_bidp = g_bestqty_list_for_buy['price']
                else:
                    l_best_bidq = 0
                    l_best_bidp = 0
                if(g_bestqty_list_for_sell != {}):
                    l_best_askq = g_bestqty_list_for_sell['qty']
                    l_best_askp = g_bestqty_list_for_sell['price'] 
                else:
                    l_best_askq = 0
                    l_best_askp = 0
                attribute.aList[currentIndex-1][0] = l_obj.currentTimeStamp
                attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
                attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
                listOfStringsToPrint = [ str(l_previous_obj.BidQ[0]) , str(l_previous_obj.BidP[0]),str(l_previous_obj.BidQ[1]) , str(l_previous_obj.BidP[1]),str(l_previous_obj.BidQ[2]) , str(l_previous_obj.BidP[2]),str(l_previous_obj.BidQ[3]) ,str(l_previous_obj.BidP[3]),\
                                         str(l_previous_obj.BidP[4]),str(l_previous_obj.BidQ[4]) , str(l_previous_obj.AskQ[0]) , str(l_previous_obj.AskP[0]) , str(l_previous_obj.AskQ[1]) , str(l_previous_obj.AskP[1]) ,str(l_previous_obj.AskQ[2]) , str(l_previous_obj.AskP[2]) ,\
                                         str(l_previous_obj.AskQ[3]) , str(l_previous_obj.AskP[3]) ,str(l_previous_obj.AskQ[4]) , str(l_previous_obj.AskP[4]) ,\
                                         str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                                        str(currentBuyPredictedValue) , str(currentSellPredictedValue) , str(l_previous_obj.OpenBuy) ,l_previous_obj.ReasonForTradingOrNotTradingOpenBuy ,str(l_previous_obj.CloseBuy) ,l_previous_obj.ReasonForTradingOrNotTradingCloseBuy , \
                                        str(l_previous_obj.OpenSell) ,l_previous_obj.ReasonForTradingOrNotTradingOpenSell ,str(l_previous_obj.CloseSell) ,l_previous_obj.ReasonForTradingOrNotTradingCloseSell  , \
                                        str(tradeStats['NumberOfOpenBuy']),\
                                        str(tradeStats['NumberOfCloseBuy']),str(tradeStats['NumberOfOpenSell']),\
                                        str(tradeStats['NumberOfCloseSell']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                        str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp),\
                                        str(l_best_askq) ,str(lBuyTradedPrice), str(lBuyTradedQty), str(lSellTradedPrice),str(lSellTradedQty)]
                attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
            currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])
            
            try:
                currentSellPredictedValue = float(predictedValuesDict[l_obj.currentTimeStamp]['sell']) 
                currentBuyPredictedValue  = float(predictedValuesDict[l_obj.currentTimeStamp]['buy'])
            except:
                noPredictionForThisRow += 1

            
            #Open Sell and Close Buy
            if(currentBuyPredictedValue >= exitCL and tradeStats['currentPositionShort'] > 0):
                g_bestqty_list_for_buy = {}
                l_obj.CloseBuy = -1       #For close by hitting
                

            if(currentSellPredictedValue >= entryCL and tradeStats['currentPositionLong'] == 0):
                g_bestqty_list_for_sell = {}
                l_obj.OpenSell = 1	#For open buy
                
            if(tradeStats['currentPositionShort'] > 0) and (l_obj.CloseBuy != -1) :
                l_obj.CloseBuy = -2
                
            
            
            
            #Open Buy and Close Sell

            if(currentSellPredictedValue >= exitCL and tradeStats['currentPositionLong'] > 0):
                g_bestqty_list_for_sell = {}
                l_obj.CloseSell = -1       #For close by hitting
                
            if(currentBuyPredictedValue >= entryCL and tradeStats['currentPositionShort'] == 0) :
                g_bestqty_list_for_buy = {}
                l_obj.OpenBuy = 1       #For close by hitting
                 
            if(tradeStats['currentPositionLong'] > 0) and (l_obj.CloseSell != -1)  :
                l_obj.CloseSell = -2              
                
        
        l_previous_obj = l_obj
        currentIndex = currentIndex + 1

# Squaring off if some open position there   
    if tradeStats['currentPositionLong'] > 0:
        tradeStats['NumberOfCloseSell'] += tradeStats['currentPositionLong']
        tradeStats['totalSellAmountLong'] += tradeStats['currentPositionLong'] * (l_previous_obj.BidP[0])
        tradeStats['currentPositionLong'] = 0
        l_obj.ReasonForTradingOrNotTradingCloseSell = 'CloseSell(Hitting)'
    if tradeStats['currentPositionShort'] > 0:
        tradeStats['NumberOfCloseBuy'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyAmountShort'] += tradeStats['currentPositionShort'] * (l_previous_obj.AskP[0])
        tradeStats['currentPositionShort'] = 0
        l_obj.ReasonForTradingOrNotTradingCloseBuy = 'CloseBuy(Hitting)'
    
    attribute.aList[currentIndex-1][0] = currentTimeStamp
    attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
    if(g_bestqty_list_for_buy != {}):
        l_best_bidq = g_bestqty_list_for_buy['qty']
        l_best_bidp = g_bestqty_list_for_buy['price'] 
    else:
        l_best_bidq = 0
        l_best_bidp = 0
    if(g_bestqty_list_for_sell != {}):
        l_best_askq = g_bestqty_list_for_sell['qty']
        l_best_askp = g_bestqty_list_for_sell['price'] 
    else:
        l_best_askq = 0
        l_best_askp = 0
    listOfStringsToPrint = [  str(l_previous_obj.BidQ[0]) , str(l_previous_obj.BidP[0]),str(l_previous_obj.BidQ[1]) , str(l_previous_obj.BidP[1]),str(l_previous_obj.BidQ[2]) , str(l_previous_obj.BidP[2]),str(l_previous_obj.BidQ[3]) ,str(l_previous_obj.BidP[3]),\
                                        str(l_previous_obj.BidP[4]),str(l_previous_obj.BidQ[4]) , str(l_previous_obj.AskQ[0]) , str(l_previous_obj.AskP[0]) , str(l_previous_obj.AskQ[1]) , str(l_previous_obj.AskP[1]) ,str(l_previous_obj.AskQ[2]) , str(l_previous_obj.AskP[2]) ,\
                                        str(l_previous_obj.AskQ[3]) , str(l_previous_obj.AskP[3]) ,str(l_previous_obj.AskQ[4]) , str(l_previous_obj.AskP[4]) ,\
                                        str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                                        str(currentBuyPredictedValue) , str(currentSellPredictedValue) , str(l_previous_obj.OpenBuy) ,l_previous_obj.ReasonForTradingOrNotTradingOpenBuy ,str(l_previous_obj.CloseBuy) ,l_previous_obj.ReasonForTradingOrNotTradingCloseBuy , \
                                        str(l_previous_obj.OpenSell) ,l_previous_obj.ReasonForTradingOrNotTradingOpenSell ,str(l_previous_obj.CloseSell) ,l_previous_obj.ReasonForTradingOrNotTradingCloseSell  , str(tradeStats['NumberOfCloseBuy']),\
                                       str(tradeStats['NumberOfOpenBuy']),\
                                        str(tradeStats['NumberOfCloseBuy']),str(tradeStats['NumberOfOpenSell']),\
                                        str(tradeStats['NumberOfCloseSell']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                        str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp), str(l_best_askq) , "0;0;0;0"]
    attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
    
    dirName = args.pd.replace('/ro/','/rs/')
    tradeLogMainDirName = dirName+"/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
    
    fileName = tradeLogSubDirectoryName + pFileName + ".trade" 
    lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0;BidP0;BidQ1;BidP1;BidQ2;BidP2;BidQ3;BidP3;BidQ4;BidP4','AskQ0;AskP0;AskQ1;AskP1;AskQ2;AskP2;AskQ3;AskP3;AskQ4;AskP4','TTQ','LTP','CurBuyPredValue','CurrentSellPredValue',\
                               'EnterTradeOpenBuy','ReasonForTradingOrNotTradingOpenBuy','EnterTradeCloseBuy','ReasonForTradingOrNotTradingCloseBuy','EnterTradeOpenSell','ReasonForTradingOrNotTradingOpenSell','EnterTradeCloseSell','ReasonForTradingOrNotTradingCloseSell',\
                               'NumberOfOpenBuy','NumOfCloseBuy','NumberOfOpenSell','NumberOfCloseSell','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy' \
                               ,'BestBidQ','BestBidP','BestAskP','BestAskQ','BuyTradedPrcie','BuyTradedQty','SellTradedPrice','SellTradedQty']
    
#     attribute.writeToFile(fileName , lHeaderColumnNamesList)

    
    tradeResultMainDirName = dirName+"/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName+pFileName+".result" 
    outputFile = open(fileName,"w")
    gross_short_profit = tradeStats['totalSellAmountShort'] - tradeStats['totalBuyAmountShort']
    gross_long_profit = tradeStats['totalSellAmountLong'] - tradeStats['totalBuyAmountLong']
    gross_profit = gross_short_profit + gross_long_profit
    net_short_profit = gross_short_profit - ( transactionCost * ( tradeStats['totalSellAmountShort'] + tradeStats['totalBuyAmountShort'] ) ) 
    net_long_profit = gross_long_profit - ( transactionCost * (tradeStats['totalSellAmountLong'] + tradeStats['totalBuyAmountLong'] ) )
    net_profit = net_short_profit + net_long_profit
    
    gross_short_profit_in_dollars = gross_profit / (currencyDivisor * 60)
    net_profit_in_dollars = net_profit / (currencyDivisor * 60 )
    #changed file write to modify it to Short Long version
    print("Starting to write: "+pFileName)
    print("The gross results for Short are: %.6f" %gross_short_profit, file = outputFile)
    print("The gross results for Long are: %.6f" %gross_long_profit, file = outputFile)
    print("Number of rows for which there is no prediction: " + str(0), file = outputFile)    
    print("Number of times asked to enter trade Short: " + str(0), file = outputFile)    
    print("Number of times asked to enter trade Long: " + str(0), file = outputFile)    
    print("Number of times asked to exit trade Short: " + str(0), file = outputFile)
    print("Number of times asked to exit trade Long: " + str(0), file = outputFile)
    print("The net results for Short are: %.6f" %net_short_profit, file = outputFile)
    print("The net results for Long are: %.6f" %net_long_profit, file = outputFile)
    print("Gross Results in Dollars: %.6f" %gross_short_profit_in_dollars, file = outputFile)
    print("Net Results in Dollars: %.6f" %net_profit_in_dollars, file = outputFile)
    print("Number of times Close buy trade happened: " + str(tradeStats['NumberOfCloseBuy']), file = outputFile)
    print("Number of times open buy trade happened: " + str(tradeStats['NumberOfOpenBuy']), file = outputFile)
    print("Assumed open sell trade did not happen since volume did not increase: " + str(0), file = outputFile)
    print("Assumed close sell trade did not happen since volume did not increase: " + str(0), file = outputFile)
    print("Assumed open sell trade did not happen since bidP0 not same as LTP: " + str(0), file = outputFile)
    print("Assumed close sell trade did not happen since bidP0 not same as LTP: " + str(0), file = outputFile)
    print("Number of Open sell trade happened: " + str(tradeStats['NumberOfOpenSell']), file = outputFile)
    print("Number of Close sell trade happened: " + str(tradeStats['NumberOfCloseSell']), file = outputFile)
    print("The total open sell value is: " + str(tradeStats['totalSellAmountShort']), file = outputFile)
    print("The total close sell value is: " + str(tradeStats['totalSellAmountLong']), file = outputFile)
    print("The total close buy value is: " + str(tradeStats['totalBuyAmountShort']), file = outputFile)
    print("The total open buy value is: " + str(tradeStats['totalBuyAmountLong']), file = outputFile)

    try:
        averageOpenSellPrice = tradeStats['totalSellAmountShort']/tradeStats['NumberOfOpenSell'] 
        averageCloseBuyPrice = tradeStats['totalBuyAmountShort']/tradeStats['NumberOfCloseBuy'] 
    except:
        averageOpenSellPrice = 0 
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellAmountLong']/tradeStats['NumberOfCloseSell'] 
        averageOpenBuyPrice = tradeStats['totalBuyAmountLong']/tradeStats['NumberOfOpenBuy'] 
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0 
    
    print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
    print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
    print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
    print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
    print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
    print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
    pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
    pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)
Esempio n. 10
0
File: tradeE8.py Progetto: grmte/ml
def readOnceAndWrite(pFileName, pIndexOfEntryOrExitCL, predictedValuesDict):
    global g_bestqty_list_for_sell, g_bestqty_list_for_buy
    attribute.initList()
    tradeStats = dict()
    tradeStats['totalSellAmountShort'] = 0
    tradeStats['totalBuyAmountShort'] = 0
    tradeStats['totalSellAmountLong'] = 0
    tradeStats['totalBuyAmountLong'] = 0
    tradeStats['NumberOfOpenBuy'] = 0
    tradeStats['NumberOfCloseSell'] = 0
    tradeStats['NumberOfOpenSell'] = 0
    tradeStats['NumberOfCloseBuy'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentSellPredictedValue = 0
    currentBuyPredictedValue = 0
    entryCL = float(totalEntryCL[pIndexOfEntryOrExitCL]) / 100
    exitCL = float(totalExitCL[pIndexOfEntryOrExitCL]) / 100
    entryCL1 = float(totalEntryCL1[pIndexOfEntryOrExitCL]) / 100
    entryCL2 = float(totalEntryCL2[pIndexOfEntryOrExitCL]) / 100
    print(entryCL, exitCL, entryCL1, entryCL2)
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    currentIndex = 0
    l_previous_obj = None
    l_obj = None
    print("Processing the data file for trades :")
    attribute.initList()
    for currentDataRow in dataFile.matrix:

        l_obj = update_obj_list(currentDataRow)
        lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(
            l_obj, l_previous_obj, tradeStats)

        lDummyBidQ0 = lReturnList[2]
        lDummyAskQ0 = lReturnList[3]
        lDummyTTQForBuy = lReturnList[4]
        lDummyTTQForSell = lReturnList[5]
        if currentIndex > 0:
            attribute.aList[currentIndex - 1][0] = l_obj.currentTimeStamp
            attribute.aList[currentIndex -
                            1][1] = tradeStats['currentPositionLong']
            attribute.aList[currentIndex -
                            1][2] = tradeStats['currentPositionShort']
            listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP0) , \
                                    str(l_previous_obj.AskQ0) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                                    str(currentSellPredictedValue) , str(l_previous_obj.enterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                                    str(l_previous_obj.enterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                                    str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                                    str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                    str(lDummyTTQForBuy),str(lDummyTTQForSell)]
            attribute.aList[currentIndex -
                            1][3] = ";".join(listOfStringsToPrint)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(
            currentDataRow[colNumberOfData.TimeStamp])

        try:
            currentSellPredictedValue = float(
                predictedValuesDict[l_obj.currentTimeStamp]['sell'])
            currentBuyPredictedValue = float(
                predictedValuesDict[l_obj.currentTimeStamp]['buy'])
        except:
            noPredictionForThisRow += 1

        #short decisions
        if (currentSellPredictedValue >= entryCL):
            l_obj.standingAtAsk = 0
            l_obj.enterTradeShort = 1
        elif (currentSellPredictedValue >= entryCL1):
            if (l_previous_obj.standingAtAsk == 0):
                g_bestqty_list_for_sell = {}
            l_obj.standingAtAsk = 1
            l_obj.enterTradeShort = 1
        elif (l_previous_obj.standingAtAsk == 1
              and currentSellPredictedValue >= entryCL2):
            l_obj.standingAtAsk = 1
            l_obj.enterTradeShort = 1
        else:
            l_obj.standingAtAsk = 0
            l_obj.enterTradeShort = 0  # Implies make no change
        if ((currentBuyPredictedValue >= exitCL)
                and tradeStats['currentPositionShort'] > 0):
            l_obj.enterTradeShort = -1  # Implies to exit the trade
        else:
            l_obj.enterTradeShort = 0  # Implies make no change

        #       if enterTradeShort == 1:
        #           if currentPredictedValue <= entryCLCutoff:
        #               enterTrade = 0
        #       if enterTrade == -1:
        #           if currentPredictedValue >= exitCLCutoff:
        #               enterTrade = 0

        #long decisions
        if (l_obj.currentBuyPredictedValue >= entryCL):
            l_obj.standingAtBid = 0
            l_obj.enterTradeLong = 1
        elif (currentBuyPredictedValue >= entryCL1):
            if (l_previous_obj.standingAtBid == 0):
                g_bestqty_list_for_buy = {}
            l_obj.standingAtBid = 1
            l_obj.enterTradeLong = 1
        elif (l_previous_obj.standingAtBid == 1
              and currentBuyPredictedValue >= entryCL2):
            l_obj.standingAtBid = 1
            l_obj.enterTradeLong = 1
        else:
            l_obj.standingAtBid = 0
            l_obj.enterTradeLong = 0  # Implies make no change

        if ((currentSellPredictedValue >= exitCL)
                and tradeStats['currentPositionLong'] > 0):
            l_obj.enterTradeLong = -1  # Implies to exit the trade
        else:
            l_obj.enterTradeLong = 0  # Implies make no change

        l_previous_obj = l_obj
        currentIndex = currentIndex + 1


# Squaring off if some open position there
    if tradeStats['currentPositionLong'] > 0:
        tradeStats['NumberOfCloseSell'] += tradeStats['currentPositionLong']
        tradeStats['totalSellAmountLong'] += tradeStats[
            'currentPositionLong'] * (l_previous_obj.BidP)
        tradeStats['currentPositionLong'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    if tradeStats['currentPositionShort'] > 0:
        tradeStats['NumberOfCloseBuy'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyAmountShort'] += tradeStats[
            'currentPositionShort'] * (l_previous_obj.AskP)
        tradeStats['currentPositionShort'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'

    attribute.aList[currentIndex - 1][0] = currentTimeStamp
    attribute.aList[currentIndex - 1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex - 1][2] = tradeStats['currentPositionShort']
    listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP0) , \
                            str(l_previous_obj.AskQ0) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                            str(currentSellPredictedValue) , str(l_previous_obj.enterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                            str(l_previous_obj.enterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                            str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                            str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                            str(lDummyTTQForBuy),str(lDummyTTQForSell)]
    attribute.aList[currentIndex - 1][3] = ";".join(listOfStringsToPrint)

    dirName = args.pd.replace('/ro/', '/rs/')
    tradeLogMainDirName = dirName + "/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName = tradeLogMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)

    fileName = tradeLogSubDirectoryName + pFileName + ".trade"
    lHeaderColumnNamesList = [
        'TimeStamp', 'CurrentPositionLong', 'CurrentPositionShort', 'BidQ0',
        'BidP0', 'AskP0', 'AskQ0', 'TTQ', 'LTP', 'CurPredValueShort',
        'EnterTradeShort', 'ReasonForTradingOrNotTradingShort',
        'CurPredValueLong', 'EnterTradeLong',
        'ReasonForTradingOrNotTradingLong', 'totalBuyTradeShort',
        'totalBuyLong', 'totalSellShort', 'totalSellLong', 'DummyBidQ0',
        'DummyAskQ0', 'DummyTTQChangeForSell', 'DummyTTQChangeForBuy'
    ]
    attribute.writeToFile(fileName, lHeaderColumnNamesList)

    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName + pFileName + ".result"
    outputFile = open(fileName, "w")

    #changed file write to modify it to Short Long version
    print("Starting to write: " + fileName)
    print("The gross profit for Short are: " +
          str(tradeStats['totalSellAmountShort'] -
              tradeStats['totalBuyAmountShort']),
          file=outputFile)
    print("The gross profit for Long are: " +
          str(tradeStats['totalSellAmountLong'] -
              tradeStats['totalBuyAmountLong']),
          file=outputFile)
    print("The total open sell amount is: " +
          str(tradeStats['totalSellAmountShort']),
          file=outputFile)
    print("The total close sell amount is: " +
          str(tradeStats['totalSellAmountLong']),
          file=outputFile)
    print("The total close buy amount is: " +
          str(tradeStats['totalBuyAmountShort']),
          file=outputFile)
    print("The total open buy amount is: " +
          str(tradeStats['totalBuyAmountLong']),
          file=outputFile)
    print("Number open sell trade happened: " +
          str(tradeStats['NumberOfOpenSell']),
          file=outputFile)
    print("Number close sell trade happened: " +
          str(tradeStats['NumberOfCloseSell']),
          file=outputFile)
    print("Number close buy trade happened: " +
          str(tradeStats['NumberOfCloseBuy']),
          file=outputFile)
    print("Number open buy trade happened: " +
          str(tradeStats['NumberOfOpenBuy']),
          file=outputFile)

    try:
        averageOpenSellPrice = tradeStats['totalSellAmountShort'] / tradeStats[
            'NumberOfOpenSell']
        averageCloseBuyPrice = tradeStats['totalBuyAmountShort'] / tradeStats[
            'NumberOfCloseBuy']
    except:
        averageOpenSellPrice = 0
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellAmountLong'] / tradeStats[
            'NumberOfCloseSell']
        averageOpenBuyPrice = tradeStats['totalBuyAmountLong'] / tradeStats[
            'NumberOfOpenBuy']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0

    print("Average open sell price per unit is: " + str(averageOpenSellPrice),
          file=outputFile)
    print("Average close sell price per unit is: " +
          str(averageCloseSellPrice),
          file=outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice),
          file=outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice),
          file=outputFile)
    print("The current position Short: " +
          str(tradeStats['currentPositionShort']),
          file=outputFile)
    print("The current position Long: " +
          str(tradeStats['currentPositionLong']),
          file=outputFile)
    print("Profit or loss per Qty traded Short is: " +
          str(averageOpenSellPrice - averageCloseBuyPrice),
          file=outputFile)
    print("Profit or loss per Qty traded Long is: " +
          str(averageCloseSellPrice - averageOpenBuyPrice),
          file=outputFile)
    pLPerLotShort = (averageOpenSellPrice - averageCloseBuyPrice) * 1000
    pLPerLotLong = (averageCloseSellPrice - averageOpenBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " +
          str(pLPerLotShort),
          file=outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong),
          file=outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10),
          file=outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10),
          file=outputFile)
Esempio n. 11
0
File: tradeE10.py Progetto: grmte/ml
def readOnceAndWrite(pFileName, pEntryList, pExitList, predictedValuesDict):
    global g_bestqty_list_for_sell, g_bestqty_list_for_buy
    attribute.initList()
    tradeStats = dict()
    tradeStats['totalSellAmountShort'] = 0
    tradeStats['totalBuyAmountShort'] = 0
    tradeStats['totalSellAmountLong'] = 0
    tradeStats['totalBuyAmountLong'] = 0
    tradeStats['NumberOfOpenBuy'] = 0
    tradeStats['NumberOfCloseSell'] = 0
    tradeStats['NumberOfOpenSell'] = 0
    tradeStats['NumberOfCloseBuy'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentSellPredictedValue = 0
    currentBuyPredictedValue = 0
    entryCL = float(pEntryList[3])/100
    entryCl0 = float(pEntryList[2])/100
    entryCL1 = float(pEntryList[1])/100
    entryCL2 = float(pEntryList[0])/100
    exitCL = float(pExitList[3])/100
    exitCl0 = float(pExitList[2])/100
    exitCL1 = float(pExitList[1])/100
    exitCL2 = float(pExitList[0])/100   
    print (entryCL, exitCL ,entryCl0, entryCL1 , entryCL2 )
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    currentIndex = 0
    l_previous_obj = None
    l_obj= None
    print("Processing the data file for trades :")
    attribute.initList()
    for currentDataRow in dataFile.matrix:
        
        l_obj = update_obj_list(currentDataRow)
        if(l_previous_obj != None):
            lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful( l_obj , l_previous_obj , tradeStats )
            
            lDummyBidQ0 = lReturnList[0]
            lDummyAskQ0 = lReturnList[1]
            lDummyTTQForBuy = lReturnList[2]
            lDummyTTQForSell = lReturnList[3]
            if currentIndex > 0:
                if(g_bestqty_list_for_buy != {}):
                    l_best_bidq = g_bestqty_list_for_buy['qty']
                    l_best_bidp = g_bestqty_list_for_buy['price']
                else:
                    l_best_bidq = 0
                    l_best_bidp = 0
                if(g_bestqty_list_for_sell != {}):
                    l_best_askq = g_bestqty_list_for_sell['qty']
                    l_best_askp = g_bestqty_list_for_sell['price'] 
                else:
                    l_best_askq = 0
                    l_best_askp = 0
                attribute.aList[currentIndex-1][0] = l_obj.currentTimeStamp
                attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
                attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
                listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP) , \
                                        str(l_previous_obj.AskQ) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                                        str(currentSellPredictedValue) , str(l_previous_obj.EnterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                                        str(l_previous_obj.EnterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                                        str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                                        str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                                        str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp), str(l_best_askq) ]
                attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
            currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])
            
            try:
                currentSellPredictedValue = float(predictedValuesDict[l_obj.currentTimeStamp]['sell']) 
                currentBuyPredictedValue  = float(predictedValuesDict[l_obj.currentTimeStamp]['buy'])
            except:
                noPredictionForThisRow += 1
            
            #short decisions
            if(currentSellPredictedValue >= entryCL):
                g_bestqty_list_for_sell = {}
                l_obj.standingAtAsk = 0
                l_obj.EnterTradeShort = 1
                l_obj.standingAtAskMinus1pip = 0
            elif(currentSellPredictedValue >= entryCL0):
                g_bestqty_list_for_sell = {}
                l_obj.standingAtAsk = 0
                l_obj.standingAtAskMinus1pip = 1
                l_obj.EnterTradeShort = 1
            elif (currentSellPredictedValue >= entryCL1):
                l_obj.standingAtAskMinus1pip = 0
                if(l_previous_obj.standingAtAsk  == 0):
                    g_bestqty_list_for_sell = {}
                l_obj.standingAtAsk = 1
                l_obj.EnterTradeShort = 1
            elif (l_previous_obj.standingAtAsk == 1 and currentSellPredictedValue >= entryCL2):
                l_obj.standingAtAsk = 1
                l_obj.EnterTradeShort = 1
            #close Long positions
            elif((currentBuyPredictedValue >= exitCL)and tradeStats['currentPositionShort'] > 0):
                l_obj.EnterTradeShort = -1  # Implies to exit the trade
                g_bestqty_list_for_buy = {}
                l_obj.CloseStandingAtBid = 0
            elif((currentBuyPredictedValue >= exitCL0)and tradeStats['currentPositionShort'] > 0):
                l_obj.EnterTradeShort = -1  # Implies to exit the trade
                g_bestqty_list_for_buy = {}
                l_obj.CloseStandingAtBidPlus1pip = 1
                l_obj.CloseStandingAtBid = 0
            elif((currentBuyPredictedValue >= exitCL1)and tradeStats['currentPositionShort'] > 0):
                l_obj.EnterTradeShort = -1  # Implies to exit the trade
                if(l_previous_obj.CloseStandingAtBid  == 0):
                    g_bestqty_list_for_sell = {}
                g_bestqty_list_for_buy = {}
                l_obj.CloseStandingAtBidPlus1pip = 0
                l_obj.CloseStandingAtBid = 1
            elif(l_previous_obj.CloseStandingAtBid  == 1 and (currentBuyPredictedValue >= exitCL2)and tradeStats['currentPositionShort'] > 0):
                l_obj.EnterTradeShort = -1  # Implies to exit the trade
                l_obj.CloseStandingAtBidPlus1pip = 0
                l_obj.CloseStandingAtBid = 1                              
            else:
                g_bestqty_list_for_sell = {}
                l_obj.standingAtAsk = 0
                l_obj.standingAtAskMinus1pip = 0
                l_obj.CloseStandingAtBidPlus1pip = 0
                l_obj.CloseStandingAtBid = 0
                l_obj.EnterTradeShort = 0  # Implies make no change
                
            #       if EnterTradeShort == 1:
            #           if currentPredictedValue <= entryCLCutoff:
            #               enterTrade = 0
            #       if enterTrade == -1:
            #           if currentPredictedValue >= exitCLCutoff:
            #               enterTrade = 0
                    
            #long decisions
            if(currentBuyPredictedValue >= entryCL):
                g_bestqty_list_for_buy = {}
                l_obj.standingAtBid = 0
                l_obj.EnterTradeLong = 1
            elif(currentBuyPredictedValue >= entryCL0):
                g_bestqty_list_for_buy = {}
                l_obj.standingAtBid = 0
                l_obj.standingAtBidPlus1pip = 1
                l_obj.EnterTradeLong = 1
            elif (currentBuyPredictedValue >= entryCL1):
                if(l_previous_obj.standingAtBid  == 0):
                    g_bestqty_list_for_buy = {}
                l_obj.standingAtBid = 1
                l_obj.EnterTradeLong = 1
                l_obj.standingAtBidPlus1pip = 0
            elif (l_previous_obj.standingAtBid == 1 and currentBuyPredictedValue >= entryCL2):
                l_obj.standingAtBid = 1
                l_obj.EnterTradeLong = 1
            #Close Long positions
            elif((currentSellPredictedValue >= exitCL ) and tradeStats['currentPositionLong'] > 0):
                l_obj.EnterTradeLong = -1  # Implies to exit the trade
                l_obj.CloseStandingAtAsk = 0
                l_obj.CloseStandingAtAskMinus1pip = 0
            elif((currentSellPredictedValue >= exitCL0 ) and tradeStats['currentPositionLong'] > 0):
                l_obj.EnterTradeLong = -1  # Implies to exit the trade
                l_obj.CloseStandingAtAsk = 0
                l_obj.CloseStandingAtAskMinus1pip = 1
            elif((currentSellPredictedValue >= exitCL1 ) and tradeStats['currentPositionLong'] > 0):
                l_obj.EnterTradeLong = -1  # Implies to exit the trade
                if(l_previous_obj.CloseStandingAtAsk  == 0):
                    g_bestqty_list_for_sell = {}
                l_obj.CloseStandingAtAsk = 1
                l_obj.CloseStandingAtAskMinus1pip = 0
            elif(l_previous_obj.CloseStandingAtAsk == 1 and (currentSellPredictedValue >= exitCL2 ) and tradeStats['currentPositionLong'] > 0):
                l_obj.EnterTradeLong = -1  # Implies to exit the trade
                l_obj.CloseStandingAtAsk = 1
                l_obj.CloseStandingAtAskMinus1pip = 0
            else:
                g_bestqty_list_for_buy = {}
                l_obj.standingAtBid = 0
                l_obj.CloseStandingAtAsk = 0
                l_obj.standingAtBidPlus1pip = 0
                l_obj.CloseStandingAtAskMinus1pip = 0
                l_obj.EnterTradeLong = 0  # Implies make no change
            

        
        l_previous_obj = l_obj
        currentIndex = currentIndex + 1

# Squaring off if some open position there   
    if tradeStats['currentPositionLong'] > 0:
        tradeStats['NumberOfCloseSell'] += tradeStats['currentPositionLong']
        tradeStats['totalSellAmountLong'] += tradeStats['currentPositionLong'] * (l_previous_obj.BidP)
        tradeStats['currentPositionLong'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    if tradeStats['currentPositionShort'] > 0:
        tradeStats['NumberOfCloseBuy'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyAmountShort'] += tradeStats['currentPositionShort'] * (l_previous_obj.AskP)
        tradeStats['currentPositionShort'] = 0
        l_obj.ReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'
    
    attribute.aList[currentIndex-1][0] = currentTimeStamp
    attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
    if(g_bestqty_list_for_buy != {}):
        l_best_bidq = g_bestqty_list_for_buy['qty']
        l_best_bidp = g_bestqty_list_for_buy['price'] 
    else:
        l_best_bidq = 0
        l_best_bidp = 0
    if(g_bestqty_list_for_sell != {}):
        l_best_askq = g_bestqty_list_for_sell['qty']
        l_best_askp = g_bestqty_list_for_sell['price'] 
    else:
        l_best_askq = 0
        l_best_askp = 0
    listOfStringsToPrint = [ str(l_previous_obj.BidQ) , str(l_previous_obj.BidP) , str(l_previous_obj.AskP) , \
                            str(l_previous_obj.AskQ) , str(l_previous_obj.TTQ) , str(l_previous_obj.LTP) ,\
                            str(currentSellPredictedValue) , str(l_previous_obj.EnterTradeShort) ,l_previous_obj.ReasonForTradingOrNotTradingShort , str(currentBuyPredictedValue) ,\
                            str(l_previous_obj.EnterTradeLong) ,l_previous_obj.ReasonForTradingOrNotTradingLong , str(tradeStats['NumberOfCloseBuy']),\
                            str(tradeStats['NumberOfOpenBuy']),str(tradeStats['NumberOfOpenSell']),\
                            str(tradeStats['NumberOfCloseBuy']),str(lDummyBidQ0),str(lDummyAskQ0),\
                            str(lDummyTTQForBuy),str(lDummyTTQForSell),str(l_best_bidq),str(l_best_bidp),str(l_best_askp), str(l_best_askq) ]
    attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
    
    dirName = args.pd.replace('/ro/','/rs/')
    tradeLogMainDirName = dirName+"/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
    
    fileName = tradeLogSubDirectoryName + pFileName + ".trade" 
    lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP','CurPredValueShort','EnterTradeShort','ReasonForTradingOrNotTradingShort','CurPredValueLong','EnterTradeLong','ReasonForTradingOrNotTradingLong','totalBuyTradeShort','totalBuyLong','totalSellShort','totalSellLong','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy' ,'BestBidQ','BestBidP','BestAskP','BestAskQ']
    attribute.writeToFile(fileName , lHeaderColumnNamesList)
    
    tradeResultMainDirName = dirName+"/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName+pFileName+".result" 
    outputFile = open(fileName,"w")
    
    #changed file write to modify it to Short Long version
    print("Starting to write: "+fileName)
    print("The gross profit for Short are: " + str(tradeStats['totalSellAmountShort'] - tradeStats['totalBuyAmountShort']), file = outputFile)
    print("The gross profit for Long are: " + str(tradeStats['totalSellAmountLong'] - tradeStats['totalBuyAmountLong']), file = outputFile)
    print("The total open sell amount is: " + str(tradeStats['totalSellAmountShort']), file = outputFile)
    print("The total close sell amount is: " + str(tradeStats['totalSellAmountLong']), file = outputFile)
    print("The total close buy amount is: " + str(tradeStats['totalBuyAmountShort']), file = outputFile)
    print("The total open buy amount is: " + str(tradeStats['totalBuyAmountLong']), file = outputFile)
    print("Number open sell trade happened: " + str(tradeStats['NumberOfOpenSell']), file = outputFile)
    print("Number close sell trade happened: " + str(tradeStats['NumberOfCloseSell']), file = outputFile)
    print("Number close buy trade happened: " + str(tradeStats['NumberOfCloseBuy']), file = outputFile)
    print("Number open buy trade happened: " + str(tradeStats['NumberOfOpenBuy']), file = outputFile)
       
    try:
        averageOpenSellPrice = tradeStats['totalSellAmountShort']/tradeStats['NumberOfOpenSell']
        averageCloseBuyPrice = tradeStats['totalBuyAmountShort']/tradeStats['NumberOfCloseBuy']
    except:
        averageOpenSellPrice = 0 
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellAmountLong']/tradeStats['NumberOfCloseSell']
        averageOpenBuyPrice = tradeStats['totalBuyAmountLong']/tradeStats['NumberOfOpenBuy']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0 
    
    print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
    print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
    print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
    print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
    print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
    print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
    pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
    pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)
def readOnceAndWrite(pFileName, targetValuesDict):
    global gOpenBuyPrice , gCloseSellPrice , gOpenSellPrice , gCloseBuyPrice
    attribute.initList()
    enterTradeShort = 0
    enterTradeLong = 0
    ltpAtTimeOfPreviousDataRow = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    askQ0AtTimeOfPreviousDataRow = 0
    bidQ0AtTimeOfPreviousDataRow = 0
    exchangeTimeStamp = 0 
    currentTimeStamp = 0
    tradeStats = dict()
    tradeStats['totalSellValueShort'] = 0
    tradeStats['totalBuyValueShort'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['totalSellValueLong'] = 0
    tradeStats['totalBuyValueLong'] = 0
    tradeStats['currentPositionLong'] = 0
    noTargetForThisRow = 0
    currentSellTargetValue = 0
    currentBuyTargetValue = 0
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    numberOfTimesAskedToEnterTradeShort = 0
    numberOfTimesAskedToEnterTradeLong = 0
    numberOfTimesAskedToExitTradeShort = 0
    numberOfTimesAskedToExitTradeLong = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
    reasonForTrade['CloseBuyTradeHappened'] = 0
    reasonForTrade['OpenBuyTradeHappened'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
    reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
    reasonForTrade['OpenSellTradeHappened'] = 0
    reasonForTrade['CloseSellTradeHappened'] = 0
    reasonForTrade['PrevWasOurOrder'] = 0
    lReasonForTradingOrNotTradingShort = ""
    lReasonForTradingOrNotTradingLong = ""
    currentIndex = 0
    lDummyBidQ0 = 0
    lDummyAskQ0=0 
    lDummyTTQForBuy =0 
    lDummyTTQForSell = 0
    print("Processing the data file for trades :")
    attribute.initList()
    prevBuyTargetValue = 0
    prevSellTargetValue = 0
    exchangeTimeStamp = 0
    lOpenBuyIndex = 0
    lOpenSellIndex = 0
    l_exchange_time_stamp_to_print= ""
    for currentDataRow in dataFile.matrix:
     
        l_expiry_wrt_1970 = exchangeTimeStamp + 315513000.0
        
        l_dt = datetime.datetime.fromtimestamp(l_expiry_wrt_1970)
        l_exchange_time_stamp_to_print = str(l_dt.hour) + ":" + str(l_dt.minute) + ":" + str(l_dt.second)
        lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,ttqAtTimeOfPreviousDataRow,askP0AtTimeOfPreviousDataRow,bidP0AtTimeOfPreviousDataRow,\
                                                                                 askQ0AtTimeOfPreviousDataRow , bidQ0AtTimeOfPreviousDataRow , enterTradeShort,enterTradeLong,tradeStats,reasonForTrade,\
                                                                                 lReasonForTradingOrNotTradingLong,lReasonForTradingOrNotTradingShort )
     
        lReasonForTradingOrNotTradingShort = lReturnList[0]
        lReasonForTradingOrNotTradingLong = lReturnList[1] 
        lDummyBidQ0 = lReturnList[2]
        lDummyAskQ0 = lReturnList[3]
        lDummyTTQForBuy = lReturnList[4]
        lDummyTTQForSell = lReturnList[5]
        if currentIndex > 0:
            lFlag = 0
            if "CloseSell" in lReasonForTradingOrNotTradingLong:
                 if gCloseSellPrice - gOpenBuyPrice <= 0 :
                     for i in range(lOpenBuyIndex,currentIndex):
                         attribute.aList[i][1] = 0
                 else:
                     lFlag = 1
                 lOpenBuyIndex = 0
            if "CloseBuy" in lReasonForTradingOrNotTradingShort:
                 if gOpenSellPrice - gCloseBuyPrice <= 0 :
                     for i in range(lOpenSellIndex,currentIndex):
                         attribute.aList[i][1] = 0
                 else:
                     lFlag = 1
                 lOpenSellIndex=0
            if "OpenSell" in lReasonForTradingOrNotTradingShort:
                 lOpenSellIndex = currentIndex-1
            if "OpenBuy" in lReasonForTradingOrNotTradingLong:
                 lOpenBuyIndex = currentIndex-1

            if (lOpenSellIndex !=0 or lOpenBuyIndex!=0):
                lFlag = 1
                

            attribute.aList[currentIndex-1][0] = currentTimeStamp
            attribute.aList[currentIndex-1][1] = lFlag
            attribute.aList[currentIndex-1][2] = tradeStats['currentPositionLong']
            listOfStringsToPrint = [ str(tradeStats['currentPositionShort']) , str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , \
                                    str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) ,\
                                    str(currentSellTargetValue) , str(enterTradeShort) ,lReasonForTradingOrNotTradingShort , str(currentBuyTargetValue) ,\
                                    str(enterTradeLong) ,lReasonForTradingOrNotTradingLong ,l_exchange_time_stamp_to_print, str(reasonForTrade['CloseBuyTradeHappened']),\
                                    str(reasonForTrade['OpenBuyTradeHappened']),str(reasonForTrade['OpenSellTradeHappened']),str(reasonForTrade['CloseSellTradeHappened']),\
                                    str(gCloseSellPrice),str(gOpenBuyPrice),str(gOpenSellPrice),str(gCloseBuyPrice)]
            attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])
    
        try:
            currentSellTargetValue = float(targetValuesDict[currentTimeStamp]['sell']) 
            currentBuyTargetValue  = float(targetValuesDict[currentTimeStamp]['buy'])
        except:
            noTargetForThisRow += 1
    
        #short decisions
        if(currentSellTargetValue == 1):
            enterTradeShort = 1
            numberOfTimesAskedToEnterTradeShort += 1
        elif(currentSellTargetValue == 0 and tradeStats['currentPositionShort'] > 0):
            numberOfTimesAskedToExitTradeShort += 1
            enterTradeShort = -1  # Implies to exit the trade
        else:
            enterTradeShort = 0  # Implies make no change
            
        #long decisions
        if(currentBuyTargetValue == 1):
            enterTradeLong = 1
            numberOfTimesAskedToEnterTradeLong += 1
        elif(currentBuyTargetValue == 0 and tradeStats['currentPositionLong'] > 0):
            numberOfTimesAskedToExitTradeLong += 1
            enterTradeLong = -1  # Implies to exit the trade
        else:
            enterTradeLong = 0  # Implies make no change
        
        ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ]) 
        askP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskP0])
        bidP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidP0])
        askQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskQ0])
        bidQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidQ0])
        ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
        currentIndex = currentIndex + 1
        prevBuyTargetValue = currentBuyTargetValue
        prevSellTargetValue = currentSellTargetValue
        exchangeTimeStamp = float(currentDataRow[colNumberOfData.ExchangeTS])
    
    # Squaring off if some open position there   
    if tradeStats['currentPositionLong'] > 0:
        reasonForTrade['CloseSellTradeHappened'] += tradeStats['currentPositionLong']
        tradeStats['totalSellValueLong'] += tradeStats['currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionLong'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
        gCloseSellPrice = bidP0AtTimeOfPreviousDataRow
        if gCloseSellPrice - gOpenBuyPrice < 0 :
             for i in range(lOpenBuyIndex,currentIndex):
                 attribute.aList[i][1] = 0
                 
    if tradeStats['currentPositionShort'] > 0:
        reasonForTrade['CloseBuyTradeHappened'] += tradeStats['currentPositionShort']
        tradeStats['totalBuyValueShort'] += tradeStats['currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionShort'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'
        gCloseBuyPrice = askP0AtTimeOfPreviousDataRow
        if gOpenSellPrice - gCloseBuyPrice < 0 :
             for i in range(lOpenSellIndex,currentIndex):
                 attribute.aList[i][1] = 0 
                    
    attribute.aList[currentIndex-1][0] = currentTimeStamp
    attribute.aList[currentIndex-1][1] = attribute.aList[currentIndex-2][1]
    attribute.aList[currentIndex-1][2] = tradeStats['currentPositionLong']
    listOfStringsToPrint = [ str(tradeStats['currentPositionShort']),str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) ,\
                             str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , \
                             str(currentSellTargetValue) , str(enterTradeShort) , "" , str(currentBuyTargetValue) , str(enterTradeLong) ,\
                             "" ,l_exchange_time_stamp_to_print, str(reasonForTrade['CloseBuyTradeHappened']),str(reasonForTrade['OpenBuyTradeHappened']),str(reasonForTrade['OpenSellTradeHappened']),\
                             str(reasonForTrade['CloseSellTradeHappened']),str(gCloseSellPrice),str(gOpenBuyPrice),str(gOpenSellPrice),str(gCloseBuyPrice)]
    attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
    
    dirName = args.d.replace('/ro/','/wf/')
    tradeLogMainDirName = dirName+"/tr/"
    if not os.path.exists(tradeLogMainDirName):
         os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeLogSubDirectoryName):
         os.mkdir(tradeLogSubDirectoryName)
    
    fileName = tradeLogSubDirectoryName + pFileName + ".targetTrade" 
    lHeaderColumnNamesList  = ['TimeStamp','targetValue','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP',\
                               'CurTargetValueShort','EnterTradeShort','ReasonForTradingOrNotTradingShort','CurTargetValueLong','EnterTradeLong',\
                               'ReasonForTradingOrNotTradingLong','Exchange_TS','totalBuyShort','totalBuyLong','totalSellShort','totalSellLong','CloseSellPrice',\
                               'OpenBuyPrice','OpenSellPrice','CloseBuyPrice']
    attribute.writeToFile(fileName , lHeaderColumnNamesList)
    
    tradeResultMainDirName = dirName+"/r/"
    if not os.path.exists(tradeResultMainDirName):
         os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
    if not os.path.exists(tradeResultSubDirectoryName):
         os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName+pFileName+".targetResult" 
    outputFile = open(fileName,"w")
    
    #changed file write to modify it to Short Long version
    print("Starting to write: "+fileName)
    print("The net results for Short are: " + str(tradeStats['totalSellValueShort'] - tradeStats['totalBuyValueShort']), file = outputFile)
    print("The net results for Long are: " + str(tradeStats['totalSellValueLong'] - tradeStats['totalBuyValueLong']), file = outputFile)
    print("Number of rows for which there is no target: " + str(noTargetForThisRow), file = outputFile)    
    print("Number of times asked to enter trade Short: " + str(numberOfTimesAskedToEnterTradeShort), file = outputFile)    
    print("Number of times asked to enter trade Long: " + str(numberOfTimesAskedToEnterTradeLong), file = outputFile)    
    print("Number of times asked to exit trade Short: " + str(numberOfTimesAskedToExitTradeShort), file = outputFile)
    print("Number of times asked to exit trade Long: " + str(numberOfTimesAskedToExitTradeLong), file = outputFile)
    print("Assumed close buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort']), file = outputFile)
    print("Assumed open buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong']), file = outputFile)
    print("Assumed close buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0Short']), file = outputFile)
    print("Assumed open buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0Long']), file = outputFile)
    print("Assumed close buy trade happened: " + str(reasonForTrade['CloseBuyTradeHappened']), file = outputFile)
    print("Assumed open buy trade happened: " + str(reasonForTrade['OpenBuyTradeHappened']), file = outputFile)
    print("Assumed open sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']), file = outputFile)
    print("Assumed close sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']), file = outputFile)
    print("Assumed open sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Short']), file = outputFile)
    print("Assumed close sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Long']), file = outputFile)
    print("Assumed open sell trade happened: " + str(reasonForTrade['OpenSellTradeHappened']), file = outputFile)
    print("Assumed close sell trade happened: " + str(reasonForTrade['CloseSellTradeHappened']), file = outputFile)
    print("The total open sell value is: " + str(tradeStats['totalSellValueShort']), file = outputFile)
    print("The total close sell value is: " + str(tradeStats['totalSellValueLong']), file = outputFile)
    print("The total close buy value is: " + str(tradeStats['totalBuyValueShort']), file = outputFile)
    print("The total open buy value is: " + str(tradeStats['totalBuyValueLong']), file = outputFile)
    
    try:
        averageOpenSellPrice = tradeStats['totalSellValueShort']/reasonForTrade['OpenSellTradeHappened']
        averageCloseBuyPrice = tradeStats['totalBuyValueShort']/reasonForTrade['CloseBuyTradeHappened']
    except:
        averageOpenSellPrice = 0 
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats['totalSellValueLong']/reasonForTrade['CloseSellTradeHappened']
        averageOpenBuyPrice = tradeStats['totalBuyValueLong']/reasonForTrade['OpenBuyTradeHappened']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0 
    
    print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
    print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
    print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
    print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
    print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
    print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
    pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
    pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)