Create strategies codes with ChatGPT for ProRealTime
Forums › ProRealTime English forum › General trading discussions › Create strategies codes with ChatGPT for ProRealTime
- This topic has 76 replies, 18 voices, and was last updated 4 months ago by GraHal.
-
-
05/12/2023 at 10:43 AM #214589
This topic will focus on the programming assistance that ChatGPT IA can give us.
I use ChatGPT almost daily, it works very well.
Here is an interesting first prompt that give good results:
I need some help generating codes for the trading platform ProRealTime. Its programming language is ProBuilder (also known as ProRealCode).
Variables names can only contain letters and numbers and always starting with a letter.
Do not use underscore for variables names.
Variables names are not case sensitive.
Variables can’t be set UNDEFINED, a null value is 0.
Instructions are reserved keywords and can’t be used for variables names._To set a pending buy stop order at price X, price must be below the price X, use the instruction: BUY AT X STOP
_To add a trailing stop of X points, use the instruction: SET STOP PTRAILING X
_The upper bollinger band of period X and deviation Y is calculated with the instruction: AVERAGE[X]+STD[X]*Y
_To get the point value in money use the constant: POINTVALUE
_To get the point size use the constant: POINTSIZE
_To get the average price of current positions use: POSITIONPRICE
_To get profit in money of current positions use this snippet:
floatingprofit = (((close-positionprice)*pointvalue)*countofposition)/pointsize //actual trade gains
_ Equal comparison is made with a single equal character.example of prompt:
_ code a strategy that: buy when supertrend cross under the price and sellshort when supertrend cross over, takeprofit is 50 points and stoploss is 25 points.
The resulting code is below:defparam cumulateOrders = false
// Setting the parameters for the supertrend indicator
Length = 14
Multiplier = 3indicator1 = supertrend[Multiplier,Length]
if close crosses over indicator1 then
buy at market
endifif close crosses under indicator1 then
sellshort at market
endifset target pprofit 50
set stop ploss 25Now let’s start programming, answer “YES” and nothing else if you are ready and wait for my next prompt.
With more hindsight and experience, I know today that to make him realize codes for ProRealTime is possible, if you use the right keywords, the right instructions, what we call a “prompt”.
With a lot of trial and error, I managed to create a “specification” (the initial prompt above) that allows to fix some programming errors that it could commit after a request (see more explanation in the following post).PREREQUISITE: Subscription to ChatGPT PLUS (v4) to get relevant results (currently 20$/month). This version being much more powerful, results obtained with an earlier version will not be integrated in our prompts searches.
If you want, let’s all try to create a coherent set of commands and prompts to allow the community to benefit from it, and then to collaborate as well, creating a virtuous circle of knowledge for this new fabulous subject that is generative AI, and associated with our favorite trading platform! 🙂
PLEASE RESPECT THE LANGUAGE OF THE TOPIC: all discussions should be written in English, posts in other languages will be deleted.
Total of 15 users thanked author for this post. Here are last 10 listed.
05/12/2023 at 10:43 AM #214591TRADING STRATEGY WITH CHATGPT, EXPLANATION: (please read carefully this post)
Upon opening a new chat with ChatGPT, copy/paste the initial prompt contained in the corresponding attachment (either the one for a strategy or the one for an indicator). Then press ENTER.
Then you can start making requests.Why this initial prompt?
It allows you to start a discussion by defining a lexical field and a template for what will be asked later.Example of a prompt for the creation of a “simple” strategy:
code a strategy that: buy when rsi cross above oversold zone and price is above supertrendThe code returned should be of this type:
12345678910111213141516defparam cumulateOrders = false// Define parameters for RSI and SuperTrendrsiLength = 14rsiOversold = 30stLength = 10stMultiplier = 3// Calculate the RSI and SuperTrendrsiValue = rsi[rsiLength](close)stValue = supertrend[stMultiplier,stLength]// Define the trading conditionsif rsiValue crosses over rsiOversold and close > stValue thenbuy at marketendifAs you can see, the code is correct, with no instruction or syntax errors.
Example of another prompt:
code a strategy that: set buy pending order at bollinger upper band, add a takeprofit, add a trailing stop
resulting code is:
1234567891011121314151617181920defparam cumulateOrders = false// Setting the parameters for the Bollinger BandLength = 20Deviations = 2// Define the Bollinger BandsUpperBand = BollingerUp[Length, Deviations]// Define the take profit and trailing stop levels (in points)TakeProfitLevel = 50TrailingStopLevel = 25if not onmarket thenif close crosses under UpperBand thenbuy stop at UpperBand next bar at marketset target pprofit TakeProfitLevelset stop ptrail TrailingStopLevelendifendifHere the code is incorrect, it does not know how to correctly place a BUY STOP order, the definition of the high bollinger is incorrect (syntax), the trailing stop instruction is also incorrect.
In case of detection of an incorrect code, I modify the initial prompt in order to give it more knowledge for the next uses. So in this case I add to the initial prompt file, the following elements:- To set a pending buy stop order at price X, price must be below the price X, use the instruction: BUY AT X STOP
- To add a trailing stop of X points, use the instruction: SET STOP PTRAILING X
- The upper bollinger band of period X iand deviation Y is calculated with the instruction: AVERAGE[X]+STD[X]*Y
I run the same prompt again for my strategy and the resulting code is:
123456789101112131415161718192021defparam cumulateOrders = false// Setting parameters for the Bollinger Bandlength = 20deviation = 2// Setting parameters for takeprofit and trailing stoptakeProfit = 50trailingStop = 10// Calculate Bollinger upper bandupperBand = average[length] + std[length]*deviation// If price is lower than the upper band, set a pending buy stop order at the upper bandif close < upperBand thenbuy at upperBand stopendif// Setting takeprofit and trailing stopset target pprofit takeProfitset stop ptrailing trailingStopWe can see that he has perfectly understood the lesson!
In conclusion, the initial prompt shared here in the attached text file will have to be modified as we test and as you discover, to get a perfect understanding of the ProBuilder language and thus allow it to generate code with a minimum of possible errors.
Other examples of prompts:
- code a strategy that: buy when stochastic cross above oversold zone and price is above both moving averages of periods 50 and 200 : https://www.prorealcode.com/topic/create-strategies-codes-with-chatgpt-for-prorealtime/#post-214593)
- code a strategy that: buy with market orders at previous donchian high and sellshort with market orders at previous donchian low : https://www.prorealcode.com/topic/create-strategies-codes-with-chatgpt-for-prorealtime/#post-214594)
- code a strategy that: buy at market each time the price cross under the lower bollinger bands, cumulate orders is true, close orders when profit is 10 in money : https://www.prorealcode.com/topic/create-strategies-codes-with-chatgpt-for-prorealtime/#post-214605
- code a strategy that: buy at market on rebound of a strong bullish trend, use a trend following indicator to determine trend and an oscillator for timing of entries, add a trailing stop, cumulate orders is true : https://www.prorealcode.com/topic/create-strategies-codes-with-chatgpt-for-prorealtime/#post-214608
- code a strategy that: buy at market each X points, in an uptrend, cumulate orders is true, add a trailing stop : https://www.prorealcode.com/topic/create-strategies-codes-with-chatgpt-for-prorealtime/#post-214611
- create a strategy for: buy at market when a short term hull average change from red to green, in a strong uptrend, add a takeprofit of X and a stoploss of Y : https://www.prorealcode.com/topic/create-strategies-codes-with-chatgpt-for-prorealtime/#post-214613
-> REMEMBER TO USE THE INITIAL PROMPT OF THE FIRST POST TO INITIATE A NEW DISCUSSION WITH CHATGPT <-
ATTACHED TEXT FILE IS THE CURRENT VERSION OF THE ABOVE STRATEGY PROMPT
9 users thanked author for this post.
05/12/2023 at 10:52 AM #214593code a strategy that: buy when stochastic cross above oversold zone and price is above both moving averages of periods 50 and 200
Sure, here is a ProBuilder code that buys when the Stochastic indicator crosses above the oversold zone and the price is above both the moving averages of periods 50 and 200.
123456789101112131415161718192021defparam cumulateOrders = false// Setting parameters for the Stochastic indicator and oversold levelLength = 14K = 3D = 3oversold = 20// Setting the periods for the moving averagesmaPeriod50 = 50maPeriod200 = 200// Calculate Stochastic and moving averagesstoch = stochastic[Length,K,D]ma50 = average[maPeriod50]ma200 = average[maPeriod200]// Buy when Stochastic crosses above oversold level and price is above both moving averagesif (stoch crosses over oversold) and (close > ma50) and (close > ma200) thenbuy at marketendifThis code will generate a buy order at the market price when the Stochastic indicator crosses above the defined oversold level (20 in this case) and the closing price is above both the 50-period and 200-period moving averages.
Please note that this code does not include any conditions for selling or closing the position. You might want to add those depending on your trading strategy.
05/12/2023 at 10:55 AM #214594code a strategy that: buy with market orders at previous donchian high and sellshort with market orders at previous donchian low
Sure, here is a ProBuilder code that buys at the previous Donchian high and sells short at the previous Donchian low using market orders.
123456789101112131415161718defparam cumulateOrders = false// Setting the parameters for the Donchian channelLength = 20// Calculate the Donchian channelDonchianHigh = highest[Length](high)DonchianLow = lowest[Length](low)// If the close price is above the previous Donchian high, place a market buy orderif close > DonchianHigh[1] thenbuy at marketendif// If the close price is below the previous Donchian low, place a market sell short orderif close < DonchianLow[1] thensellshort at marketendifIn this code, the previous Donchian high and low are represented by
DonchianHigh[1]
andDonchianLow[1]
, respectively. If the close price is above the previous Donchian high, a market buy order is placed. If the close price is below the previous Donchian low, a market sell short order is placed.Please note that this code does not include any conditions for closing the positions. You might want to add those depending on your trading strategy.
1 user thanked author for this post.
05/12/2023 at 1:05 PM #214605code a strategy that: buy at market each time the price cross under the lower bollinger bands, cumulate orders is true, close orders when profit is 10 in money
Here is the ProRealTime code for your requested strategy:
12345678910111213141516171819defparam cumulateOrders = true // Cumulating orders is enabled// Setting the parameters for the Bollinger Bands indicatorLength = 20 // This is a standard setting, but you might adjust this to suit your strategyDeviation = 2 // Again, this is a standard setting// Calculating the lower Bollinger BandLowerBand = average[Length] - (Deviation * std[Length])if close crosses under LowerBand thenbuy at marketendif// Calculating the profit in money for current positionsFloatingProfit = (((close - POSITIONPRICE) * POINTVALUE) * countofposition) / POINTSIZEif FloatingProfit >= 10 thensell at marketendifThis strategy buys at market each time the price crosses under the lower Bollinger band, and closes orders when the profit in money of the current positions is greater or equal to 10. It also cumulates orders as per your requirement. Please adjust the parameters of the Bollinger Bands as required for your strategy.
1 user thanked author for this post.
05/12/2023 at 1:14 PM #214608TIP: You can also be more “generic” to let the IA determines itself what indicators to choose for your strategy:
code a strategy that: buy at market on rebound of a strong bullish trend, use a trend following indicator to determine trend and an oscillator for timing of entries, add a trailing stop, cumulate orders is true
To code your strategy, I’ll use the Moving Average Convergence Divergence (MACD) as the trend-following indicator and the Relative Strength Index (RSI) as the oscillator to time entries. The MACD shows the relationship between two moving averages of a security’s price, while the RSI compares the magnitude of recent gains and losses over a specified time period to measure speed and change of price movements.
123456789101112131415161718192021defparam cumulateOrders = true // Cumulating orders is enabled// Setting the parameters for the MACD and RSI indicatorsMACDLengthFast = 12MACDLengthSlow = 26MACDLengthSignal = 9RSILength = 14OverSold = 30 // RSI level for oversold conditions// Calculating the MACD and RSImacdValue = ExponentialAverage[MACDLengthFast](close) - ExponentialAverage[MACDLengthSlow](close)signalValue = ExponentialAverage[MACDLengthSignal](macdValue)rsiValue = RSI[RSILength](close)if macdValue > signalValue and rsiValue crosses over OverSold thenbuy at marketendif// Set a trailing stop of X pointsX = 15 // Define your own value for XSET STOP PTRAILING XThis strategy buys at the market on a rebound from an oversold condition (as indicated by the RSI crossing over the oversold threshold) during a bullish trend (as indicated by the MACD line being above the signal line). A trailing stop is also set. Please adjust the parameters and thresholds as required for your strategy.
05/12/2023 at 3:02 PM #214611code a strategy that: buy at market each X points, in an uptrend, cumulate orders is true, add a trailing stop
Sure, here is a basic code for the strategy you’ve requested. You will need to adjust the value of X and set the conditions that define an uptrend based on your preferred indicators. I’ve used a simple moving average for illustration purposes.
123456789101112131415161718192021222324252627defparam cumulateOrders = true// Define the points step for buyingX = 10// Define the moving average period for trendmaPeriod = 20// Calculate the moving averageavg = average[maPeriod]// Define the trailing stop valuetrailingStop = 15// In each bar, check if the price has moved X points from the last buy priceif barindex > 1 and close > lastBuyPrice + X * pointsize and close > avg thenbuy at marketlastBuyPrice = closeset stop ptrailing trailingStopendif// At the start of the strategy, we buy once at market priceif barindex = 1 thenbuy at marketlastBuyPrice = closeset stop ptrailing trailingStopendifIn this example,
lastBuyPrice
is a variable that tracks the price of the last buy order. The strategy first checks if the price has moved X points above this price and that the current close is above the moving average. If these conditions are met, it places a buy order at the market price, updateslastBuyPrice
, and sets a trailing stop. At the start of the strategy, it also places a buy order, setslastBuyPrice
, and sets a trailing stop.Remember to adjust the moving average period (
maPeriod
), the points step (X
), and the trailing stop value (trailingStop
) to fit your strategy.1 user thanked author for this post.
05/12/2023 at 3:14 PM #214613create a strategy for: buy at market when a short term hull average change from red to green, in a strong uptrend, add a takeprofit of X and a stoploss of Y
Sure, I’ll consider a strong uptrend to be when the long-term Hull Moving Average (HMA) is also increasing. I’ll use 21 periods for the long-term HMA, but you can adjust this to your liking. We’ll use a change from decreasing (red) to increasing (green) in the short-term HMA to trigger the buy condition.
Let’s denote
X
as the take profit target andY
as the stop loss limit.Here is the strategy:
1234567891011121314151617// Setting the parameters for the Hull Moving AveragesShortTermLength = 9LongTermLength = 21TakeProfitX = 50 // adjust this to your likingStopLossY = 25 // adjust this to your liking// Calculate the Hull Moving AveragesShortTermHMA = HullAverage[ShortTermLength](close)LongTermHMA = HullAverage[LongTermLength](close)// Identify when the ShortTermHMA changes from decreasing (red) to increasing (green) and LongTermHMA is also increasingif (ShortTermHMA[1] < ShortTermHMA[2] and ShortTermHMA > ShortTermHMA[1]) and LongTermHMA > LongTermHMA[1] thenbuy at marketset target pprofit TakeProfitXset stop ploss StopLossYendifIn this code,
ShortTermHMA[1] < ShortTermHMA[2]
andShortTermHMA > ShortTermHMA[1]
checks if the short-term HMA is now increasing after decreasing, signaling a change from red to green.LongTermHMA > LongTermHMA[1]
checks if the long-term HMA is increasing, which indicates a strong uptrend. When all these conditions are met, the code executes a buy at market order and sets the take profit and stop loss levels.2 users thanked author for this post.
05/12/2023 at 3:33 PM #214619Now, if you want to use a custom indicator, you have to define its code for being used by ChatGPT.
Firstly, give the indicator a precise name, so that you can refer to it later in your chat. For this example, I’m using the ALPHATREND indicator from the library.
Here is my prompt to introduce the custom indicator:
let’s define the custom indicator “ALPHATREND” with the below code:
and paste the code just after that sentence.
Now I’m asking a strategy to use it with the below prompt:
code a strategy that: buy at market on new uptrend detection of ALPHATREND indicator
Sure, given the definition of the ALPHATREND indicator you provided earlier, we can create a strategy that buys at market when a new uptrend is detected.
An uptrend is detected when the ALPHATREND changes color from red to green, i.e., when the ALPHATREND value is increasing.
Here’s the corresponding code:
123456789101112131415161718192021222324252627// --- settingsAP = 14 //Common Periodcoeff = 1 //Multiplier// --- end of settingsif (MoneyFlowIndex[ap]>=50) thenmagic=Low[0]-AverageTrueRange[ap](close)*coeffendifif (MoneyFlowIndex[ap]<50) thenmagic=High[0]+AverageTrueRange[ap](close)*coeffendifif (MoneyFlowIndex[ap]>=50 and magic<magic[1]) thenmagic=magic[1]endifif (MoneyFlowIndex[ap]<50 and magic>magic[1]) thenmagic=magic[1]endifAlphaTrend = magic// Buy at market when a new uptrend is detectedif AlphaTrend[1] < AlphaTrend[2] and AlphaTrend > AlphaTrend[1] thenbuy at marketendif1 user thanked author for this post.
05/12/2023 at 8:12 PM #214634ChatGPT is unbelievable! I had to teach the thing about the timeframe instruction LOL but now it can even write multitimeframe strategies. Here’s a short prompt of a simple strategy:
Write a simple strategy in the 5 min timeframe that goes long at market if the close croses over the 10 period EMA of the 1 hour timeframe and goes short
if the price crosses under the 10 period EMA of the 1 hour timeframe. To trade the 5 minute timeframe you must use the instruction timeframe(5 minutes).
To trade in the 1 hour timeframe you must use timeframe(1 hour).ChatGPT: Certainly! Here’s an example of a strategy that goes long at market if the close crosses over the 10-period EMA of the 1-hour timeframe and goes short
if the price crosses under the 10-period EMA of the 1-hour timeframe, all within the 5-minute timeframe:12345678910111213141516171819defparam cumulateOrders = false// 5-minute timeframetimeframe(5 minutes)// 1-hour timeframetimeframe(1 hour)ema10 = average[10](close)// Go long if close crosses over 10-period EMA of 1-hour timeframetimeframe(5 minutes)if close crosses over ema10 thenbuy at marketendif// Go short if close crosses under 10-period EMA of 1-hour timeframeif close crosses under ema10 thensellshort at marketendifIn this code, the strategy is implemented within the 5-minute timeframe. It starts by switching to the 1-hour timeframe to calculate the 10-period EMA (
ema10
)
based on the close price. Then, it switches back to the 5-minute timeframe and executes the buy or sellshort orders based on the cross of the close price with
the 10-period EMA.3 users thanked author for this post.
05/15/2023 at 12:58 PM #214735fantastic thread ^^ thanks
05/17/2023 at 4:51 PM #214856This is some real interesting stuff. Accurate and descriptive Prompting is key for success with AI.
We did a video on creating a ProRealTime algo with ChatGPT already back in December 2022 and have made a couple of more since.Here’s the code of the Daily Gold algo we created back then
123456789101112131415161718threshold = 10atr = AverageTrueRange[14]If (currentMonth >= 6) And (currentMonth <= 9) And (atr > threshold) And (rsi < 30) Then// It's summer, ATR is above the threshold, and RSI is oversold, so we enter a long tradeBuy 1 contract at marketElsIf (currentMonth >= 12) Or (currentMonth <= 3) And (atr > threshold) And (rsi > 70) Then// It's winter, ATR is above the threshold, and RSI is overbought, so we enter a short tradeSell 1 contract at marketEndIfIf (longOnMarket) And (rsi > 70) then//The position is long, and RSI is overbought, so we exit the tradesell at marketElsIf (shortOnMarket) And (rsi < 30) Then// The position is short, and RSI is oversold, so we exit the tradeexitshort at marketEndIfAnd here’s the video if you want to watch that: https://www.youtube.com/shorts/uwx4Q_xuH_Q
2 users thanked author for this post.
05/19/2023 at 9:53 AM #214912Thanks, but there is an error at line 9, to enter a short trade, it should be: SELLSHORT.
In the video, you asked the IA to create a code in “basic” language, so it would need a lot of adjustements to make it work properly in ProRealTime.
The aim here is to make it compatible straight away for ProBuilder programming, by feeding the prompt with all necessary requirements. The idea is to make it user friendly for non-programmers.
05/25/2023 at 7:56 AM #215146PREREQUISITE: Subscription to ChatGPT PLUS (v4) to get relevant results (currently 20$/month). This version being much more powerful, results obtained with an earlier version will not be integrated in our prompts searches.
I tried my best to
a. teach (instruct) GPT-3.5 (which should be version 4) but it does not allow for that, for what I can see.
b. use the taught examples so far in this topic. They don’t work at all.ChatGPT itself (experience is mainly based on V3) is more than superb. It is freighting, so good. With this remark, I only try to make clear that I think I know how to deal with it, and how to converse with it, so constructive results come from it.
… but the results are only for yourself …
Unless someone teaches me how to do it after all, it is my suggestion that the $20 (which is ex VAT) is wasted. But please notice that I base this on the superb results with ChatGPT (which is V3). Officially V4 is infinitely better, with the notice that V4 is hardly usable at this moment (too few messages allowed per time period). The 3.5 payed version should do the same (??). Anyway, this is from V4 :
PS: Why can’t I see the instructs given by my colleagues ?
I refer to : instructs given to ChatGTP (in any version).GPT-4 :
As an AI model, I don’t have the ability to remember specific interactions or instructions from previous conversations. Each conversation with me doesn’t have a memory of past sessions. I don’t store personal data from the questions you ask me unless explicitly provided in the course of our conversation. As soon as the conversation ends, I forget it.
So if your colleagues gave instructions to me in a different session or version, I won’t be able to recall or refer to those instructions in our current conversation. This is part of OpenAI’s commitment to privacy and data security.
If you need to follow up on a previous topic or set of instructions, you would need to provide the relevant information again in our current conversation. I’m here to help answer questions and provide information based on the data I was trained on up until September 2021.
I really like to hear that I am wrong …
1 user thanked author for this post.
05/25/2023 at 8:10 AM #215148You have to create your own session with ChatGPT Plus (v4) in order to be able to use the prompts I gave in the first posts of the topic.
V3.5 is not sufficient to get good (and accurate) results to make it work properly for ProBuilder coding.
-
AuthorPosts
Find exclusive trading pro-tools on