Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Implementing Flip and Exrem Functions in Python Pandas Structure

2 min read

In (AFL), Flip and ExRem are two useful functions often used in trading system development. Let’s explore each of them:

Flip Function

The Flip function is used to toggle a variable between two states (True and False) based on two given conditions. This function is particularly useful for tracking the state of a trade or an indicator between two events, such as entry and exit signals in a trading strategy.

Syntax: Flip(Buy, Sell)

  • Buy and Sell are conditions (expressions that return True or False).
  • When Buy is True, Flip returns True.
  • Once Flip has flipped to True, it stays True until Sell becomes True.

Example Usage:

Buy = Cross(MA(Close, 5), MA(Close, 20)); // Buy when short MA crosses above long MA
Sell = Cross(MA(Close, 20), MA(Close, 5)); // Sell when long MA crosses above short MA
Buycontinue = Flip(Buy, Sell); // Buycontinue is True between Buy and Sell signals

In this example, Buycontinue will be True from the point where the Buy condition is met until the Sell condition occurs.

ExRem Function

The ExRem function stands for “Exclude Remnant” and is used to eliminate opposing signals within a given window. Essentially, it ensures that once a Buy or Sell signal is given, subsequent signals of the opposite type are ignored until an opposing signal is generated.

Syntax: ExRem(Buy, Sell)

  • Buy and Sell are again conditions.
  • ExRem removes remnant (extra) Buy signals that occur after the first Buy signal and before the first Sell signal. The same logic applies to Sell signals.

Example Usage:

Buy = Cross(MA(Close, 5), MA(Close, 20)); 
Sell = Cross(MA(Close, 20), MA(Close, 5));
Buy = ExRem(Buy, Sell); // Removes extra Buy signals after the first Buy and before the first Sell
Sell = ExRem(Sell, Buy); // Removes extra Sell signals after the first Sell and before the first Buy

Here, ExRem is used to filter out additional Buy signals that occur after an initial Buy and before the next Sell signal, and vice versa for Sell signals.

Both Flip and ExRem are powerful tools in the AFL toolbox, particularly useful for signal processing in trading strategies to manage entry and exit points more effectively. They help in simplifying the logic and avoiding unnecessary trades or signal overlaps.

Code Implementation of Flip and Exrem Functions in Pandas Dataframe

The provided code defines two functions, exrem and flip, both of which are designed to work with boolean series in a pandas DataFrame. These functions are modeled after the ExRem and Flip functions in AmiBroker Formula Language (AFL).

import pandas as pd

def exrem(series1, series2):
    """
    Mimics the ExRem function.
    After a True signal in series1, it ignores subsequent True signals in series2 until a new True signal in series1.
    """
    in_position = False
    clean_series1 = pd.Series(False, index=series1.index)

    for i in range(len(series1)):
        if series1.iloc[i] and not in_position:
            clean_series1.iloc[i] = True
            in_position = True
        elif series2.iloc[i] and in_position:
            in_position = False

    return clean_series1

def flip(series1, series2):
    """
    Mimics the Flip function.
    Toggles a state between True and False based on True signals in series1 and series2.
    """
    state = False
    flipped_state = pd.Series(False, index=series1.index)

    for i in range(len(series1)):
        if series1.iloc[i]:
            state = True
        elif series2.iloc[i]:
            state = False
        flipped_state.iloc[i] = state

    return flipped_state

# Example DataFrame
data = {'Buy': [False, True, False,True,False, False, True, True, False, False],
        'Sell': [False, False, False, False, True, True, False, False, True, True]}
df = pd.DataFrame(data)

# Apply the exrem function
df['ExremData'] = exrem(df['Buy'], df['Sell'])

# Apply the flip function
df['FlipData'] = flip(df['Buy'], df['Sell'])

print(df)

Output

    Buy   Sell  ExremData  FlipData
0  False  False      False     False
1   True  False       True      True
2  False  False      False      True
3   True  False      False      True
4  False   True      False     False
5  False   True      False     False
6   True  False       True      True
7   True  False      False      True
8  False   True      False     False
9  False   True      False     False
Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Voice Commands to Trade on OpenAlgo Platform Using Google…

Trading platforms are always getting better by using the newest technologies to make things easier and more efficient for users. A great example of...
Rajandran R
5 min read

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

How to Place Orders Concurrently using ThreadPoolExecutor – Python…

Creating concurrent orders is essential for active traders, especially those handling large funds, as it allows for executing multiple trade orders simultaneously, thereby maximizing...
Rajandran R
2 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More