Include MACD with live trading data

Hello to all i have this code with live data and i try it to add the MACD to buy when the macd > 0 and dont buy when the macd < 0
without includ the macd bot working perfectly, but when i go to add the macd of course bot running but dosnt execute trades. Can someone help me?

THIS IS THE CODE WITHOUT INCLUDE MACD (working)

df = pd.DataFrame()
in_position = False
buyorders,sellorders = [],[]

def on_open(ws):
    ws.send(our_msg)
    
def on_message(ws,message):
    global df, in_position, buyorders, orderqty, buyprice#, sellorders
    out = json.loads(message)
    out = pd.DataFrame({'price':float(out['c'])}, index=[pd.to_datetime(out['E'],unit='ms')])
    df = pd.concat([df,out],axis=0)
    print(df)
    df = df.tail(15)
    last_price = df.tail(1).price.values[0]
    sma_15 = df.price.rolling(15).mean().tail(1).values[0]
    if not in_position and last_price > sma_15:
        order = client.create_order(symbol='BTCUSDT',
                                    side='BUY',
                                    type='MARKET',
                                    quoteOrderQty=40)
        orderqty = float(order['executedQty'])
        buyprice = float(order['fills'][0]['price'])
        in_position = True
        print(order)
    if in_position and (last_price > buyprice * 1.0005 or last_price < buyprice * 0.999): 
        order = client.create_order(symbol='BTCUSDT',
                                    side='SELL',
                                    type='MARKET',
                                    quantity=orderqty)
        in_position = False
        print(order)        

AND THIS IS MY CODE WITH INCLUDE MACD (dont working):

df = pd.DataFrame()
in_position = False
buyorders,sellorders = [],[]

def on_open(ws):
    ws.send(our_msg)
    
def on_message(ws,message):
    global df, in_position, buyorders, orderqty, buyprice#, sellorders
    out = json.loads(message)
    out = pd.DataFrame({'price':float(out['c'])}, index=[pd.to_datetime(out['E'],unit='ms')])
    df = pd.concat([df,out],axis=0)
    print(df)
    df = df.tail(15)
    last_price = df.tail(1).price.values[0]
    sma_15 = df.price.rolling(15).mean().tail(1).values[0]
    if not in_position and ta.trend.macd_diff(df.Close) > 0 \
            and ta.trend.macd_diff(df.Close) < 0 and last_price < sma_15:
        order = client.create_order(symbol='BTCUSDT',
                              side='BUY',
                              type='MARKET',
                              quoteOrderQty=40)
        orderqty = float(order['executedQty'])
        buyprice = float(order['fills'][0]['price'])
        in_position = True
        print(order)
    if in_position and (last_price > buyprice * 1.0005 or last_price < buyprice * 0.999): 
        order = client.create_order(symbol='BTCUSDT',
                                    side='SELL',
                                    type='MARKET',
                                    quantity=orderqty)
        in_position = False
        print(order)        

It would have been better to post one file with a comment line the following.

    if not in_position and last_price < sma_15:
# Replace 'if' above with that below and problem occurs.
#    if not in_position and ta.trend.macd_diff(df.Close).iloc[-1] > 0 \
#           and ta.trend.macd_diff(df.Close).iloc[-2] < 0 and last_price < sma_15:

Is this the only difference and everything else the same?

My reading of the your problem description is that the addition makes the condition always false. I would put a debug print above the if statement to see why.

1 Like

Your code has this condition:

not in_position and ta.trend.macd_diff(df.Close) > 0 and ta.trend.macd_diff(df.Close) < 0 and last_price < sma_15

Looking more closely: ta.trend.macd_diff(df.Close) > 0 and ta.trend.macd_diff(df.Close) < 0

ta.trend.macd_diff(df.Close) is never going to be both positive and negative at the same time.

1 Like

thanks you and the forum for directly answers probably this coding need more knowledge’s and i write b@#@ts. please can you tell me what i can write in correct code to add the macd?

THIS IS THE STARTUP CODE:

df = pd.DataFrame()
in_position = False
buyorders,sellorders = [],[]

def on_open(ws):
    ws.send(our_msg)
    
def on_message(ws,message):
    global df, in_position, buyorders, orderqty, buyprice#, sellorders
    out = json.loads(message)
    out = pd.DataFrame({'price':float(out['c'])}, index=[pd.to_datetime(out['E'],unit='ms')])
    df = pd.concat([df,out],axis=0)
    print(df)
    df = df.tail(45)
    last_price = df.tail(1).price.values[0]
    sma_45 = df.price.rolling(45).mean().tail(1).values[0]
    if not in_position and last_price < sma_45:
        order = client.create_order(symbol='BTCUSDT',
                                    side='BUY',
                                    type='MARKET',
                                    quoteOrderQty=40)
        orderqty = float(order['executedQty'])
        buyprice = float(order['fills'][0]['price'])
        in_position = True
        print(order)
    if in_position and (last_price > buyprice * 1.0004 or last_price > buyprice * 0.9996): 
        order = client.create_order(symbol='BTCUSDT',
                                    side='SELL',
                                    type='MARKET',
                                    quantity=orderqty)
        in_position = False
        print(order)        

You said “buy when the macd > 0 and dont buy when the macd < 0”, and that can be simplified to “buy when the macd > 0”.

1 Like

yes correct excuse this is my wrong to search solution on this code but never started with macd. i wont to do exactly what you say because this bot running perfectly when the prise going up. But when the price fail continues buy because if you have understand the logic this bot do live sma in last 45 secs but when the coin moving down and the sma just going up will continue to buy and will lost the transaction for this reason i wont to include the macd to stop buyng when the price moving down. If you can tell me how to do this i will appreciate

i have leave only this and again bot dosnt execute trades. if you can help me. Thanks in advance

df = df.tail(15)
    last_price = df.tail(1).price.values[0]
    sma_15 = df.price.rolling(15).mean().tail(1).values[0]
    if not in_position and ta.trend.macd_diff(df.Close).iloc[-1] > 0 and last_price > sma_15:
        order = client.create_order(symbol='BTCUSDT',
                              side='BUY',
                              type='MARKET',
                              quoteOrderQty=40)

Hello again i do one change but the bot again is not buy i add the method to do it most symply but nothing again. can you tell me now my wrong?

i add:

def applytechnicals(df):
    df['macd'] = ta.trend.macd_diff(df.Close)
    df.dropna(inplace=True)
 last_price = df.tail(1).price.values[0]
    sma_15 = df.price.rolling(15).mean().tail(1).values[0]
    if not in_position and ta.trend.macd_diff(df.Close) > 0 and last_price > sma_15:
        order = client.create_order(symbol='BTCUSDT',
                                    side='BUY',
                                    type='MARKET',
                                    quoteOrderQty=15)

please can you help me?

Hello again i do one change but the bot again is not buy i add the method to do it most symply but nothing again. can you tell me now my wrong?

i add:

def applytechnicals(df):
    df['macd'] = ta.trend.macd_diff(df.Close)
    df.dropna(inplace=True)
 df = df.tail(15)
 last_price = df.tail(1).price.values[0]
    sma_15 = df.price.rolling(15).mean().tail(1).values[0]
    if not in_position and ta.trend.macd_diff(df.Close) > 0 and last_price > sma_15:
        order = client.create_order(symbol='BTCUSDT',
                                    side='BUY',
                                    type='MARKET',
                                    quoteOrderQty=15)

please can you help me?

I’m going to suggest that you write the values and related data of the condition to a log file so that you can study it and see where you’re going wrong. That’s what I would do.

1 Like

Thanks for replying and sorry for the noob questions but i am a new. i have start to coding before 1 month and i know you will have laugh very mach with my coding skills but without a help i will finish in one year… If you can can you explain me how to write the values and related data of the condition to a log file?

At it’s simplest it’s just:

    last_price = df.tail(1).price.values[0]
    sma_15 = df.price.rolling(15).mean().tail(1).values[0]

    with open(log_path, 'a') as log_file:
        print('last_price is', last_price, file=log_file)
        print('sma_15 is', sma_15, file=log_file)
        print('ta.trend.macd_diff(df.Close).iloc[-1] is', ta.trend.macd_diff(df.Close).iloc[-1], file=log_file)

    if not in_position and ta.trend.macd_diff(df.Close).iloc[-1] > 0 and last_price > sma_15:
        with open(log_path, 'a') as log_file:
            print('buying', file=log_file)

        order = client.create_order(symbol='BTCUSDT',
                              side='BUY',
                              type='MARKET',
                              quoteOrderQty=40)
    else:
        with open(log_path, 'a') as log_file:
            print('not buying', file=log_file)
1 Like

Thanks you very mach i will try to work with it you are the best of the best support

I remake the code again i did it to include the macd but now the sell order dosnt work and the bot continue when buy without sell please any help and finish.


# Buy condition
    if not in_position and last_price > sma_60 and macd > 0:
        order = client.create_order(symbol='BTCUSDT',
                                    side='BUY',
                                    type='MARKET',
                                    quoteOrderQty=15)
        orderqty = float(order['executedQty'])
        buyprice = float(order['fills'][0]['price'])
        in_position = True
        buy_orders.append({'price': buyprice, 'quantity': orderqty})
        print("BUY ORDER: ", order)

    # Sell condition
    if in_position:
        current_price = client.get_symbol_ticker(symbol='BTCUSDT')['price']
        if float(current_price) >= buyprice*1.0005 or float(current_price) <= buyprice*0.9995:
            order = client.create_order(symbol='BTCUSDT',
                                        side='SELL',
                                        type='MARKET',
                                        quantity=orderqty)
            in_position = False
            sellprice = float(order['fills'][0]['price'])
            sell_orders.append({'price': sellprice, 'quantity': orderqty})
            print("SELL ORDER: ", order)

It looks like you’re selling if the current price is slightly above or slightly below the buy price. Is that correct?

Is in_position being set to False somewhere else?

Once again, I’m going to suggest that you write what you’re doing and the values and related data to a log file so that you can study it and see where you’re going wrong.

I try to do a log file but I never see it🙄. But becose I am on last step to sell I uploaded here… About the strategy yes I try to do when the last price >live sma and macd > 0 to buy and sell to give me back 0,05% I don’t care about the low profits this bot do many transactions every minute but cannot sell🙄

guys i did it thanks the forum for support especially the Mr Matthew Barnett i learn a lot of thing thanks all of you