Create strategies codes with ChatGPT for ProRealTime

Viewing 15 posts - 1 through 15 (of 88 total)
  • Author
    Posts
  • #214589 quote
    Nicolas
    Keymaster
    Master

    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 = 3

    indicator1 = supertrend[Multiplier,Length]

    if close crosses over indicator1 then
    buy at market
    endif

    if close crosses under indicator1 then
    sellshort at market
    endif

    set target pprofit 50
    set stop ploss 25

    Now 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.

    GraHal, JADINVEST, ZeroCafeine and 12 others thanked this post
    automatic-trading-chatgpt-prorealtime-1.png automatic-trading-chatgpt-prorealtime-1.png
    #214591 quote
    Nicolas
    Keymaster
    Master

    TRADING 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 supertrend

    The code returned should be of this type:

    defparam cumulateOrders = false 
    
    // Define parameters for RSI and SuperTrend
    rsiLength = 14
    rsiOversold = 30
    stLength = 10
    stMultiplier = 3
    
    // Calculate the RSI and SuperTrend
    rsiValue = rsi[rsiLength](close)
    stValue = supertrend[stMultiplier,stLength]
    
    // Define the trading conditions
    if rsiValue crosses over rsiOversold and close > stValue then
      buy at market 
    endif

    As 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:

    defparam cumulateOrders = false 
    
    // Setting the parameters for the Bollinger Band
    Length = 20
    Deviations = 2
    
    // Define the Bollinger Bands
    UpperBand = BollingerUp[Length, Deviations]
    
    // Define the take profit and trailing stop levels (in points)
    TakeProfitLevel = 50
    TrailingStopLevel = 25
    
    if not onmarket then
      if close crosses under UpperBand then
        buy stop at UpperBand next bar at market
        set target pprofit TakeProfitLevel
        set stop ptrail TrailingStopLevel
      endif
    endif

    Here 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:

    defparam cumulateOrders = false 
    
    // Setting parameters for the Bollinger Band
    length = 20
    deviation = 2
    
    // Setting parameters for takeprofit and trailing stop
    takeProfit = 50
    trailingStop = 10
    
    // Calculate Bollinger upper band
    upperBand = average[length] + std[length]*deviation
    
    // If price is lower than the upper band, set a pending buy stop order at the upper band
    if close < upperBand then
        buy at upperBand stop
    endif
    
    // Setting takeprofit and trailing stop
    set target pprofit takeProfit
    set stop ptrailing trailingStop

    We 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:

    1. 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)
    2. 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)
    3. 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
    4. 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
    5. 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
    6. 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 

    pableitor, Meta Signals Pro, corsica and 6 others thanked this post
    ProRealTime-strategy-prompt-1.txt
    #214593 quote
    Nicolas
    Keymaster
    Master

    code 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.

    defparam cumulateOrders = false 
    
    // Setting parameters for the Stochastic indicator and oversold level
    Length = 14
    K = 3
    D = 3
    oversold = 20
    
    // Setting the periods for the moving averages
    maPeriod50 = 50
    maPeriod200 = 200
    
    // Calculate Stochastic and moving averages
    stoch = stochastic[Length,K,D]
    ma50 = average[maPeriod50]
    ma200 = average[maPeriod200]
    
    // Buy when Stochastic crosses above oversold level and price is above both moving averages
    if (stoch crosses over oversold) and (close > ma50) and (close > ma200) then
        buy at market 
    endif
    

    This 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.

    pableitor and gonzocorp thanked this post
    #214594 quote
    Nicolas
    Keymaster
    Master

    code 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.

    defparam cumulateOrders = false 
    
    // Setting the parameters for the Donchian channel
    Length = 20
    
    // Calculate the Donchian channel
    DonchianHigh = highest[Length](high)
    DonchianLow = lowest[Length](low)
    
    // If the close price is above the previous Donchian high, place a market buy order
    if close > DonchianHigh[1] then
        buy at market 
    endif
    
    // If the close price is below the previous Donchian low, place a market sell short order
    if close < DonchianLow[1] then
        sellshort at market 
    endif
    

    In this code, the previous Donchian high and low are represented by DonchianHigh[1] and DonchianLow[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.

    gonzocorp thanked this post
    #214605 quote
    Nicolas
    Keymaster
    Master

    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

    Here is the ProRealTime code for your requested strategy:

    defparam cumulateOrders = true // Cumulating orders is enabled
    
    // Setting the parameters for the Bollinger Bands indicator
    Length = 20 // This is a standard setting, but you might adjust this to suit your strategy
    Deviation = 2 // Again, this is a standard setting
    
    // Calculating the lower Bollinger Band
    LowerBand = average[Length] - (Deviation * std[Length])
    
    if close crosses under LowerBand then
        buy at market
    endif
    
    // Calculating the profit in money for current positions
    FloatingProfit = (((close - POSITIONPRICE) * POINTVALUE) * countofposition) / POINTSIZE
    
    if FloatingProfit >= 10 then
        sell at market
    endif
    

    This 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.

    gonzocorp thanked this post
    #214608 quote
    Nicolas
    Keymaster
    Master

    TIP: 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.

    defparam cumulateOrders = true // Cumulating orders is enabled
    
    // Setting the parameters for the MACD and RSI indicators
    MACDLengthFast = 12
    MACDLengthSlow = 26
    MACDLengthSignal = 9
    RSILength = 14
    OverSold = 30 // RSI level for oversold conditions
    
    // Calculating the MACD and RSI
    macdValue = ExponentialAverage[MACDLengthFast](close) - ExponentialAverage[MACDLengthSlow](close)
    signalValue = ExponentialAverage[MACDLengthSignal](macdValue)
    rsiValue = RSI[RSILength](close)
    
    if macdValue > signalValue and rsiValue crosses over OverSold then
        buy at market
    endif
    
    // Set a trailing stop of X points
    X = 15 // Define your own value for X
    SET STOP PTRAILING X
    

    This 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.

    GraHal and gonzocorp thanked this post
    #214611 quote
    Nicolas
    Keymaster
    Master

    code 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.

    defparam cumulateOrders = true
    
    // Define the points step for buying
    X = 10
    
    // Define the moving average period for trend
    maPeriod = 20
    
    // Calculate the moving average
    avg = average[maPeriod]
    
    // Define the trailing stop value
    trailingStop = 15
    
    // In each bar, check if the price has moved X points from the last buy price
    if barindex > 1 and close > lastBuyPrice + X * pointsize and close > avg then
      buy at market
      lastBuyPrice = close
      set stop ptrailing trailingStop
    endif
    
    // At the start of the strategy, we buy once at market price
    if barindex = 1 then
      buy at market
      lastBuyPrice = close
      set stop ptrailing trailingStop
    endif
    

    In 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, updates lastBuyPrice, and sets a trailing stop. At the start of the strategy, it also places a buy order, sets lastBuyPrice, 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.

    gonzocorp thanked this post
    #214613 quote
    Nicolas
    Keymaster
    Master

    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

    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 and Y as the stop loss limit.

    Here is the strategy:

    // Setting the parameters for the Hull Moving Averages
    ShortTermLength = 9
    LongTermLength = 21
    
    TakeProfitX = 50 // adjust this to your liking
    StopLossY = 25 // adjust this to your liking
    
    // Calculate the Hull Moving Averages
    ShortTermHMA = HullAverage[ShortTermLength](close)
    LongTermHMA = HullAverage[LongTermLength](close)
    
    // Identify when the ShortTermHMA changes from decreasing (red) to increasing (green) and LongTermHMA is also increasing
    if (ShortTermHMA[1] < ShortTermHMA[2] and ShortTermHMA > ShortTermHMA[1]) and LongTermHMA > LongTermHMA[1] then
        buy at market
        set target pprofit TakeProfitX
        set stop ploss StopLossY
    endif
    

    In this code, ShortTermHMA[1] < ShortTermHMA[2] and ShortTermHMA > 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.

    TraderGlyn and gonzocorp thanked this post
    #214619 quote
    Nicolas
    Keymaster
    Master

    Now, 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:

    // --- settings 
    AP = 14 //Common Period
    coeff = 1 //Multiplier
    // --- end of settings 
    
    if (MoneyFlowIndex[ap]>=50) then
        magic=Low[0]-AverageTrueRange[ap](close)*coeff
    endif
    
    if (MoneyFlowIndex[ap]<50) then
        magic=High[0]+AverageTrueRange[ap](close)*coeff
    endif
    
    if (MoneyFlowIndex[ap]>=50 and magic<magic[1]) then
        magic=magic[1]
    endif
    
    if (MoneyFlowIndex[ap]<50 and magic>magic[1]) then
        magic=magic[1]
    endif
    
    AlphaTrend = magic
    
    // Buy at market when a new uptrend is detected
    if AlphaTrend[1] < AlphaTrend[2] and AlphaTrend > AlphaTrend[1] then
        buy at market
    endif
    
    gonzocorp thanked this post
    #214634 quote
    pableitor
    Participant
    Master

    ChatGPT 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:

    defparam cumulateOrders = false
    
    // 5-minute timeframe
    timeframe(5 minutes)
    
    // 1-hour timeframe
    timeframe(1 hour)
    ema10 = average[10](close)
    
    // Go long if close crosses over 10-period EMA of 1-hour timeframe
    timeframe(5 minutes)
    if close crosses over ema10 then
        buy at market
    endif
    
    // Go short if close crosses under 10-period EMA of 1-hour timeframe
    if close crosses under ema10 then
        sellshort at market
    endif
    

    In 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.

    Nicolas, PGH and upupandaway thanked this post
    #214735 quote
    Meta Signals Pro
    Participant
    Veteran

    fantastic thread ^^ thanks

    #214856 quote
    ProRealAlgos
    Participant
    Junior

    This 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

    threshold = 10
    atr = 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 trade
    Buy 1 contract at market
    ElsIf (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 trade
    Sell 1 contract at market
    EndIf
    
    If (longOnMarket) And (rsi > 70) then
    //The position is long, and RSI is overbought, so we exit the trade
    sell at market
    ElsIf (shortOnMarket) And (rsi < 30) Then
    // The position is short, and RSI is oversold, so we exit the trade
    exitshort at market
    EndIf

    And here’s the video if you want to watch that: https://www.youtube.com/shorts/uwx4Q_xuH_Q

    Ipsch and Meta Signals Pro thanked this post
    616050_e8c8ca5f374a4262a5baf525c1b9443dmv2.png 616050_e8c8ca5f374a4262a5baf525c1b9443dmv2.png
    #214912 quote
    Nicolas
    Keymaster
    Master

    Thanks, 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.

    #215146 quote
    PeterSt
    Participant
    Master

    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.

    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 …

    GraHal thanked this post
    image_2023-05-25_083247188.png image_2023-05-25_083247188.png
    #215148 quote
    Nicolas
    Keymaster
    Master

    You 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.

Viewing 15 posts - 1 through 15 (of 88 total)
  • You must be logged in to reply to this topic.

Create strategies codes with ChatGPT for ProRealTime


General Trading: Market Analysis & Manual Trading

New Reply
Author
author-avatar
Nicolas @nicolas Keymaster
Summary

This topic contains 87 replies,
has 22 voices, and was last updated by crankbuddy
6 months ago.

Topic Details
Forum: General Trading: Market Analysis & Manual Trading
Language: English
Started: 05/12/2023
Status: Active
Attachments: 17 files
Logo Logo
Loading...