Advertisement
akanoce

traility_sl_tp_template

Feb 25th, 2022
1,014
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.94 KB | None | 0 0
  1. class bcolors:
  2.     HEADER = '\033[95m'
  3.     OKBLUE = '\033[94m'
  4.     OKCYAN = '\033[96m'
  5.     OKGREEN = '\033[92m'
  6.     WARNING = '\033[93m'
  7.     FAIL = '\033[91m'
  8.     ENDC = '\033[0m'
  9.     BOLD = '\033[1m'
  10.     UNDERLINE = '\033[4m'
  11.            
  12. def initialize(state):
  13.     state.number_offset_trades = 0;
  14.  
  15. trailingEnabled = False
  16. trailingPerc = 10
  17.  
  18. atrPeriod = 14
  19. stopLossEnabled = False
  20. takeProfitEnabled = False
  21. stopLossAtrMult = 2
  22. takeProfitAtrMult = 4
  23.  
  24.  
  25. SYMBOLS = ['BTCBUSD','ETHBUSD']
  26.  
  27. @schedule(interval="12h", symbol=SYMBOLS)
  28. def handler(state, data):
  29.     '''
  30.    1) Compute indicators from data
  31.    '''
  32.     PORTFOLIO_PERC_PER_BUY = 1/len(SYMBOLS)
  33.     symbols = [{'data': data[symbol],'dataframe' : data[symbol].to_pandas()} for symbol in data.keys() if data[symbol]]
  34.  
  35.     for symbol in symbols:
  36.         dataframe = symbol['dataframe']
  37.         data = symbol['data']
  38.  
  39.         atr = data.atr(period=atrPeriod)
  40.  
  41.         # on erronous data return early (indicators are of NoneType)
  42.         if atr is None:
  43.             print("Missing some indicators data...")
  44.             return
  45.  
  46.         current_price = data.close_last
  47.        
  48.         '''
  49.        2) Fetch portfolio
  50.            > check liquidity (in quoted currency)
  51.            > resolve buy value
  52.        '''
  53.        
  54.         portfolio = query_portfolio()
  55.         balance_quoted = portfolio.excess_liquidity_quoted
  56.         quote_asset = portfolio.quoted
  57.         portfolio_value = portfolio.portfolio_value
  58.         balances = portfolio.balances
  59.         position_open = portfolio.open_positions
  60.         position_closed = portfolio.closed_positions
  61.         # we invest only 80% of available liquidity
  62.         #balance_quoted
  63.         buy_value = float(portfolio_value) * PORTFOLIO_PERC_PER_BUY
  64.         if buy_value > balance_quoted:
  65.             buy_value = balance_quoted
  66.        
  67.        
  68.         '''
  69.        3) Fetch position for symbol
  70.            > has open position
  71.            > check exposure (in base currency)
  72.        '''
  73.  
  74.         position = query_open_position_by_symbol(data.symbol,include_dust=False)
  75.         has_position = position is not None
  76.  
  77.         '''
  78.        4) Resolve buy or sell signals
  79.            > create orders using the order api
  80.            > print position information
  81.            
  82.        '''
  83.         buySignal = True
  84.         sellSignal = False
  85.  
  86.         #your strategy logic here. Should be sufficent setting changing buySignal and sellSignal in order to trigger orders
  87.  
  88.         if not has_position and buySignal:
  89.             print("\n -------")
  90.             print(bcolors.OKGREEN + "BUY" + bcolors.ENDC + f" - [{data.symbol}]: {buy_value:.2f} at { current_price:.4f}")
  91.             print(f"portfolio: {portfolio_value:.3f}{quote_asset} - OPENPOS: {len(position_open)}")
  92.             order = order_market_value(symbol=data.symbol, value=buy_value)
  93.             if trailingEnabled:
  94.                 firstStopPrice = current_price-(current_price*trailingPerc)/100
  95.                 order_trailing_iftouched_amount(symbol=data.symbol, amount=-subtract_order_fees(order.quantity), trailing_percent= trailingPerc/100, stop_price=firstStopPrice)
  96.                 print(f"TS order created - {-order.quantity}  at {firstStopPrice} ({trailingPerc}%)")
  97.             elif stopLossEnabled or takeProfitEnabled:
  98.                 with OrderScope.one_cancels_others():
  99.                     if stopLossEnabled:
  100.                         stopLossPrice = current_price - (atr[-1]*stopLossAtrMult)
  101.                         stopLossOrder = order_iftouched_market_amount(data.symbol,amount=-subtract_order_fees(order.quantity),stop_price=stopLossPrice)
  102.                         stopLossPerc = ((current_price-stopLossPrice)/current_price)*100
  103.                         print(f"[{data.symbol}] - Stop loss order created at {stopLossPrice} ({stopLossPerc:.2f}%)")
  104.                     if takeProfitEnabled:
  105.                         takeProfitPrice = current_price + (atr[-1]*takeProfitAtrMult)
  106.                         takeProfitOrder = order_iftouched_market_amount(data.symbol,amount=-subtract_order_fees(order.quantity),stop_price=takeProfitPrice)
  107.                         takeProfitPerc = ((takeProfitPrice - current_price)/current_price)*100
  108.                         print(f"[{data.symbol}] - Take profit order created at {takeProfitPrice} ({takeProfitPerc:.2f}%)")
  109.         elif has_position and sellSignal:
  110.             print("\n -------")
  111.             print(bcolors.FAIL + "SELL" + bcolors.ENDC + f" - [{data.symbol}]: {current_price:.4f}")
  112.             print(f"portfolio: {portfolio_value:.3f}{quote_asset} - OPENPOS: {len(position_open)}")
  113.             close_position(data.symbol)
  114.  
  115.  
  116.      
  117.         # 5) Check strategy profitability
  118.         #     > print information profitability on every offsetting trade
  119.        
  120.         if state.number_offset_trades < portfolio.number_of_offsetting_trades:
  121.            
  122.             pnl = query_portfolio_pnl()
  123.             profitability = query_portfolio_profitablity()
  124.            
  125.             # print(f"Profitability: {profitability}")
  126.             print(f"Accumulated Pnl of Strategy: {pnl}")
  127.            
  128.             offset_trades = portfolio.number_of_offsetting_trades
  129.             number_winners = portfolio.number_of_winning_trades
  130.             winrate = (number_winners/offset_trades) *100
  131.  
  132.             print(f"Win Rate: {winrate:.2f}% ({number_winners}/{offset_trades})" )
  133.             print(f"Best trade Return : {portfolio.best_trade_return:.2%} - {profitability.bestTradePnl:.2f}")
  134.             print(f"Worst trade Return : {portfolio.worst_trade_return:.2%} - {profitability.worstTradePnl:.2f}")
  135.             print(f"Average Profit per Winning Trade : {portfolio.average_profit_per_winning_trade:.2f}")
  136.             print(f"Average Loss per Losing Trade : {portfolio.average_loss_per_losing_trade:.2f}")
  137.             # reset number offset trades
  138.             state.number_offset_trades = portfolio.number_of_offsetting_trades
  139.             print("------- \n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement