Pine Script
À propos de la leçon

Here are the different useful functions of the library strategy :

  • strategy.entry(...) : open a position at the market or a limit order;
  • strategy.close(...) : close a market position;
  • strategy.cancel(...) : cancel a limit order;
  • strategy.exit(...) : take profit / stop loss;
  • strategy.cancel_all() : cancel all the open orders;
  • strategy.close_all() : close the open positions;
  • strategy.opentrades : number of trades opened;
  • strategy.equity : account equity.

 

Note that a strategy must contain at least one call to strategy (e.g. strategy.entry()).

 

Let’s illustrate this with taking market orders with Take Profit (TP) / Stop Loss (SL):

In these lines of code, we first calculate the ATR technical indicator over 14 periods. It is an indicator of volatility: its value is greater as the volatility is greater.

If the long condition is satisfied, we open a long position on the market, with a TP (at the price high+atr) and a SL (at the price low-atr); in addition, we close the short position if there is one in progress.

Conversely, if the short condition is satisfied, we open a short position on the market, with a TP (at the price low-atr) and a SL (at the price high+atr); in addition, we close the long position if there is one in progress.

 

A 2nd example, where we open limit orders:

In these lines of code, we first check that there are no open positions. If there are no trades in progress, we open a long limit order (whose price is 3% below the current price) and another short order (whose price is 3% below the current price).

 

Finally, as for an indicator, we can indicate input parameters which will be entered by the user, using the keyword input. This may concern the periods of the indicators here.

For example, the following instruction can be used to give the user the choice of whether or not to open short positions:

=>

 

Several arguments can be added to the declarator strategy() for the backtesting. For example, to add have an initial capital of 1000 for the backtesting and commission fees of 0.4%:

 

If you click « Add to Chart », the buy and sell signals will be displayed on the chart:

Illustration of buy/sell trading signals on the backtest

 

Participer à la discussion