ProRealCode - Trading & Coding with ProRealTime™
Hola,
la nueva versión v.04 recogiendo todos los cambios está terminada (a expensas del punto tratado en el siguiente párrafo), y pendiente de probar exhaustivamente a la caza de algún gazapo, bastante probable, especialmente a la vista del galimatías que me ha supuesto programar el punto (a). Si no se complica ni la prueba ni mi tiempo disponible, confío en que sea un asunto de unos pocos días.
Mientras tanto, una duda me ha surgido sobre un punto que no se ha comentado: admitir o no una actualización de stop hacia abajo, una posibilidad real usando un exit filter mayor que 0. Parece claro que el primer stop, usado en el cálculo de acciones a comprar, no se puede modificar a la baja, para no incurrir en posibles pérdidas superiores al riesgo permitido por posición abierta (50000*0.6/100 = 300), pero y el resto?
Saludos
Disculpa no pude logarme en todo el fin de semana, me daba error y he tenido que restaurar la contraseña.
Efectivamente, no habíamos hablado de ello pero puede darse el caso que el stop vaya a la baja. En ese caso, que no es muy frecuente, estaría asumiendo un riesgo superior al tenido inicialmente. Quizá no es muy correcto, lo sé, pero asi es como lo hago, reduzco riesgo en la siguiente entrada de otro valor puesto que tengo en cuenta el riesgo total de toda mi cartera. Que no te importe/afecte a efectos de programación. El tema de la gestión del dinero es secundario para mi programarlo en PRT. Es mas importante el resto, punto a) etc.
gracias
Buen día,
he aquí la versión v.04, la penúltima!?, de la estrategia, recién salida de cocina (no ha resultado precisamente una sopa al cuarto de hora).
Como los cambios que se han ido incorporando, respetando la estructura lógica del código inicial, lo habían convertido bastante en lo que en el argot se conoce como código-spaghetti, difícil de entender y depurar, decidí reescribirlo desde cero, aprovechando que ya tenía la idea completa de las necesidades del sistema y también mi mayor dominio de esta plataforma de programación. El resultado es un código bastante diferente, más corto y más claro, y hasta donde lo he probado parece funcionar como debería.
Para cualquier aclaración, ya sabes dónde estamos, aunque no estemos siempre. Saludos.
// TS name: Historical Maximum Breakout
// Description: Buy at pivot highs breakouts.
// Sell at relative minimums (or lows) between the
// breakout of a pivot high and that pivot high
// A pivot high is confirmed by a correction in the low
// of the bar(s) after a new historical maximum
// Instruments: Stocks/ETFs
// Time frame: Daily / Weekly / Monthly (preferred)
// Features: Only long system. Risk and money management
// Version: 04.1
// ****************************************************************************//
REM customizable and optional parameters
once initialCapital= 50000 // initial capital
once exitFilter = 3 // % below relative minimum to exit
once risk = 0.6 // % equity risk
once minimalCashSize = 1000 // minimal cash position size
once upForBreakeven = 10 // % above entry price to move stop to breakeven
once gainAtBreakeven = 1 // % marginal profit at breakeven
//
REM variables declaration
once historicalMax = 0 // pivot high
once currentMax = 0 // current maximum candidate to pivot high
once exitPrice = 0 // sell stop price
once buyPrice = 0 // buy stop price
once currentMin = 0 // current minimum candidate to sell stop
once breakevenStop = 0 // breakeven stop
once barLow = 0 // stores low of certain bars
once equity = 0 // current equity
once positionSize = 0 // number of shares to buy
once cashSize = 0 // cash investment
//
REM special treatment for 2 first loaded bars
if barIndex = 0 then
currentMax = high
currentMin = low
endif
if barIndex = 1 then
if high > currentMax then
currentMax = high
endif
if low < currentMin then
currentMin = low
exitPrice = low * (1 - exitFilter/100)
historicalMax = currentMax
buyPrice = historicalMax
endif
endif
//
REM normal coding body
if barIndex > 1 then
currentMin = min(low, currentMin)
if not onmarket then
exitPrice = currentMin * (1 - exitFilter/100)
endif
if high > currentMax then
barLow = 0 // reset barLow
currentMax = high
if low < low[1] then
currentMin = low
exitPrice = currentMin * (1 - exitFilter/100)
endif
endif
if low < low[1] and currentMax > historicalMax then
historicalMax = currentMax
if barLow > 0 then
currentMin = min(low, barLow)
else
currentMin = low
endif
if not onmarket then
exitPrice = currentMin * (1 - exitFilter/100)
endif
buyPrice = historicalMax
endif
if high < high[1] and currentMax > historicalMax then
barLow = low
endif
if high > historicalMax then
exitPrice = currentMin * (1 - exitFilter/100)
endif
endif
// cleaning
if not onmarket then
breakevenStop = 0 // reset breakEvenStop
endif
//
REM money and risk management
equity = initialCapital + STRATEGYPROFIT
// calculate breakeven stop price
if onmarket and upForBreakeven > 0 then
if high >= tradeprice * (1 + upForBreakeven/100) then
breakevenStop = tradeprice * (1 + gainAtBreakeven/100)
endif
endif
// calculate number of shares and cash size
positionSize = ROUND((equity * risk/100) / (buyPrice - exitPrice))
cashSize = positionSize * buyPrice
//
REM set buy and sell stop orders
if not onmarket and positionSize > 0 and cashSize >= minimalCashSize then
buy positionSize shares at buyPrice + 0.001 stop
endif
if onmarket and exitPrice > 0 then
exitPrice = max(breakevenStop, exitPrice)
sell at exitPrice stop
endif
//*****************************************************************
//graph currentmin
//graph historicalmax
//graph buyPrice
//graph exitprice
Ayayayayay, Tikitaka, gracias por el enorme esfuerzo lo primero pero creo que por arreglar el punto a), es decir alguna salida errónea que ocurria de vez en cuando (tenia que coincidir que hacia minimo la misma barra que hacia maximo para que no actualizara el stop y no ocurria muchas veces), hemos estropeado la entrada. Ahora siempre entra tarde. Si superpones el anterior código con el nuevo lo ves. A modo de ejemplo pongo el gráfico de citi que te decía que en feb93 no salia correctamente. Ahora sale donde debe, como ves, pero no entra bien y el problema de entrar tarde ocurre siempre en cada entrada de cada valor.
Es probable que el tema de la gestion del dinero te haya llevado a reprogramarlo todo de nuevo y por eso dan fallo todas las entradas. Antes de que me mandes a paseo con razón te propongo, si te parece, que si puedes arreglar el punto a) con el anterior código perfecto, y si no no pasa nada lo dejamos asi. Perderíamos la gestión del dinero pero como siempre te he dicho, es un tema menor que si no lo tengo no importa, no quiero que por ello te vuelvas loco y tampoco que cuando lo teníamos ya casi vayamos para atrás.
Verás, yo antes salvo el punto a) estaba y estoy encantado porque arreglaste el problema c) añadiendo 0,001 y el problema 2) dándome unas lineas para sustituir por otras, lo que me permitía tener dos versiones, asegurando entrada y sin asegurarla. Ahora al cambiar todo el código no sé que lineas cambiar por otras para tener estas dos versiones y lo mas importante, la entrada falla siempre y todo por una gestión del dinero que te ha hecho cambiar todo desde el principio. No quiero que eso lo estropee todo por lo que, si te parece, si no puedes arreglar el punto a) en el código antiguo comprando 2000 eur, lo dejamos terminado como está, quedando en todo caso y si quieres, (entiendo que esto no te llevaría mucho tiempo) la versión bajista.
Tengo que hablar con Nicolás para que te meta en plantilla, no he visto nada igual en el foro y tenemos la suerte de que eres español. Después de esto el agradecimiento no se puede quedar solo en palabras, son muchas horas ayudando las que metes.
Espero si lo lees ahora no haberte dado la noche.
Gracias de verdad
// TS name: Historical Maximum Breakout
// Description: Buy at pivot highs breakouts.
// Sell at relative minimums (or lows) between the
// breakout of a pivot high and that pivot high
// A pivot high is confirmed by a correction in the low
// of the bar(s) after a new historical maximum
// Instruments: Stocks/ETFs
// Time frame: Daily / Weekly / Monthly (preferred)
// Features: Only long system. Risk and money management
// Version: 04.2
// ****************************************************************************//
REM customizable and optional parameters
once initialCapital= 50000 // initial capital
once exitFilter = 3 // % below relative minimum to exit
once risk = 0.6 // % equity risk
once minimalCashSize = 1000 // minimal cash position size
once upForBreakeven = 10 // % above entry price to move stop to breakeven
once gainAtBreakeven = 1 // % marginal profit at breakeven
//
REM variables declaration
once historicalMax = 0 // pivot high
once currentMax = 0 // current maximum candidate to pivot high
once exitPrice = 0 // sell stop price
once buyPrice = 0 // buy stop price
once currentMin = 0 // current minimum candidate to sell stop
once breakevenStop = 0 // breakeven stop
once barLow = 0 // stores low of certain bars
once equity = 0 // current equity
once positionSize = 0 // number of shares to buy
once cashSize = 0 // cash investment
//
REM special treatment for 2 first loaded bars
if barIndex = 0 then
currentMax = high
currentMin = low
endif
if barIndex = 1 then
if high > currentMax then
currentMax = high
endif
if low < currentMin then
currentMin = low
exitPrice = low * (1 - exitFilter/100)
historicalMax = currentMax
buyPrice = historicalMax
endif
endif
//
REM normal coding body
if barIndex > 1 then
currentMin = min(low, currentMin)
if not onmarket then
exitPrice = currentMin * (1 - exitFilter/100)
endif
if high > currentMax then
barLow = 0 // reset barLow
currentMax = high
// bullish engulfing bar
if low < low[1] and close > open then
currentMin = low
exitPrice = currentMin * (1 - exitFilter/100)
endif
endif
if low < low[1] and currentMax > historicalMax then
historicalMax = currentMax
if barLow > 0 then
currentMin = min(low, barLow)
else
currentMin = low
endif
if not onmarket then
exitPrice = currentMin * (1 - exitFilter/100)
endif
buyPrice = historicalMax
endif
if high < high[1] and currentMax > historicalMax then
barLow = low
endif
if high > historicalMax then
exitPrice = currentMin * (1 - exitFilter/100)
endif
endif
// cleaning
if not onmarket then
breakevenStop = 0 // reset breakEvenStop
endif
//
REM money and risk management
equity = initialCapital + STRATEGYPROFIT
// calculate breakeven stop price
if onmarket and upForBreakeven > 0 then
if high >= tradeprice * (1 + upForBreakeven/100) then
breakevenStop = tradeprice * (1 + gainAtBreakeven/100)
endif
endif
// calculate number of shares and cash size
positionSize = ROUND((equity * risk/100) / (buyPrice - exitPrice))
cashSize = positionSize * buyPrice
//
REM set buy and sell stop orders
if not onmarket and positionSize > 0 and cashSize >= minimalCashSize then
buy positionSize shares at buyPrice + 0.001 stop
endif
if onmarket and exitPrice > 0 then
exitPrice = max(breakevenStop, exitPrice)
sell at exitPrice stop
endif
//*****************************************************************
//graph currentmin
//graph historicalmax
//graph buyPrice
//graph exitprice
Describe what this topic is trying to build, in plain English, and ProRealAI writes the ProRealTime™ indicator, screener or system for you.
Aclaraciones sobre una estrategia propuesta por quo en el forum en inglés
This topic contains 21 replies,
has 2 voices, and was last updated by quo
9 years, 9 months ago.
| Forum: | ProOrder: Trading Automático y Backtesting |
| Language: | Spanish |
| Started: | 10/29/2016 |
| Status: | Active |
| Attachments: | No files |
The information collected on this form is stored in a computer file by ProRealCode to create and access your ProRealCode profile. This data is kept in a secure database for the duration of the member's membership. They will be kept as long as you use our services and will be automatically deleted after 3 years of inactivity. Your personal data is used to create your private profile on ProRealCode. This data is maintained by SAS ProRealCode, 407 rue Freycinet, 59151 Arleux, France. If you subscribe to our newsletters, your email address is provided to our service provider "MailChimp" located in the United States, with whom we have signed a confidentiality agreement. This company is also compliant with the EU/Swiss Privacy Shield, and the GDPR. For any request for correction or deletion concerning your data, you can directly contact the ProRealCode team by email at privacy@prorealcode.com If you would like to lodge a complaint regarding the use of your personal data, you can contact your data protection supervisory authority.