Hi,
I sparred with ChatGPT on this but it couldnt help me.
It suggested the below code, but no matter how much I asked it to adjust the code it didnt help.
I got an error message on the line concerning “position_size_percent” (line 4), “entry_dates” (line 6), and “profit_treshold” (line 8).
So basically I want to create a code that says BUY or SELL at certain dates in the future, with adjusting trailing stop losses and also adjusting for volatility.
Assistance would be greatly appreciated:)
// Parameters
DEFPARAM CumulateOrders = False
// Position size percentage
POSITION_SIZE_PERCENT = 5.0 // 5% of the total capital
// List of dates to go long (in YYYYMMDD format)
ENTRY_DATES = [20240801, 20240901, 20241001, 20241101, 20241201]
// Constants for profit thresholds and trailing stops
PROFIT_THRESHOLD_1 = 0.5 // Profit threshold of 0.5%
PROFIT_THRESHOLD_2 = 1.0 // Profit threshold of 1%
PROFIT_THRESHOLD_3 = 1.5 // Profit threshold of 1.5%
PROFIT_THRESHOLD_4 = 3.0 // Profit threshold of 3%
INITIAL_TRAILING_STOP_PERCENT = 2.0 // Initial trailing stop of 2%
TRAILING_STOP_1_PERCENT = 1.5 // Trailing stop of 1.5%
TRAILING_STOP_2_PERCENT = 1.0 // Trailing stop of 1%
TRAILING_STOP_3_PERCENT = 0.75 // Trailing stop of 0.75%
TRAILING_STOP_4_PERCENT = 0.5 // Trailing stop of 0.5%
// Variables
var trailing_stop = 0.0
var entry_price = 0.0
var contracts_to_trade = 0
// Calculate the last 10 days historical volatility
historical_volatility = Std[10](Close)
// Adjust position size and trailing stop loss based on historical volatility
adjusted_position_size_percent = POSITION_SIZE_PERCENT * (historical_volatility / 0.01) // Assuming 0.01 as a reference volatility
adjusted_initial_trailing_stop = INITIAL_TRAILING_STOP_PERCENT * (historical_volatility / 0.01)
// Conditions to enter long positions
IF NOT LongOnMarket THEN
FOR i = 0 TO (ArraySize(ENTRY_DATES) – 1) DO
IF (Date = ENTRY_DATES[i] AND IntradayBarIndex = IntradayBarIndexMax) THEN
// Calculate the number of contracts to trade
contracts_to_trade = (adjusted_position_size_percent * StrategyAccountEquity) / Close
contracts_to_trade = Round(contracts_to_trade) // Ensure it’s an integer value
entry_price = Close
trailing_stop = adjusted_initial_trailing_stop
BUY contracts_to_trade CONTRACTS AT MARKET
BREAK // Exit loop once position is opened
ENDIF
NEXT
ENDIF
// Conditions to exit long positions
IF LongOnMarket THEN
// Calculate the current profit percentage
current_profit = (Close – entry_price) / entry_price * 100
// Adjust the trailing stop based on profit thresholds
IF current_profit >= PROFIT_THRESHOLD_4 THEN
trailing_stop = TRAILING_STOP_4_PERCENT * (historical_volatility / 0.01)
ELSIF current_profit >= PROFIT_THRESHOLD_3 THEN
trailing_stop = TRAILING_STOP_3_PERCENT * (historical_volatility / 0.01)
ELSIF current_profit >= PROFIT_THRESHOLD_2 THEN
trailing_stop = TRAILING_STOP_2_PERCENT * (historical_volatility / 0.01)
ELSIF current_profit >= PROFIT_THRESHOLD_1 THEN
trailing_stop = TRAILING_STOP_1_PERCENT * (historical_volatility / 0.01)
ELSE
trailing_stop = adjusted_initial_trailing_stop
ENDIF
// Set the trailing stop price
trailing_stop_price = entry_price * (1 – trailing_stop / 100)
// If the current price falls below the trailing stop price, close the position
IF Close <= trailing_stop_price THEN
SELL AT MARKET
ENDIF
ENDIF
JSParticipant
Master
It is not allowed to use “underscore” in variables… (this happens in many places in the code)
For the “Entry_Dates do not use square brackets and 1 date at a time…
EntryDate1=20240801
EntryDate2=20240901
etc.
Thanks a lot.
I tried to backtest and the system did not flag any errors with the code.
However, the backtest did not return any trades…What could be the issue?
I tried to backtest on the SP500 Cash 50 USD contract.
Full code below.
// Parameters
DEFPARAM CumulateOrders = False
// Position size percentage
PositionSizePercent = 5.0 // 5% of the total capital
// List of dates to go long (in YYYYMMDD format)
EntryDate1 = 20231508
EntryDate2 = 20232509
EntryDate3 = 20232112
EntryDate4 = 20242602
EntryDate5 = 20241704
// Constants for profit thresholds and trailing stops
ProfitThreshold1 = 0.5 // Profit threshold of 0.5%
ProfitThreshold2 = 1.0 // Profit threshold of 1%
ProfitThreshold3 = 1.5 // Profit threshold of 1.5%
ProfitThreshold4 = 3.0 // Profit threshold of 3%
InitialTrailingStopPercent = 2.0 // Initial trailing stop of 2%
TrailingStop1Percent = 1.5 // Trailing stop of 1.5%
TrailingStop2Percent = 1.0 // Trailing stop of 1%
TrailingStop3Percent = 0.75 // Trailing stop of 0.75%
TrailingStop4Percent = 0.5 // Trailing stop of 0.5%
// Calculate the last 10 days historical volatility
HistoricalVolatility = Std[10](Close)
// Adjust position size and trailing stop loss based on historical volatility
AdjustedPositionSizePercent = PositionSizePercent * (HistoricalVolatility / 0.05) // Assuming 0.1 as a reference volatility
AdjustedInitialTrailingStop = InitialTrailingStopPercent * (HistoricalVolatility / 0.01)
// Conditions to enter long positions
IF NOT LongOnMarket THEN
IF Date = EntryDate1 OR Date = EntryDate2 OR Date = EntryDate3 OR Date = EntryDate4 OR Date = EntryDate5 THEN
IF Time = 160000 THEN // Assuming the market close time is 16:00 (4 PM) in HHMMSS format
// Calculate the number of contracts to trade based on fixed capital
TotalCapital = 10000 // Example fixed capital value for calculation
contractsToTrade = (AdjustedPositionSizePercent * TotalCapital) / Close
contractsToTrade = Round(contractsToTrade) // Ensure it’s an integer value
entryPrice = Close
trailingStop = AdjustedInitialTrailingStop
BUY contractsToTrade CONTRACTS AT MARKET
ENDIF
ENDIF
ENDIF
// Conditions to exit long positions
IF LongOnMarket THEN
// Calculate the current profit percentage
CurrentProfit = (Close – entryPrice) / entryPrice * 100
// Adjust the trailing stop based on profit thresholds
IF CurrentProfit >= ProfitThreshold4 THEN
trailingStop = TrailingStop4Percent * (HistoricalVolatility / 0.01)
ELSIF CurrentProfit >= ProfitThreshold3 THEN
trailingStop = TrailingStop3Percent * (HistoricalVolatility / 0.01)
ELSIF CurrentProfit >= ProfitThreshold2 THEN
trailingStop = TrailingStop2Percent * (HistoricalVolatility / 0.01)
ELSIF CurrentProfit >= ProfitThreshold1 THEN
trailingStop = TrailingStop1Percent * (HistoricalVolatility / 0.01)
ELSE
trailingStop = AdjustedInitialTrailingStop
ENDIF
// Set the trailing stop price
TrailingStopPrice = entryPrice * (1 – trailingStop / 100)
// If the current price falls below the trailing stop price, close the position
IF Close <= TrailingStopPrice THEN
SELL AT MARKET
ENDIF
ENDIF
JSParticipant
Master
You got the format of the “date” wrong: YYYYMMDD
Because there are also times in your code (160000) you must use a time frame of maximum 1 hour…
Thanks reply.
Adjusted the dates. What do you mean by Timeframe?
I tried removing the code concerning hours, and changed the chart display from weekly to hourly. The backtest still showed nothing..
JSParticipant
Master
Hi,
What I meant by time frame is that in your code there is a certain time (160000), and you then must use a time frame in which this time occurs, so for example 5 min, 10 min and a maximum of an hour…
I tried your code on a time frame of 1 hour and your system works, only the number of contracts bought was very high (more than 5000 contracts)…
The backtest still showed nothing..
JS got 5000 contracts, so you might be ‘out of funds’ and it therefore appears as no contracts?
JSParticipant
Master
When I reduce the number of contracts to 1 contract, the system opens a long position on December 21, 2023 at 16:00, only this position is not closed by a take profit or a stop loss (position continues to run) …
@GraHal you could see the number of contracts, probably because the position was in profit for a while and then immediately ran out of money…
JSParticipant
Master
This is your code I’m currently using (IG, Dow Jones, TF 1 hour)…
// Parameters
DEFPARAM CumulateOrders = False
// Position size percentage
PositionSizePercent = 5.0 // 5% of the total capital
// List of dates to go long (in YYYYMMDD format)
EntryDate1 = 20230815
EntryDate2 = 20230925
EntryDate3 = 20231221
EntryDate4 = 20240226
EntryDate5 = 20240417
// Constants for profit thresholds and trailing stops
ProfitThreshold1 = 0.5 // Profit threshold of 0.5%
ProfitThreshold2 = 1.0 // Profit threshold of 1%
ProfitThreshold3 = 1.5 // Profit threshold of 1.5%
ProfitThreshold4 = 3.0 // Profit threshold of 3%
InitialTrailingStopPercent = 2.0 // Initial trailing stop of 2%
TrailingStop1Percent = 1.5 // Trailing stop of 1.5%
TrailingStop2Percent = 1.0 // Trailing stop of 1%
TrailingStop3Percent = 0.75 // Trailing stop of 0.75%
TrailingStop4Percent = 0.5 // Trailing stop of 0.5%
// Calculate the last 10 days historical volatility
HistoricalVolatility = Std[10](Close)
// Adjust position size and trailing stop loss based on historical volatility
AdjustedPositionSizePercent = PositionSizePercent * (HistoricalVolatility / 0.05) // Assuming 0.1 as a reference volatility
AdjustedInitialTrailingStop = InitialTrailingStopPercent * (HistoricalVolatility / 0.01)
// Conditions to enter long positions
IF NOT LongOnMarket THEN
IF Date = EntryDate1 OR Date = EntryDate2 OR Date = EntryDate3 OR Date = EntryDate4 OR Date = EntryDate5 THEN
IF Time = 160000 THEN // Assuming the market close time is 16:00 (4 PM) in HHMMSS format
// Calculate the number of contracts to trade based on fixed capital
TotalCapital = 10000 // Example fixed capital value for calculation
contractsToTrade = (AdjustedPositionSizePercent * TotalCapital) / Close
contractsToTrade = Round(contractsToTrade) // Ensure it’s an integer value
entryPrice = Close
trailingStop = AdjustedInitialTrailingStop
//BUY contractsToTrade CONTRACTS AT MARKET
Buy 1 contract at Market
ENDIF
ENDIF
ENDIF
// Conditions to exit long positions
IF LongOnMarket THEN
// Calculate the current profit percentage
CurrentProfit = (Close - entryPrice) / entryPrice * 100
// Adjust the trailing stop based on profit thresholds
IF CurrentProfit >= ProfitThreshold4 THEN
trailingStop = TrailingStop4Percent * (HistoricalVolatility / 0.01)
ELSIF CurrentProfit >= ProfitThreshold3 THEN
trailingStop = TrailingStop3Percent * (HistoricalVolatility / 0.01)
ELSIF CurrentProfit >= ProfitThreshold2 THEN
trailingStop = TrailingStop2Percent * (HistoricalVolatility / 0.01)
ELSIF CurrentProfit >= ProfitThreshold1 THEN
trailingStop = TrailingStop1Percent * (HistoricalVolatility / 0.01)
ELSE
trailingStop = AdjustedInitialTrailingStop
ENDIF
// Set the trailing stop price
TrailingStopPrice = entryPrice * (1 - trailingStop / 100)
// If the current price falls below the trailing stop price, close the position
IF Close <= TrailingStopPrice THEN
SELL AT MARKET
ENDIF
ENDIF
Thanks again, much appreciated.
However, the backtest is still blank…
And why would the contract sizes be so large? I put 10.000 USD as start capital.
JSParticipant
Master
Hi,
I think it goes wrong with the calculation of your contracts because you use the historical volatility, this volatility can change a lot and affects the calculation of the number of contracts…
@
Melchizedek
Give your topic a meaningful title. Describe your question or your subject in your title. Do not use meaningless titles such as ‘Coding Help Needed’
Thanks 🙂
I changed it.
Hi,
Thanks to all for the replies!
Tried a code generated by ChatGPT, without adjusting for historical volatility.
The below code was able to backtest, but as you can see from the attached picture – no trades were executed. What is wrong?
// Parameters
DEFPARAM CumulateOrders = False
// Position size percentage
PositionSizePercent = 5.0 // 5% of the total capital
// List of dates to go long (in YYYYMMDD format)
EntryDate1 = 20230815
EntryDate2 = 20230925
EntryDate3 = 20231221
EntryDate4 = 20240226
EntryDate5 = 20240417
// Constants for profit thresholds and trailing stops
ProfitThreshold1 = 1.0 // Profit threshold of 1%
ProfitThreshold2 = 2.0 // Profit threshold of 2%
ProfitThreshold3 = 3.0 // Profit threshold of 3%
InitialTrailingStopPercent = 5.0 // Initial trailing stop of 5%
TrailingStop1Percent = 4.0 // Trailing stop of 4%
TrailingStop2Percent = 3.0 // Trailing stop of 3%
TrailingStop3Percent = 2.0 // Trailing stop of 2%
// Conditions to enter long positions
IF NOT LongOnMarket THEN
IF Date = EntryDate1 OR Date = EntryDate2 OR Date = EntryDate3 OR Date = EntryDate4 OR Date = EntryDate5 THEN
IF Time = 160000 THEN // Assuming the market close time is 16:00 (4 PM) in HHMMSS format
// Calculate the number of contracts to trade based on fixed capital
TotalCapital = 10000 // Example fixed capital value for calculation
contractsToTrade = (PositionSizePercent * TotalCapital) / Close
contractsToTrade = Round(contractsToTrade) // Ensure it’s an integer value
entryPrice = Close
trailingStop = InitialTrailingStopPercent
BUY contractsToTrade CONTRACTS AT MARKET
ENDIF
ENDIF
ENDIF
// Conditions to exit long positions
IF LongOnMarket THEN
// Calculate the current profit percentage
CurrentProfit = (Close – entryPrice) / entryPrice * 100
// Adjust the trailing stop based on profit thresholds
IF CurrentProfit >= ProfitThreshold3 THEN
trailingStop = TrailingStop3Percent
ELSIF CurrentProfit >= ProfitThreshold2 THEN
trailingStop = TrailingStop2Percent
ELSIF CurrentProfit >= ProfitThreshold1 THEN
trailingStop = TrailingStop1Percent
ELSE
trailingStop = InitialTrailingStopPercent
ENDIF
// Set the trailing stop price
TrailingStopPrice = entryPrice * (1 – trailingStop / 100)
// If the current price falls below the trailing stop price, close the position
IF Close <= TrailingStopPrice THEN
SELL AT MARKET
ENDIF
ENDIF
no trades were executed. What is wrong?
Post screenshot of equity curve … you may be opening 1 or more trades on the far left of the equity curve, but the trades are not closed and then you run out of funds so you can’t open any more due to the reason JS states below?
this volatility can change a lot and affects the calculation of the number of contracts…
I now think it is not above as I tested it and your conditions are rarely coincident / True, i.e. dates AND time of 160000.
Try adding more dates and more times?
Anyway attached does take 2 trades (over 100k bars) … it might help you, or at least get over the ‘no trades’ bit!