Skip to content
All library documents

Commodity Futures Spread Hedging with Python and Runtime Controls

Article FMZ digest · Author: 善

Summary

This teaching example demonstrates a two-contract commodity futures hedge that monitors the price difference between contracts A and B. It opens opposing positions when the spread exceeds a configured threshold, then closes them when the spread reaches a cover threshold. A task queue coordinates the two orders, while position state tracks which hedge direction is active. The example also adds a spread chart by building bars from price differences and plotting hedge and cover levels.

The article describes runtime controls for changing those thresholds and closing all positions through interactive commands. It presents code as a port of an earlier JavaScript strategy and shows a backtest image, but gives no quantitative performance analysis. The implementation is explicitly intended for learning and reference. Its simple state handling and order coordination are not accompanied by discussion of partial fills, execution risk, contract sizing, or robust failure recovery, so it should not be treated as a validated production strategy.

Key ideas

  • The strategy compares quotes for two futures contracts and opens opposing positions when their spread crosses a threshold.
  • It closes the hedge when the spread returns to a configured cover level.
  • A task queue is used to submit the two legs of each hedge.
  • Spread bars and threshold lines can be plotted to monitor the strategy.
  • Interactive commands can adjust thresholds or close positions while the strategy runs.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.