Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. Taewoo Kim
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    T
    • Profile
    • Following 0
    • Followers 2
    • Topics 26
    • Posts 75
    • Best 2
    • Groups 0

    Taewoo Kim

    @Taewoo Kim

    2
    Reputation
    1711
    Profile views
    75
    Posts
    2
    Followers
    0
    Following
    Joined Last Online

    Taewoo Kim Unfollow Follow

    Best posts made by Taewoo Kim

    • RE: How to Turn Bid/Ask Data into BT compatible data?

      Tried another method

      class BidAskCSV(btfeeds.GenericCSVData):
          linesoverride = True  # discard usual OHLC structure
          # datetime must be present and last
          lines = ('datetime', 'ask', 'bid' )
          # datetime (always 1st) and then the desired order for
          params = (
              # (datetime, 0), # inherited from parent class
              ('ask', 1),  # default field pos 1
              ('bid', 2),  # default field pos 2
      
      
          )
      
      
      
      data = BidAskCSV(dataname=args.data, dtformat=args.dtformat)
      

      But this one throws a different error:

      ValueError: time data '' does not match format '%Y-%m-%d %H:%M:%S'
      

      Does this have to do with the fact that Dukas data has nanoseconds and it's causing parsing issues?

      posted in General Code/Help
      T
      Taewoo Kim
    • RE: How to track orders? Kelly criterion sizers?

      You can keep the order instance returned by the different order-generation methods (buy, sell, close, order_target_xxx, buy_bracket) or later when the changes in status is notified to the strategy via notify_order

      The latter part I get. Let me explain

      in the tutorial

       if len(self) >= (self.bar_executed + 5):
                  # SELL, SELL, SELL!!! (with all possible default parameters)
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
      
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.sell()
      

      if I have multiple positions open that are using the same "strategy" (close after 5 bars) but opened at different times, how do I tell which order to sell?

      Unless the only way is to keep the orders in a list.. and iterate through the loop at every next().. which seems very inefficient.

      PS: thanks for being patient with my noob questions

      posted in General Code/Help
      T
      Taewoo Kim

    Latest posts made by Taewoo Kim

    • RE: Simultaneous bracket order - Cancel one when another has been submitted & accepted

      im having trouble having BT cancel one of the bracket orders when the other bracket order is converted into a position... here's what i've tried

      1. putting the order.cancel in order. accepted / submitted
      2. set exectype as bt.Order.StopLimit / bt.Order.Limit

      Still, all the orders are cancelling each other out simultaneously.

      Questions:

      1. When the "main" order of a bracket order is converted into a position, how is BT notified? via notify_order or notify_trade?
      2. Is there a sample code that achieves what I'm trying to do? I am trying to
      • place simultaeous long and short bracket order, both of which are X pips away
      • close one set of bracket orders when the other set of bracket orders (i.e. the main order of that other bracket order set) has been filled
      posted in General Code/Help
      T
      Taewoo Kim
    • RE: 3 Consecutive Highs / Low?

      @backtrader

      Will test it out. Thanks once again

      posted in Indicators/Strategies/Analyzers
      T
      Taewoo Kim
    • RE: 3 Consecutive Highs / Low?

      now that's elegant..
      thank you

      posted in Indicators/Strategies/Analyzers
      T
      Taewoo Kim
    • 3 Consecutive Highs / Low?

      I was doing peak detection but I just realized BT has a wide array of indicators that I am not too 100% familiar with.

      Is there an indicator that determines 3 consecutive highs (each higher than the previous)..?

      posted in Indicators/Strategies/Analyzers
      T
      Taewoo Kim
    • RE: Simultaneous bracket order - Cancel one when another has been submitted & accepted

      In any case the cancelling is donde at the wrong place. It's been done here

      if order.status in [order.Accepted]:
      

      Which only means the broker has accepted the order because there is enough cash to execute it.

      So where does this need to go? Which status?

      posted in General Code/Help
      T
      Taewoo Kim
    • RE: Forex Commission Scheme

      @ThatBlokeDave

      I just heard of it.. never actually listened to any of the podcasts. Im guessing there's lots of discretionary trading gurus trying to sell their shitty courses.

      posted in General Code/Help
      T
      Taewoo Kim
    • RE: Forex Commission Scheme

      @ThatBlokeDave

      This is great. Will test it out.

      BTW.. completely random but are you part of that bloke trading podcast?

      posted in General Code/Help
      T
      Taewoo Kim
    • RE: Simultaneous bracket order - Cancel one when another has been submitted & accepted

      Oh oops, sorry about that

      distance_sl = 0.0003
      distance_entry=0.0001
      distance_tp=0.0006
      

      I tried widening the values just to see if the volatility was triggering both... even up to:

      distance_sl = 0.00010
      distance_entry=0.0005
      distance_tp=0.0020
      

      But it seems that all the orders are getting bought/sold at exact same time

      [INFO] 14:21:32 [NOTIFY_ORDE] BUY ORDER EXECUTED [151], Size: 8814.339166956806, Price: 1.142125, Cost: 10067.077121060544, Comm 0.0
      [INFO] 14:21:32 [NOTIFY_ORDE] ORDER Completed - 0
      [INFO] 14:21:32 [NOTIFY_ORDER] SELL ORDER EXECUTED [154], Size: -8814.339166956806, Price: 1.142125, Cost: 10067.077121060544, Comm 0.0
      [INFO] 14:21:32 [NOTIFY_TRADE] OPERATION PROFIT, GROSS 0.00, NET 0.00
      [INFO] 14:21:32 [NOTIFY_TRADE] OPERATION PROFIT, GROSS 0.00, NET 0.00
      
      posted in General Code/Help
      T
      Taewoo Kim
    • Simultaneous bracket order - Cancel one when another has been submitted & accepted

      I'm trying to enter both a long and a short bracket order with target price, take profit, and stop loss... simultaneously

      For long: Limit order +1 pip from current price. Stop loss -1 pip from current price. And take profit of +5 pip of from current price.

      For short, exact reverse.

      Here's the picture
      for illustration

      When one of the two bracket orders get filled (at target price), i'd like to cancel the other one.

      Here's the logic for entering the 2 simultaneous orders:

      def next(self):
      
      
      	current_tick = {}
      	current_tick["close"]   = self.datas[0].close[0]
      	current_tick["volume"]  = self.datas[0].volume[0]
      	current_tick["date"]    = self.datas[0].datetime.date()
      	current_tick["time"]    = self.datas[0].datetime.time()
      
      	if(self.entrysig):
      
      		order_size =get_size(
      			currency_to_trade=self.p.currency,
      			leverage=self.p.leverage,
      			max_loss_per_trade=0.01,
      			total_cash=self.broker.get_cash(),
      			at_datetime =self.datas[0].datetime.datetime(0),
      			default_value = self.datas[0].close[0]
      		)
      
      		long_order = {
      		    "direction"       	: "long",
      		    "order_placed_at" 	: len(self),
      		    "order_placed_at_datetime" : current_tick["date"],
      		    "target_price"    	: self.datas[0].close + self.distance_entry,
      		    "take_profit"     	: self.datas[0].close + self.distance_tp,
      		    "stop_loss"       	: self.datas[0].close - self.distance_sl
      		    #"valid"			  	: terminate_order
      		}
      
      		long_bracket = {
      			"limitprice": float('%.4f' % long_order["take_profit"]),
      			"price"     : float('%.4f' % long_order["target_price"]), 
      			"stopprice" : float('%.4f' % long_order["stop_loss"]),
      			"addinfo"   : "long",
      			"size"      : order_size,
      			#"exectype"	: bt.Order.Market
      			#"valid"     : terminate_order
      		}
      
      		self.order_pairs["long"] = self.buy_bracket(**long_bracket)
      
      
      
      		short_order = {
      		    "direction"       	: "short",
      		    "order_placed_at" 	: len(self),
      		    "order_placed_at_datetime" : current_tick["date"],
      		    "target_price"    	: self.datas[0].close - self.distance_entry,
      		    "take_profit"     	: self.datas[0].close - self.distance_tp,
      		    "stop_loss"       	: self.datas[0].close + self.distance_sl
      		    #"valid"			  	: terminate_order
      		}
      
      		short_bracket = {
      			"limitprice": float('%.4f' % short_order["take_profit"]),
      			"price"     : float('%.4f' % short_order["target_price"]),
      			"stopprice" : float('%.4f' % short_order["stop_loss"]),
      			"addinfo"   : "short",
      			"size"      : order_size,
      			#"exectype"	: bt.Order.Market
      			#"valid"     : terminate_order
      		}
      
      		self.order_pairs["short"] = self.sell_bracket(**short_bracket)
      

      Here's the logic for cancelling the other

      def notify_order(self, order):
      
      
      	logging.info('[NOTIFY_ORDER {}] ORDER {} - {}'.format(len(self), order.Status[order.status], order.tradeid))
      
      	if order.status in [order.Submitted]:
      		# Buy/Sell order submitted/accepted to/by broker - Nothing to do
      		return
      
      
      	if order.status in [order.Accepted]:
      		# Buy/Sell order submitted/accepted to/by broker - Nothing to do			
      		self.total_played+=1
      		if(order.isbuy()):
      			self.went_long+=1
      		if(order.issell()):
      			self.went_short+=1
      
      		order_addinfo = dict(order.info)
      
      		if(order_addinfo["addinfo"] == "long"):
      			
      			if(self.order_pairs["short"] is not None):
      				for order in self.order_pairs["short"]:
      					self.cancel(order)
      				self.order_pairs["short"] = None
      
      		if(order_addinfo["addinfo"] == "short"):
      
      			if(self.order_pairs["long"] is not None):
      				for order in self.order_pairs["long"]:
      					self.cancel(order)
      				self.order_pairs["long"] = None
      
      
      		return
      
      	if order.status in [order.Expired, order.Cancelled, order.Rejected]:
      		
      		pass
      
      	if order.status in [order.Completed]:
      
      		order_type  = "buy" if( order.isbuy() ) else "sell"
      
      		logging.info('[NOTIFY_ORDER {}] {} ORDER EXECUTED [{}], Size: {}, Price: {}, Cost: {}, Comm {}'.format(
      			len(self),
      			order_type.upper(), 
      			order.ref,
      			order.executed.size,
      			order.executed.price,
      			order.executed.value,
      			order.executed.comm))
      

      For some reason, all the orders seem to be getting in but also getting out at exact same bar

      alt text

      Where am I going wrong?

      posted in General Code/Help
      T
      Taewoo Kim
    • RE: Why skip order.Margin status?

      Before i close off this thread.. do you see anything wrong with this syntax? Im getting zero trades...

      def __init__(self):
      
      	self.fast_ema = bt.ind.ExponentialMovingAverage(period=8, plotname="Fast EMA")
      	self.slow_ema = bt.ind.ExponentialMovingAverage(period=26, plotname="Slow EMA")		
      	self.stddev = bt.ind.StandardDeviation(period=8)	
      
      	self.regime = self.fast_ema - self.slow_ema    # Positive when bullish
      
      	self.buysig = bt.ind.And(
      				self.fast_ema > self.datas[0].close, 
      				self.datas[0].close >  self.slow_ema,
      				bt.ind.CrossUp(self.datas[0].close, self.fast_ema),
      				self.regime > 0
      			)
      
      	self.sellsig = bt.ind.And(
      				self.fast_ema < self.datas[0].close,
      				self.datas[0].close <  self.slow_ema,
      				bt.ind.CrossDown(self.datas[0].close, self.fast_ema),
      				self.regime < 0
      			)
      	self.order = None
      
      posted in General Code/Help
      T
      Taewoo Kim