Exemplo n.º 1
0
def FetchTradingPairs():
    # Fetch a list of trading pairs for which quotes should be fetched
    global tradingPairList
    try:
        if len(tradingPairList) != 0:
            # TODO: Create logging item
            return tradingPairList
        with open(initService.getTradingPairsFileLocation()) as json_file:
            # TODO: Create logging item
            JSONFromFile = json.load(json_file)
            tradingPairList = ConvertToList(JSONFromFile)
            return tradingPairList
    except NameError:
        print("Log: File '" + initService.getTradingPairsFileLocation() +
              "' does not exist")
Exemplo n.º 2
0
def fetchSellOrdersToSwap(quoteResponseList):
    print(datetime.datetime.now().isoformat() +
          " ##### SellOrderService: Fetch SellOrders to SWAP #####")
    takeprofit = tradingPairService.FetchTradingPairs()[0].takeProfitPercentage
    # Validate if an outstanding virtual sell order is smaller then recent quote
    modifiedSellOrderlist = []
    for quoteResponse in quoteResponseList:
        for sellOrder in fetchSellOrders():
            if float(sellOrder.sellprice) < float(quoteResponse.toAmount):
                print(datetime.datetime.now().isoformat() +
                      " ##### SellOrderService: !!HIT!! Quote price [[" +
                      str(quoteResponse.toAmount) +
                      "]] is higher then Virtual Sell Order price [[" +
                      str(sellOrder.sellprice) + "]] for pair <BTSBUSD> #####")
                tradeService.appendClosedSwapToFile(sellOrder, quoteResponse)
            else:
                print(datetime.datetime.now().isoformat() +
                      " ##### SellOrderService: Quote price [[" +
                      str(quoteResponse.toAmount) +
                      "]] is lower than Virtual Sell Order price [[" +
                      str(sellOrder.sellprice) + "]] for pair <BTSBUSD> #####")
                # SellOrder remains valid therefore appended to the ModifiedSellOrderList
                modifiedSellOrderlist.append(sellOrder)
        commonService.writeJson(InitService.getSellOrdersFileLocation(),
                                modifiedSellOrderlist)
Exemplo n.º 3
0
def fetchBuyOrderList():
    filename = InitService.getBuyOrderFileLocation()
    if commonService.checkIfFileExists(filename):
        with open(filename) as json_file:
            JSONFromFile = json.load(json_file)
            buyOrderList = ConvertToList(JSONFromFile)
            return buyOrderList
Exemplo n.º 4
0
def executeSwap(swapOrder):

        # execute health check of exchange API
        if requests.get('https://api.1inch.exchange/v3.0/56/healthcheck').json()["status"] == "OK":
            print(datetime.datetime.now().isoformat() + " ##### SwapService: Exchange health check okey #####")
            # TODO: 2. Check if approved
            # 3. ActualiseQuote
            quote = fetchActualQuote()
            # 4. Request swap
            swapRequest = requestSwap(tokenService.getAddress(swapOrder.baseToken), tokenService.getAddress(swapOrder.swapToken), swapOrder.baseAmount, swapOrder.slippage)
            #print(swapRequest["tx"])
            signed_tx = signTx(swapRequest["tx"])
            #print(signed_tx)
            if initService.getTradeExecution() == True:
                tx_hash = sendTx(signed_tx).hex()
                print(tx_hash.hex())
            else:
                tx_hash = "NOT SWAPPED - PAPER TRADING"
            # TODO: BB-8 not implemented yet
            # 4. Creat SellOrder
            if swapOrder.type == "BUY":
                json.dumps(signed_tx, ensure_ascii=False, default=lambda o: o.__dict__,
                          sort_keys=False, indent=4)
                sellOrderService.placeVirtualSellOrder(swapOrder, tx_hash)
            elif swapOrder.type == "SELL":
                print("test temp")
            return
        else:
            print(datetime.datetime.now().isoformat() + " ##### SwapService: Exchange health check NOT Okey, cannot proceed with swap #####")
Exemplo n.º 5
0
 def run(self, *args, **kwargs):
     while True:
         print(datetime.datetime.now().isoformat() +
               " ##### BackGroundTasks: Starting BuyOrderScheduler #####")
         buyOrderService.placeVirtualBuyorders()
         print(datetime.datetime.now().isoformat() +
               " ##### BackGroundTasks: Finished BuyOrderScheduler #####")
         time.sleep(initService.getBuyOrderInterval())
Exemplo n.º 6
0
def appendClosedSwapToFile(closedSellOrder, quoteResponse):
    print(
        datetime.datetime.now().isoformat() +
        " ##### TradeService: Appending ClosedSellOrder to ClosedSwaps.json #####"
    )
    # First fetch the historical ClosedSwaps from file
    closedSwapList = fetchClosedSwaps(initService.getClosedSwapsFileLocation())
    # Now append new closedSellOrder
    closedSwapList = addClosedSwapToList(closedSwapList, closedSellOrder)
    # Now convert from quote entity list to JSON object
    closedSwapJSON = json.dumps(closedSwapList,
                                ensure_ascii=False,
                                default=lambda o: o.__dict__,
                                sort_keys=False,
                                indent=4)
    with open(initService.getClosedSwapsFileLocation(), 'w+') as json_file:
        json_file.write(closedSwapJSON + '\n')
Exemplo n.º 7
0
    def run(self, *args, **kwargs):

        while True:
            print(datetime.datetime.now().isoformat() +
                  " ##### BackGroundTasks: Starting QuoteScheduler #####")
            quoteService.ScheduledQuoteRequest()
            print(datetime.datetime.now().isoformat() +
                  " ##### BackGroundTasks: Finished QuoteScheduler #####")
            time.sleep(initService.getQuoteInterval())
Exemplo n.º 8
0
def write_json(quoteResponseEntity):
    # First fetch the history of quotes
    quoteList = fetchQuoteResponse()
    # Now append the new quote
    quoteList = addQuoteToList(quoteList, quoteResponseEntity)
    # Now convert from quote entity list to JSON object
    quoteJSON = json.dumps(quoteList, ensure_ascii=False, default=lambda o: o.__dict__,
                           sort_keys=False, indent=4)
    with open(InitService.getQuoteFileLocation(), 'w+') as json_file:
        json_file.write(quoteJSON + '\n')
Exemplo n.º 9
0
def fetchQuoteResponse():
    filename = initService.getQuoteFileLocation()
    if commonService.checkIfFileExists(filename):
        with open(filename) as json_file:
            JSONFromFile = json.load(json_file)
            # create list of quotes from json file
            quoteList = convertToList(JSONFromFile)
            return quoteList
    else:
        quoteList = []
        return quoteList
Exemplo n.º 10
0
def fetchClosedTradeList():
    filename = initService.getClosedSwapsFileLocation()
    if commonService.checkIfFileExists(filename):
        with open(filename) as json_file:
            JSONFromFile = json.load(json_file)
            closedSwapList = convertToList(JSONFromFile)
            return closedSwapList
    else:
        print(datetime.datetime.now().isoformat() +
              " ##### TradeService: No closed trades found #####")
        closedSwapList = []
        return closedSwapList
Exemplo n.º 11
0
def fetchSellOrders():
    filename = InitService.getSellOrdersFileLocation()
    print(datetime.datetime.now().isoformat() +
          " ##### SellOrderService: Fetching outstanding Sell Orders #####")
    if commonService.checkIfFileExists(filename):
        with open(filename) as json_file:
            JSONFromFile = json.load(json_file)
            # create list of quotes from json file
            sellOrderList = convertToList(JSONFromFile)
            return sellOrderList
    else:
        print(
            datetime.datetime.now().isoformat() +
            " ##### SellOrderService: No outstanding sell orders found #####")
        sellOrderList = []
        return sellOrderList
Exemplo n.º 12
0
def placeVirtualSellOrder(swapOrder, tx_hash):
    print(datetime.datetime.now().isoformat() +
          " ##### SellOrderService: Swapping Buy Order to Sell Order #####")
    buyOrder = swapOrder.order
    quoteResponse = swapOrder.quote
    # TODO: also include temporarily the buyorder being swapped and later the actual swapped order details along with the sell order
    # TODO: include slippage
    tp = tradingPairService.FetchTradingPairs()[0].takeProfitPercentage
    sellOrder = entity.sellOrder.SellOrder(
        buyOrder.swapToken,  # The swaptoken from buy becomes basetoken
        buyOrder.baseToken,  # The basetoken from buy becomes swaptoken
        quoteResponse.
        toAmount,  # Price for which the amount of basetoken was purchased, for now this is the quoted price
        float(quoteResponse.toAmount) *
        (1 + (tp + buyOrder.slippage) /
         100),  # sell price based on quoted price later based on real swap
        buyOrder.amount / quoteResponse.
        toAmount,  # amount swapped incl. max slipage used, in buy order expressed in base token of sell order
        buyOrder.amount / quoteResponse.toAmount *
        float(quoteResponse.toAmount) *
        (1 + tp / 100),  # Swapped amount if sell order would be filled
        buyOrder.amount / quoteResponse.toAmount *
        float(quoteResponse.toAmount) * (1 + tp / 100) -
        buyOrder.amount,  # expected profit
        tp,  # Take profit percentage
        buyOrder.slippage,
        quoteResponse,
        buyOrder,
        swapOrder,
        tx_hash)
    print(
        datetime.datetime.now().isoformat() +
        " ##### SellOrderService: Add new sell order to outstanding Sell Orders #####"
    )
    # First fetch the list of outstanding SellOrders
    sellOrderList = fetchSellOrders()
    # now append the new sellOrder
    sellOrderList = addSellOrderToList(sellOrderList, sellOrder)
    # now convert from quote entity list to JSON object
    commonService.writeJson(InitService.getSellOrdersFileLocation(),
                            sellOrderList)
Exemplo n.º 13
0
def checkBuyOrdersForExecution(quoteResponseList):
    print(
        datetime.datetime.now().isoformat() +
        " ##### BuyOrderService: Checking if virtual buy orders to swap #####")
    # Validate if an outstanding virtual buy order is greater then recent quote
    for quoteResponse in quoteResponseList:
        for buyOrderListPair in fetchBuyOrderList():
            for pair, buyOrderList in buyOrderListPair.items(
            ):  # pair = key; buyOrderList = value
                modifiedBuyOrderlist = []
                for index, buyOrder in enumerate(buyOrderList):
                    if float(buyOrder.buyprice) > float(
                            quoteResponse.toAmount):
                        print(
                            datetime.datetime.now().isoformat() +
                            " ##### BuyOrderService: !!HIT!! Quote price [[" +
                            str(quoteResponse.toAmount) +
                            "]] is below Virtual Buy Order price [[" +
                            str(buyOrder.buyprice) + "]] for pair <" + pair +
                            ">. #####")
                        #SellOrderService.swapToSellOrder(buyOrder, quoteResponse)
                        swapService.swapBuyOrder(buyOrder, quoteResponse)
                    else:
                        print(datetime.datetime.now().isoformat() +
                              " ##### BuyOrderService: Quote price [[" +
                              str(quoteResponse.toAmount) +
                              "]] is above Virtual Buy Order price [[" +
                              str(buyOrder.buyprice) + "]] for pair <" + pair +
                              ">. #####")
                        # BuyOrder remains valid therefore appended to the ModifiedBuyOrderList
                        # for testing only swapService.swapBuyOrder(buyOrder, quoteResponse)
                        modifiedBuyOrderlist.append(buyOrder)
                # Now replace the buyOrderList with the modifiedBuyOrderList
                buyOrderListPair[pair] = modifiedBuyOrderlist
            newOutStandingBuyOrderList = []
            newOutStandingBuyOrderList.append(buyOrderListPair)
        commonService.writeJson(InitService.getBuyOrderFileLocation(),
                                newOutStandingBuyOrderList)
Exemplo n.º 14
0
def placeVirtualBuyorders():
    print(datetime.datetime.now().isoformat() +
          " ##### BuyOrderService: Actualising BuyOrderList #####")
    # Fetch a list of trading pairs for which quotes should be fetched
    tradingPairList = tradingPairService.FetchTradingPairs()
    # now loop trough the list of tradingPair objects
    outStandingBuyOrderList = []
    for tradingPair in tradingPairList:
        lastQuoteResponses = quoteService.fetchRecentQuotes(1)
        buyOrderPairList = calculateBuyOrderList(lastQuoteResponses,
                                                 tradingPair)
        pair = tradingPair.swapToken + tradingPair.baseToken
        pairToAdd = {}
        pairToAdd[pair] = {}
        pairToAdd[pair] = buyOrderPairList
        outStandingBuyOrderList.append(pairToAdd)
    # Now actualise the buyOrderList JSON file
    commonService.writeJson(InitService.getBuyOrderFileLocation(),
                            outStandingBuyOrderList)
    print(datetime.datetime.now().isoformat() +
          " ##### BuyOrderService: BuyOrderList actualised #####")
    # TODO: Return full list, not only actualised ones but also ones for which no pair is active
    return outStandingBuyOrderList
Exemplo n.º 15
0
def approve(address):
    swapService.ApproveBaseToken(address)
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())
Exemplo n.º 16
0
from flask import Flask, render_template
import services.InitService as InitService
from services.TokenService import tokenList
from services.ProtocolService import protocolList
import services.QuoteService as quoteService
import services.BuyOrderService as buyOrderService
import services.SellOrderService as sellOrderService
import services.TradeService as tradeService
import services.SwapService as swapService
import datetime



app = Flask(__name__)
InitService.InitialiseBot()


@app.route('/')
def home():
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())

@app.route('/approve/<address>')
def approve(address):
    swapService.ApproveBaseToken(address)
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())

@app.route('/restart')
def restart():
    print(datetime.datetime.now().isoformat() + " ##### Engine: Restart #####")
    InitService.RestartBot()
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())
Exemplo n.º 17
0
def home():
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())
Exemplo n.º 18
0
def placeVirtualBuyOrders():
    buyOrderService.placeVirtualBuyorders()
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())
Exemplo n.º 19
0
def fetchQuotes():
    quoteService.ScheduledQuoteRequest()
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())
Exemplo n.º 20
0
def restart():
    print(datetime.datetime.now().isoformat() + " ##### Engine: Restart #####")
    InitService.RestartBot()
    return render_template("index.html", dashBoardData = InitService.getDashBoardFigures())
Exemplo n.º 21
0
def addQuoteToList(quoteList, quoteResponseEntity):
    # append the quote entity object to the quoteList
    quoteList = quoteList[-InitService.getQuoteHistoryCount():]
    quoteList.append(quoteResponseEntity)
    return quoteList