Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. 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. Now the recent curiosity on building Trading AI Agents.

Implementing Flip and Exrem Functions in Python Pandas Structure

2 min read

In AmiBroker Formula Language (AFL), Flip and ExRem are two useful functions often used in trading system development. Here is how the Flip and ExRem functions work, followed by a Python version:

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)

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls
  • 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 handy AFL functions, 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
Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. 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. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

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