Пример #1
0
def closeAllOrders(SetUp, TradeInfo):
    apiK = open(SetUp['paths']['secure'], 'r').read().split('\n')
    client = Client(apiK[0], apiK[1])
    acc = getBalance(SetUp)
    if len(acc['openBuyOrders']) > 0:
        for i in acc['openBuyOrders']:
            print('Closing open buy order (' + str(i['orderId']) + ')')
            order = client.cancel_order(symbol=SetUp['trade']['pair'],
                                        orderId=i['orderId'])
    if len(acc['openSellOrders']) > 0:
        for i in acc['openSellOrders']:
            print('Closing open sell order (' + str(i['orderId']) + ')')
            order = client.cancel_order(symbol=SetUp['trade']['pair'],
                                        orderId=i['orderId'])
    # Calculate Stop loss value
    LastPrice = float(
        client.get_symbol_ticker(symbol=SetUp['trade']['pair'])['price'])
    if not TradeInfo['btclO'].isnull()[0]:
        print('Closing long position (' + str(TradeInfo['btclO'][0]) + ')')
        qqty = binFloat(TradeInfo['btclO'][0])
        # Put in the order
        order = client.create_order(
            symbol=SetUp['trade']['pair'],
            side='SELL',
            type='MARKET',
            quantity=qqty,
        )
        TradeInfo['btclO'] = np.nan
        TradeInfo['BprlO'] = np.nan

    if not TradeInfo['btcsO'].isnull()[0]:
        print('Closing short position (' + str(TradeInfo['btcsO'][0]) + ')')
        qqty = binFloat(TradeInfo['btcsO'][0])
        # Put in the order
        order = client.create_order(
            symbol=SetUp['trade']['pair'],
            side='BUY',
            type='MARKET',
            quantity=qqty,
        )
        TradeInfo['btcsO'] = np.nan
        TradeInfo['BprsO'] = np.nan

    TradeInfo = initTradeFiles(SetUp)
    return TradeInfo
Пример #2
0
def putOrder(SetUp, TradeInfo, side):
    apiK = open(SetUp['paths']['secure'], 'r').read().split('\n')
    client = Client(apiK[0], apiK[1])
    LastPrice = float(
        client.get_symbol_ticker(symbol=SetUp['trade']['pair'])['price'])
    if side == 'BUY':
        TradeInfo['btclO'] = binFloat(TradeInfo['Free Funds'][0] *
                                      SetUp['trade']['PercentFunds'] /
                                      LastPrice * SetUp['trade']['Leverage'])
    elif side == 'SELL':
        TradeInfo['btcsO'] = binFloat(TradeInfo['Free Funds'][0] *
                                      SetUp['trade']['PercentFunds'] /
                                      LastPrice * SetUp['trade']['Leverage'])
    # Create a Long order


#    if tpBol:
#        qtytp1 = binFloat(TradeInfo['btclO'][0]*SetUp['trade']['ftp']
#            ) if side == 'BUY' else binFloat(TradeInfo['btcsO'][0]*SetUp['trade']['ftp'])
#        qtytp2 = binFloat(TradeInfo['btclO'][0]*(1-SetUp['trade']['ftp']
#            )) if side == 'BUY' else binFloat(TradeInfo['btcsO'][0]*(1-SetUp['trade']['ftp']))
#        tp1stop = binFloat(LastPrice*(SetUp['trade']['tp1']+1.0)
#            ) if side == 'BUY' else binFloat(LastPrice*(1.0 - SetUp['trade']['tp1']))
#        tp2stop = binFloat(LastPrice*(SetUp['trade']['tp2']+1.0)
#            ) if side == 'BUY' else binFloat(LastPrice*(1.0 - SetUp['trade']['tp2']))
#
#        ordertp1 = client.create_order(
#        symbol=SetUp['trade']['pair'],
#        side=side,
#        type='MARKET',
#        quantity=qtytp1,
#        )
#        TradeInfo = checkMarketOrder(TradeInfo,SetUp,ordertp1,1)
#        ordertp2 = client.create_order(
#        symbol=SetUp['trade']['pair'],
#        side=side,
#        type='MARKET',
#        quantity=qtytp2,
#        )
#        TradeInfo = checkMarketOrder(TradeInfo,SetUp,ordertp2,2)
#    else:
    qqty = binFloat(TradeInfo['btclO'][0]) if side == 'BUY' else binFloat(
        TradeInfo['btcsO'][0])
    order = client.create_order(
        symbol=SetUp['trade']['pair'],
        side=side,
        type='MARKET',
        quantity=qqty,
    )
    TradeInfo = checkMarketOrder(TradeInfo, SetUp, order, False)
    TradeInfo['BlO'] = True if side == 'BUY' else False
    TradeInfo['BsO'] = True if side == 'SELL' else False
    acc = getBalance(SetUp)
    TradeInfo['Free Funds'] = acc['USDT']['wBalance']
    return TradeInfo
Пример #3
0
def reset_account(SetUp, TradeInfo):
    apiK = open(SetUp['paths']['secure'], 'r').read().split('\n')
    client = Client(apiK[0], apiK[1])
    acc = getBalance(SetUp)
    if len(acc['openBuyOrders']) > 0:
        for i in acc['openBuyOrders']:
            order = client.cancel_order(symbol=SetUp['trade']['pair'],
                                        orderId=i['orderId'])
    if len(acc['openSellOrders']) > 0:
        for i in acc['openSellOrders']:
            order = client.cancel_order(symbol=SetUp['trade']['pair'],
                                        orderId=i['orderId'])
        if acc['BTC']['wBalance'] > 0:
            order = client.create_order(
                symbol=SetUp['trade']['pair'],
                side='SELL',
                type='MARKET',
                quantity=binFLoat(acc['BTC']['wbalance']),
            )
    TradeInfo = initTradeFiles(SetUp)
Пример #4
0
def takeProfit(SetUp, TradeInfo, side):
    # use implicit Falsness of empty lists
    if side == 'SELL':
        if not TradeInfo['lTP2ID'].isnull(
        )[0] and not TradeInfo['lTP2ID'].isnull()[0]:
            print('TP1 order (Id=' + str(TradeInfo['lTP1ID'][0]) +
                  ') and TP2 order (Id=' + str(TradeInfo['lTP2ID'][0]) +
                  ') exists')
            print('No action taken')
            return TradeInfo
    elif side == 'BUY':
        if not TradeInfo['sTP2ID'].isnull(
        )[0] and not TradeInfo['sTP2ID'].isnull()[0]:
            print('TP1 order (Id=' + str(TradeInfo['sTP1ID'][0]) +
                  ') and TP2 order (Id=' + str(TradeInfo['sTP2ID'][0]) +
                  ') exists')
            print('No action taken')
            return TradeInfo

    limit1 = SetUp["trade"]["tp1"] - SetUp["trade"][
        "TPlimitadd"] if side == 'BUY' else SetUp["trade"]["tp1"] + SetUp[
            "trade"]["TPlimitadd"]
    limit2 = SetUp["trade"]["tp2"] - SetUp["trade"][
        "TPlimitadd"] if side == 'BUY' else SetUp["trade"]["tp2"] + SetUp[
            "trade"]["TPlimitadd"]
    stop1 = SetUp["trade"]["tp1"] if side == 'BUY' else SetUp["trade"]["tp1"]
    stop2 = SetUp["trade"]["tp2"] if side == 'BUY' else SetUp["trade"]["tp2"]
    # Open Binance client
    apiK = open(SetUp['paths']['secure'], 'r').read().split('\n')
    client = Client(apiK[0], apiK[1])

    # Calculate Stop loss value
    LastPrice = float(
        client.get_symbol_ticker(symbol=SetUp['trade']['pair'])['price'])
    if side == 'SELL':
        qtytp1 = binFloat(TradeInfo['btclO'][0] * SetUp['trade']['ftp'])
        qtytp2 = binFloat(TradeInfo['btclO'][0] * (1 - SetUp['trade']['ftp']))
        tp1stop = binFloat(LastPrice * (1 + stop1))
        tp2stop = binFloat(LastPrice * (1 + stop2))
        tp1limit = binFloat(LastPrice * (1 + limit1))
        tp2limit = binFloat(LastPrice * (1 + limit2))
    else:
        qtytp1 = binFloat(TradeInfo['btcsO'][0] * SetUp['trade']['ftp'])
        qtytp2 = binFloat(TradeInfo['btcsO'][0] * (1 - SetUp['trade']['ftp']))
        tp1stop = binFloat(LastPrice * (1 - stop1))
        tp2stop = binFloat(LastPrice * (1 - stop2))
        tp1limit = binFloat(LastPrice * (1 - limit1))
        tp2limit = binFloat(LastPrice * (1 - limit2))

    ordertp1 = client.create_order(symbol=SetUp['trade']['pair'],
                                   side=side,
                                   type='TAKE_PROFIT',
                                   timeInForce='GTC',
                                   reduceOnly='true',
                                   quantity=qtytp1,
                                   stopPrice=tp1stop,
                                   price=tp1limit)
    ordertp2 = client.create_order(symbol=SetUp['trade']['pair'],
                                   side=side,
                                   type='TAKE_PROFIT',
                                   timeInForce='GTC',
                                   reduceOnly='true',
                                   quantity=qtytp2,
                                   stopPrice=tp2stop,
                                   price=tp2limit)
    TradeInfo['lTP1ID'] = int(ordertp1['orderId']) if side == "SELL" else None
    TradeInfo['lTP2ID'] = int(ordertp2['orderId']) if side == "SELL" else None
    TradeInfo['CprlTP1'] = tp1stop if side == "SELL" else None
    TradeInfo['CprlTP2'] = tp2stop if side == "SELL" else None

    TradeInfo['sTP1ID'] = int(ordertp1['orderId']) if side == "BUY" else None
    TradeInfo['sTP2ID'] = int(ordertp2['orderId']) if side == "BUY" else None
    TradeInfo['CprsTP1'] = tp1stop if side == "SELL" else None
    TradeInfo['CprsTP2'] = tp2stop if side == "SELL" else None

    print('Initiated Take profit (' + side + ') at: ' +
          SetUp['trade']['pairTrade'] + '=' + str(tp1stop) + '/' +
          str(tp2stop))
    return TradeInfo
Пример #5
0
def stopLoss(SetUp, TradeInfo, side, stop):
    """  This submodule sets a stop loss order.

    Args:
        SetUp (dict): trading set-up set with SetUp = ini.initSetUp()
        TradeInfo (dict): Current state of trades
        side (str): side of transaction ('SELL' or 'BUY') 
        stop (float): fraction of price above or below current for the stop loss

    Returns:
        TradeInfo (dict): Current state of trades is updated
    """
    # Check arguments and raise exceptions if needed
    if side != 'SELL' and side != 'BUY':
        raise Exception('Error: set side to a valid value (SELL or BUY)')
        return TradeInfo

    if not TradeInfo['LongStopLossId'].isnull()[0] and side == 'SELL':
        print('Current stop loss (Id=' + str(TradeInfo['LongStopLossId'][0]) +
              ') exists')
        print('No action taken')
        return TradeInfo
    elif not TradeInfo['ShortStopLossId'].isnull()[0] and side == 'BUY':
        print('Current stop loss (Id=' + str(TradeInfo['ShortStopLossId'][0]) +
              ') exists')
        print('No action taken')
        return TradeInfo

    limit = SetUp["trade"]["Stoplimitadd"]

    # Open Binance client
    apiK = open(SetUp['paths']['secure'], 'r').read().split('\n')
    client = Client(apiK[0], apiK[1])

    # Calculate Stop loss value
    LastPrice = float(
        client.get_symbol_ticker(symbol=SetUp['trade']['pair'])['price'])
    if side == 'SELL':
        stopPrice = binFloat((1 - float(stop)) * LastPrice)
        limitPrice = binFloat((1 - float(stop + limit)) * LastPrice)
        TradeInfo['Sell Stop Price'] = stopPrice
        qqty = binFloat(TradeInfo['btclO'][0])
    elif side == 'BUY':
        stopPrice = binFloat((1 + float(stop)) * LastPrice)
        limitPrice = binFloat((1 + float(stop - limit)) * LastPrice)
        TradeInfo['Buy Stop Price'] = stopPrice
        qqty = binFloat(TradeInfo['btcsO'][0])

    # Put in the order
    order = client.create_order(
        symbol=SetUp['trade']['pair'],
        side=side,
        type='STOP_MARKET',
        reduceOnly='true',
        quantity=qqty,
        stopPrice=binFloat(stopPrice),
        #    price=binFloat(limitPrice),
    )

    if side == 'SELL':
        TradeInfo['LongStopLossId'] = int(order['orderId'])
    elif side == 'BUY':
        TradeInfo['ShortStopLossId'] = int(order['orderId'])
    print('Initiated Stop loss at: ' + SetUp['trade']['pairTrade'] + '=' +
          str(stopPrice))
    return TradeInfo