programmatically add line item of commerce_discount type to order I want to programmatically add line item of commerce_doscount type to my order, I test below code,it is correctly add a record to line items array but not show in  order list even I refresh the order I dont see anything in order table .

$amount = trim($amount);
  $basePrice = commerce_price_field_data_auto_creation();
  $basePrice['amount'] = $amount;
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
if ($amount) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
     $line_item = entity_create('commerce_line_item', array(
    'type' =&gt; 'commerce_discount',
    'line_item_label' =&gt; 'my test',
    'quantity' =&gt; 1,
));
    // Wrap the line item and product to easily set field information.
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
// Set the unit price on the line item object.
$basePrice = commerce_price_field_data_auto_creation();
$basePrice['amount'] = $amount;
  $line_item_wrapper-&gt;commerce_unit_price = $basePrice;
// Save the line item now so we get its ID.
  commerce_line_item_save($line_item);

      //  $line_item = commerce_line_item_save($line_item);
        // Add it to the order's line item reference value.
$order_wrapper-&gt;commerce_line_items[] = $line_item;
     //commerce_order_save($wrapper);
      commerce_order_save($order);
$order = commerce_order_load($order-&gt;order_id);

        // Recalculate discounts.
      //  ym($order);
        commerce_cart_order_refresh($order);


also I look at discount module and try below code

 module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');
   $amount = trim($amount);
  $basePrice = commerce_price_field_data_auto_creation();
  $basePrice['amount'] = $amount;
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  commerce_discount_add_line_item($order_wrapper,'commerce_discount',$basePrice);


but return me EntityMetadataWrapperException: Unable to get the data property commerce_total as the parent data structure is not set. in EntityStructureWrapper-&gt;getPropertyValue()
Don't reinvent the wheel, here. Discounts provides functions for apply discounts to orders: 

// Pass in an $order or $product that has been entity_metadata_wrapper()ed.
// And pass in a discount name.
commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, $discount_name);

// Same thing, but a percentage.
commerce_discount_percentage(EntityDrupalWrapper $wrapper, $discount_name);


If you must reinvent the wheel, use these functions as examples to guide what you are doing.