Primeiros passos
Configure o PineBag uma vez e prepare seu primeiro teste em alguns minutos.
Você precisa de três coisas
- Google Chrome 116 ou mais recente.
- Uma conta TradingView conectada com acesso aos símbolos que você deseja testar.
- Um arquivo Pine Script que declara
strategy(), não sóindicator().
Instale e abra o PineBag
-
Instale a extensão.
Use o botão de instalação do PineBag. Fixe a extensão se desejar acesso rápido. -
Abra um gráfico TradingView.
Faça login primeiro e, em seguida, abra qualquer mercado e período suportados. -
Recarregue a guia do gráfico.
Faça isso após instalar ou atualizar o PineBag para que o gráfico possa se conectar. -
Abra o PineBag.
Selecione o ícone PineBag. O indicador de conexão fica verde quando o gráfico está pronto.
O painel lateral, controle por controle
Os números na interface real correspondem às explicações. Nada nesta imagem é uma maquete.
1
2
3
4
5
6
7
8
9
10
11
- 1Estratégia
A estratégia carregada. Clique no cartão para abri-la no editor; a lixeira no cabeçalho da seção a remove.
- 2Resumo da execução
Prazo, capital, tamanho do pedido e comissão que será utilizada.
- 3Buscar
Abre a pesquisa de símbolos do TradingView para que você possa adicionar um ticker qualificado para bolsa.
- 4Bolsa para cópias
Copia cada ticker, um
EXCHANGE:SYMBOLpor linha. - 5Saco de pasta
Aceita linhas, vírgulas, ponto e vírgula ou espaços e ignora duplicatas.
- 6Limpar
Pede um segundo clique, copia os tickers e depois limpa a lista; «Colar tickers» a traz de volta.
- 7Tags de ação
Mostra a bolsa atual. Use × para remover um símbolo; adicione até 500.
- 8Executar backtest
Valida a configuração e inicia a execução sequencial do portfólio.
- 9Relatórios
Salve os 50 relatórios mais recentes localmente e exporte JSON ou CSV.
- 10Dias restantes
Active days: 05— Dias restantes. - 11Suporte
O suporte está disponível para solicitações técnicas, de faturamento, de licenciamento e de privacidade.
Carregar uma estratégia
- Escolha a fonte.
Deixe um.pineno Strategy ou abra o Editor e cole o código. - Corrija qualquer mensagem de validação.
O script deve conterstrategy(). PineBag mostra um erro claro se não puder ser usado. - Verifique o resumo.
Confirme o nome do script, prazo, capital e tamanho do pedido mostrados acima de Executar.
indicator(), converta-o em uma estratégia antes de executar o PineBag.Modelo de estratégia
Cada campo da aba Properties do TradingView corresponde a um argumento de strategy(). Mantenha os valores como constantes nomeadas no início do script: com a prioridade do script, cada ticker é testado com as mesmas premissas.
TIMEFRAMETempo gráfico
INITIAL_CAPITAL · CURRENCYCapital inicial
ORDER_SIZE · ORDER_SIZE_TYPETamanho padrão da ordem
PYRAMIDINGPiramidação
BAR_MAGNIFIERDetalhamento das barras
CALC_EVERY_TICK · CALC_ON_FILLSExecução do script
COMMISSION · COMMISSION_TYPEComissão
MARGIN_LONG · MARGIN_SHORTAlavancagem long e short
SLIPPAGEDeslizamento
LIMIT_FILL_TICKSExecução de ordens limite
FILL_ON_BAR_CLOSEAtraso na execução de ordens
runtime.error()Interrompe o script em qualquer outro tempo gráfico.
//@version=6
// ============================================================================
// Trend breakout · ATR risk — PineBag strategy template
// ============================================================================
// ----------------------------------------------------------------------------
// STRATEGY PROPERTIES (TradingView: Settings → Properties)
// ----------------------------------------------------------------------------
// TIMEFRAME takes a standard TradingView interval. Paste one of these, by the
// lowest TradingView plan that has it (tradingview.com/pricing, Charts):
// Basic days "1D" "1W" "1M" "3M" "6M" "12M"
// Essential minutes "1" "3" "5" "15" "30" "45"
// hours "60" "120" "180" "240"
// ranges "1R" "10R" "100R" "1000R"
// Premium seconds "1S" "5S" "10S" "15S" "30S" "45S"
// Ultimate ticks "1T" "10T" "100T" "1000T"
// Other intervals are custom and not used: a week is "1W", not "7D".
const string TIMEFRAME = "1D" // Chart timeframe
const float INITIAL_CAPITAL = 100000 // Initial capital
const string CURRENCY = currency.USD // Initial capital currency
const float ORDER_SIZE = 100 // Default order size
const string ORDER_SIZE_TYPE = strategy.percent_of_equity // Order size: % of equity
const int PYRAMIDING = 1 // Pyramiding
const bool BAR_MAGNIFIER = false // Bar detalization: Default (4 ticks per bar)
const bool CALC_EVERY_TICK = false // Script execution: On bar close
const bool CALC_ON_FILLS = false // Script execution: no recalculation after fills
const float COMMISSION = 0 // Commission
const string COMMISSION_TYPE = strategy.commission.percent // Commission: Percent
const float MARGIN_LONG = 100 // Long leverage 1x (leverage = 100 / margin)
const float MARGIN_SHORT = 100 // Short leverage 1x
const int SLIPPAGE = 0 // Slippage, ticks
const int LIMIT_FILL_TICKS = 0 // Limit order execution: Requested price
const bool FILL_ON_BAR_CLOSE = false // Order execution delay: One tick
strategy("Trend breakout · ATR risk", overlay = true,
initial_capital = INITIAL_CAPITAL,
currency = CURRENCY,
default_qty_type = ORDER_SIZE_TYPE,
default_qty_value = ORDER_SIZE,
pyramiding = PYRAMIDING,
use_bar_magnifier = BAR_MAGNIFIER,
calc_on_every_tick = CALC_EVERY_TICK,
calc_on_order_fills = CALC_ON_FILLS,
commission_type = COMMISSION_TYPE,
commission_value = COMMISSION,
margin_long = MARGIN_LONG,
margin_short = MARGIN_SHORT,
slippage = SLIPPAGE,
backtest_fill_limits_assumption = LIMIT_FILL_TICKS,
process_orders_on_close = FILL_ON_BAR_CLOSE)
// Stops with a clear message on any other timeframe; PineBag reads TIMEFRAME
// and selects it for the run.
if timeframe.period != TIMEFRAME
runtime.error("Switch the chart to the " + TIMEFRAME + " timeframe.")
// ----------------------------------------------------------------------------
// INPUT SETTINGS (TradingView: Settings → Inputs)
// ----------------------------------------------------------------------------
fastLength = input.int(20, "Fast EMA", minval = 1)
slowLength = input.int(50, "Slow EMA", minval = 2)
breakoutLength = input.int(20, "Breakout lookback", minval = 2)
atrLength = input.int(14, "ATR length", minval = 1)
atrStop = input.float(2.0, "ATR stop multiplier", minval = 0.1, step = 0.1)
// ----------------------------------------------------------------------------
// CALCULATIONS
// ----------------------------------------------------------------------------
fast = ta.ema(close, fastLength)
slow = ta.ema(close, slowLength)
atr = ta.atr(atrLength)
highestBefore = ta.highest(high, breakoutLength)[1]
// ----------------------------------------------------------------------------
// ENTRIES AND EXITS
// ----------------------------------------------------------------------------
longSignal = fast > slow and close > highestBefore
if longSignal and strategy.position_size == 0
strategy.entry("Long", strategy.long)
stopPrice = strategy.position_avg_price - atr * atrStop
strategy.exit("ATR stop", "Long", stop = stopPrice)
// ----------------------------------------------------------------------------
// PLOTS
// ----------------------------------------------------------------------------
plot(fast, "Fast EMA", color = color.rgb(0, 153, 255))
plot(slow, "Slow EMA", color = color.rgb(123, 97, 255))
Valores de TIMEFRAME
Escreva entre aspas um dos intervalos padrão do TradingView. Quais deles carregam depende do seu plano TradingView, conforme tradingview.com/pricing.
Dias, semanas e meses.
"1D" "1W" "1M" "3M" "6M" "12M"
Minutos, horas e barras de range. Minutos não têm letra; uma hora é 60.
"1" "3" "5" "15" "30" "45""60" "120" "180" "240""1R" "10R" "100R" "1000R"
Intervalos em segundos.
"1S" "5S" "10S" "15S" "30S" "45S"
Intervalos em ticks.
"1T" "10T" "100T" "1000T"
const string TIMEFRAME = "1D" // 1 day
// const string TIMEFRAME = "1W" // 1 week
// const string TIMEFRAME = "240" // 4 hours
// const string TIMEFRAME = "15" // 15 minutes
// const string TIMEFRAME = "30S" // 30 seconds, Premium and higher
Tamanho da ordem: percentual, valor ou quantidade
ORDER_SIZE contém o número e ORDER_SIZE_TYPE diz o que ele significa. Juntos, preenchem o campo Order size da aba Properties do TradingView.
strategy.percent_of_equity
Uma porcentagem do capital atual. 10 significa 10% do capital por operação.
strategy.cash
Um valor na moeda da estratégia. 1000 significa 1.000 USD por operação.
strategy.fixed
Uma quantidade de contratos, ações ou moedas. 0.5 significa 0,5 BTC por operação.
qty = …
O tamanho padrão vale apenas para ordens sem qty próprio. Uma entrada com qty = … usa esse valor no lugar.
// 10% of equity per trade
const float ORDER_SIZE = 10
const string ORDER_SIZE_TYPE = strategy.percent_of_equity
// 1,000 USD per trade (CURRENCY = currency.USD)
// const float ORDER_SIZE = 1000
// const string ORDER_SIZE_TYPE = strategy.cash
// 0.5 contracts, shares or coins per trade
// const float ORDER_SIZE = 0.5
// const string ORDER_SIZE_TYPE = strategy.fixed
Suas próprias variáveis
Mantenha as configurações da sua própria lógica de estratégia em um bloco INPUT SETTINGS separado. Cada chamada de input.int(), input.float() ou input.bool() vira um campo na aba Inputs do TradingView, para você ajustar sem editar o código.
// ----------------------------------------------------------------------------
// INPUT SETTINGS (TradingView: Settings → Inputs)
// ----------------------------------------------------------------------------
fastLength = input.int(20, "Fast EMA", minval = 1)
slowLength = input.int(50, "Slow EMA", minval = 2)
breakoutLength = input.int(20, "Breakout lookback", minval = 2)
atrLength = input.int(14, "ATR length", minval = 1)
atrStop = input.float(2.0, "ATR stop multiplier", minval = 0.1, step = 0.1)