dimanche 19 mai 2019

What is the best way to fix "IFs hell"?

I have a Deal class, that has several states : New, Bought, Finished, trend and crossing properties. Deal instance can change trend and crossing any time - depends of market condition.

Depend of current "trend", "crossing" and maybe other conditions deal can be processed in different ways

I tried Strategy and Chain of Responsibility patterns but my knowledge and experience isn't enough to do it correctly. And I'm not sure that made the right decision.

Now it works but it's a hell of ifs

async def check_deal(deal):

if deal.is_new():
    if deal.current_trend == UP_TREND and CROSSED_TOP_GREEN in deal.crossing:
        return await deal.create_order(CROSSED_TOP_GREEN)

    if deal.current_trend == FLAT_TREND and CROSSED_BOTTOM_ORANGE in deal.crossing:
        return await deal.create_order(CROSSED_BOTTOM_ORANGE)

    if deal.current_trend == DOWN_TREND and CROSSED_BOTTOM in deal.crossing:
        return await deal.create_order(CROSSED_BOTTOM)

if deal.is_bought() and not deal.candle_has_order:
    if deal.current_trend == UP_TREND and CROSSED_BOTTOM_GREEN in deal.crossing:
        return await deal.create_order(CROSSED_BOTTOM_GREEN)
    else:
        return await deal.update_deal()

    if deal.current_trend == DOWN_TREND and CROSSED_BOTTOM in deal.crossing:
        return await deal.create_order(CROSSED_BOTTOM)
    else:
        return await deal.update_deal()

else:
    return await deal.update_deal()

if deal.is_profitable() and len(deal.orders) == 1 :
    if deal.current_trend == UP_TREND  and CROSSED_TOP in deal.crossing:
        return await deal.trailing_enable(CROSSED_TOP)

    if deal.current_trend == FLAT_TREND and CROSSED_TOP_GREEN in deal.crossing:
        return await deal.trailing_enable(CROSSED_TOP_GREEN)

    if deal.current_trend == DOWN_TREND and CROSSED_BASIS in deal.crossing:
        return await deal.trailing_enable(CROSSED_BASIS)

if deal.is_profitable() and len(deal.orders) > 1:
    if deal.current_trend == UP_TREND and CROSSED_BASIS in deal.crossing:
        return await deal.trailing_enable(CROSSED_BASIS)

    if deal.current_trend == DOWN_TREND and  CROSSED_BOTTOM_GREEN in deal.crossing:
        return await deal.trailing_enable(CROSSED_BOTTOM_GREEN)

Aucun commentaire:

Enregistrer un commentaire