Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.
Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.
Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.
Trality has been discontinued as of 31.7.2023. Thank you to all our users 💙.

How to Use ChatGPT to Convert Pine Script to Python Trading Bots with Trality


24 May 20236 min read

Table of contents

As a trading enthusiast, you've probably come across Pine Script at some point in your trading journey.

For the uninitiated, however, Pine Script is a programming language created by TradingView and it's used specifically for financial trading and analysis. It's also a powerful Python-based language that allows traders to create custom indicators and algo trading strategies that can be used on their platform.

Many traders would like to convert Pine scripts to Python and use the freely available Pine Script resources on other platforms, but are inhibited from doing so by the lack of Pine script to Python converter tools available.

In this guide, we will walk you through how to convert a Pine script indicator on TradingView called Fibonacci Levels Based on Supertrend" created by MUQWISHI using ChatGPT, a powerful language model that uses advanced machine learning techniques to understand and interpret natural language. ChatGPT can be used to breakdown code to understand what is happening in the indicators and strategies we come across, even for the most unexperienced of traders.

Converting TradingView’s Pine Script to Natural Language

We open a chat with ChatGPT and prompt ChatGPT using GPT-3 with the following prompt and append the TradingView script below this prompt.

Convert the following Pine Script code into natural language.
- provide me with as much context as possible about the trading strategy or indicator
- declare whether it's a trading strategy or indicator
- including desired indicators and timeframes in the description
- this is the structure of Pine Script:
 - version declaration: The script starts with a declaration of the Pine Script version (e.g., //@version=4).
 - indicator or strategy declaration: This line specifies whether you're creating an indicator or a strategy (e.g., indicator("My Indicator", shorttitle="MI", overlay=true) or strategy("My Strategy", shorttitle="MS", overlay=true)).
 - input declaration: Define user inputs for your script (e.g., length = input(14, minval=1, title="Length")).
 - variable declaration and calculation: Declare and calculate variables used in the script (e.g., sma = sma(close, length)).
 - plotting and displaying: Plot indicators, lines, or other visual elements on the chart (e.g., plot(sma,, linewidth=2)).

This gives us the following as an output:

This Pine Script code is for a trading indicator called "Supertrend-Fib," which combines the Supertrend indicator with Fibonacci levels. The script allows users to customize various settings, such as the ATR length, factor, line and label styles, and Fibonacci levels. It then calculates the Supertrend and Fibonacci levels based on these inputs and displays them on the chart.

Here is a description of the code in natural language:
The input parameters for the Fibonacci levels are defined, such as applying the levels only to the last Supertrend direction, background transparency, line transparency, and color for each Fibonacci level.
The Supertrend indicator is calculated using the given ATR Length and Factor.
A function to calculate the Fibonacci levels is defined using the Supertrend values.
The entered Fibonacci levels are calculated and sorted based on the trend direction.

Now that you have a natural language description of your Pine Script code, you can use it to optimize your trading strategy. With the code now in a more intuitive and easy-to-understand format, you can quickly and easily identify areas for improvement or tweak your strategy for better performance. You could also do some additional cleaning by removing any lines that refer to customizing lines or other graphical elements.

At this point, you could also define your own strategy appended to the prompt below. This involves identifying the conditions under which the bot should execute trades. For example, you might want the bot to buy a crypto when its price drops below a certain level or sell a crypto when its price rises above a certain level.

Converting Pine Script’s Natural Language to Python Bot Code

To define your trading strategy, you can simply describe it in natural language, similar to the natural language output above.

For example, you could say, “I want the bot to buy ETH when its price drops below $1600 and sell it when it rises above $2000.” ChatGPT would then convert this natural language of the Pine script into Python code that can be used by Trality.

Convert the following natural language instructions directly into a Trality Python bot.
- strip all plot customization from the bot. Ignore any directions about adding colors or styles.
- the bot does not need any imports from a fictional "Trality" library.
- add a scheduler around modules and group modules by the time interval chart. The scheduler is in this format @schedule(interval="${interval}", symbol="${SYMBOL}") with the chart interval being inserted in ${interval} and the symbol pair being inserted in ${SYMBOL} . Only cryptocurrency asset pairs can be used and they must be a pair that is able to be traded using the API from Coinbase/Binance/Kraken/Bitpanda. You are allowed to have up to 3 schedulers. Modules may not need a scheduler if they are being passed data from another module with a scheduler. Do not have multiple schedulers of the same ${interval}, these modules can be joined or passed data and state.
- we start the script with defining an initializing function:  def initialize(state): where we can place variables that can function as a global variable in the bot. The variables are formatted as state.${variable} = ${value}. State is a finite resource, do not load up all the data from "data" into state. If nothing needs to initialize you can skip this function. Initialize does not need to be wrapped in a scheduler.
- data is passed between the modules using the parameter "data" for the asset data and "state"
- for each python module add a doc-string to describe what should be happening in that module.
- Trality's data object is a dictionary with the following keys: ['open', 'high', 'low', 'close', 'volume'] that gets called as a parameter to any module that needs it. Data is accessed as a dictionary with data($key) that gives a list object. For example if you wanted to get the last close price you would put data["close"][-1]
- plotting is done by with PlotScope.root(data.symbol): where the plot follows plot_line("${name}",${value}). Plot_line only accepts a string and a set of numerical values
- indicators are used by manipulating Trality's data object in the order data.${indicator}(${parameters}). You do not need to save the indicator period length in state. You can put them directly in the parameters in the format \${parameter}=\${value} . When creating an indicator save it under a Python friendly indicator name. For example: RSI = data.RSI(14)
- orders can be made with order_market_amount(symbol="${symbol}", amount=${order_amount}) for simple instantly filled orders or order_limit_amount(symbol="${symbol}, amount=${amount}" for limit orders. For anything else you can make a custom order using order_amount(symbol=${symbol},amount=${amount}, stop_price=${stop_price},limit_price=${limit_price}). If selling, we can also completely close positions with close_position(${symbol}). When using orders that are not market, we must refresh them to view their status using refresh_orders(). We can also check on open orders using query_open_orders().
- use 80% of the portfolio for a buy order. We can query Trality's portfolio using query_portfolio. This gives us the portfolio object with keys ["quoted","balances","fee_balances","cum_fee_quoted","portfolio_value","locked_amount","realized_pnl","unrealized_pnl","excess_liquidity_quoted","open_positions","closed_positions","open_order_ids","last_buy_order_times","last_sell_order_times","number_of_trades","number_of_offsetting_trades","number_of_winning_trades"]. We can get the use excess_liquidity_quoted to find our available free balance.

Deploying Python Bot Code on Trality

After having the Pine script converted to Python code, it is necessary to test before attempting to deploy the bot on the Trality platform.

Fortunately, Trality offers a user-friendly interface that makes it simple to create, test, and deploy your Python bot. Running a backtest will quickly identify any errors resulting from lines that need to be tweaked. For help with this, you can pop over to Trality’s helpful community on Discord. Lastly, you need to ensure that you’ve subscribed to a Trality subscription level that corresponds to the intervals used in the bot to ensure that it runs smoothly. The free tier of Trality allows you to run intervals 1 hour and larger with a trading volume of $5,000 per month.

Once the bot is deployed, you can monitor its performance closely and make adjustments to the bot as needed, optimizing it with Trality’s real-time performance metrics and charts to help you track the bot's profitability.

Parting Words

While this guide accommodates traders who might not have an understanding of Pine script or Python, we highly recommend that users familiarize themselves with the fundamentals of Python to take full advantage of Trality's trading bot features.

And, as always, you can reach out at any time with questions or comments via Discord (mentioned above), our social media channels, or by e-mail (support [at] trality [dot] com).

Happy coding!